问:
Selecting an html node's text content with htmlparser2 in Node.js
I want to parse some html with htmlparser2 module for Node.js. My task is to find a precise element by its ID and extract its text content.

I have read the documentation (quite limited) and I know how to setup my parser with the onopentag function but it only gives access to the tag name and its attributes (I cannot see the text). The ontext function extracts all text nodes from the given html string, but ignores all markup.

So here's my code.

const htmlparser = require("htmlparser2");
const file = '
Some heading

Foobar
';

const parser = new htmlparser.Parser({
  onopentag: function(name, attribs){
    if (attribs.id === "heading1"){
      console.log(/*how to extract text so I can get "Some heading" here*/);
    }
  },

  ontext: function(text){
    console.log(text); // Some heading \n Foobar
  }
});

parser.parseComplete(file);
```

I expect the output of the function call to be 'Some heading'. I believe that there is some obvious solution but somehow it misses my mind.

Thank you.

答:
You can do it like this using the library you asked about:

```<code>const htmlparser = require('htmlparser2');
const domUtils = require('domutils');

const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';

var handler = new htmlparser.DomHandler(function(error, dom) {
  if (error) {
    console.log('Parsing had an error');
    return;
  } else {
    const item = domUtils.findOne(element => {
      const matches = element.attribs.id === 'heading1';
      return matches;
    }, dom);

    if (item) {
      console.log(item.children[0].data);
    }
  }
});

var parser = new htmlparser.Parser(handler);
parser.write(file);
parser.end();
</code>```

The output you will get is "Some Heading". However, you will, in my opinion, find it easier to just use a querying library that is meant for it. You of course, don't need to do this, but you can note how much simpler the following code is: How do I get an element name in cheerio with node.js

Cheerio OR a querySelector API such as https://www.npmjs.com/package/node-html-parser if you prefer the native query selectors is much more lean.

You can compare that code to something more lean, such as the node-html-parser which supports simply querying:

```<code>const { parse } = require('node-html-parser');

const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';
const root = parse(file);
const text = root.querySelector('#heading1').text;
console.log(text);
</code>```

Body:
I want to parse some html with htmlparser2 module for Node.js. My task is to find a precise element by its ID and extract its text content.

I have read the documentation (quite limited) and I know how to setup my parser with the onopentag function but it only gives access to the tag name and its attributes (I cannot see the text). The ontext function extracts all text nodes from the given html string, but ignores all markup.

So here's my code.

const htmlparser = require("htmlparser2");
const file = '
Some heading

Foobar
';

const parser = new htmlparser.Parser({
  onopentag: function(name, attribs){
    if (attribs.id === "heading1"){
      console.log(/*how to extract text so I can get "Some heading" here*/);
    }
  },

  ontext: function(text){
    console.log(text); // Some heading \n Foobar
  }
});

parser.parseComplete(file);

I expect the output of the function call to be 'Some heading'. I believe that there is some obvious solution but somehow it misses my mind.

Thank you.

Body:
You can do it like this using the library you asked about:

const htmlparser = require('htmlparser2');
const domUtils = require('domutils');

const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';

var handler = new htmlparser.DomHandler(function(error, dom) {
  if (error) {
    console.log('Parsing had an error');
    return;
  } else {
    const item = domUtils.findOne(element => {
      const matches = element.attribs.id === 'heading1';
      return matches;
    }, dom);

    if (item) {
      console.log(item.children[0].data);
    }
  }
});

var parser = new htmlparser.Parser(handler);
parser.write(file);
parser.end();

The output you will get is "Some Heading". However, you will, in my opinion, find it easier to just use a querying library that is meant for it. You of course, don't need to do this, but you can note how much simpler the following code is: How do I get an element name in cheerio with node.js

Cheerio OR a querySelector API such as https://www.npmjs.com/package/node-html-parser if you prefer the native query selectors is much more lean.

You can compare that code to something more lean, such as the node-html-parser which supports simply querying:

const { parse } = require('node-html-parser');

const file = '<h1 id="heading1">Some heading</h1><p>Foobar</p>';
const root = parse(file);
const text = root.querySelector('#heading1').text;
console.log(text);


来源: stackexchange

问:
how to change my grid view in horizontal view?
Hi now i am create thumbnails images.....but I wish to create images in horizontal view..
how to change my grid view in horizontal.....</p>

答:
You can use , HorizontalScrollView as parent layout and inside it use , ImagViews.

Or you can use GalleryView.

ContentLicense: CC BY-SA 3.0


问:
Secure way of storing 3rd party databases/APIs credentials through Laravel
I am working on a Laravel app that should allow the user to manually add integration to 3rd party APIs and databases. With APIs it's easy: you only need to store the token. But the user should also be able to add integration with their own databases like MySQL. For that I'll need to store a host, user, password, basically all of the credentials. The issue I'm having is finding a proper and secure way of storing those credentials.

I was thinking about storing all of the connections in a connections table, adding the credentials to a connection_parameters JSON type field (so there would be flexibility and different types of connections can be stored in the same table) and hiding the details using the $hidden property on the model. This would be a first step towards a secure way of storing them, but I'm not sure that's enough.

Do you have any suggestions or practices you've used that you can explain to me?

答:
I can see your main concern is to hide sensitive data from 3rd parties. What you are doing is already "ok" unless someone gets access to your database somehow. You may want to treat those fields the same way you treat users' passwords, since they also contain credentials.

One way would be to encrypt them before storing. Laravel comes with encryption/decryption out of the box https://laravel.com/docs/5.8/encryption.

Another solution is to store each user's credentials in a file and store the file in any directory but the public directory (e.g: /storage/connections). This way, only you can access those files. Each file could be named something like user_1234 1234 being the user ID. So it's easy to retrieve.

ContentLicense: CC BY-SA 4.0


问:
Is it a good idea to add a WebService Request inside a Custom View?
So I have lets say I have a requirement where whenever the specific button is pressed, I should call a webservice to send some logs.

This button is present for multiple screens, so I though why not place it inside a CustomView View and call the webservice from there?

Then I'll just add this custom view to the xml layout and I don't have to worry about a thing anymore. Is it a good idea?

If it's not can someone suggest a better solution? Thanks.

答:
I would suggest you to create a class let say RequestSender that a has string logs as params int the constructor .

And then you will create a method send() that trigger the sending process.

And anytime you want to send logs you will proceed as below :

```<code>RequestSender request = new RequestSender(string logs);
request.send();
</code>```

Body:
I would suggest you to create a class let say RequestSender that a has string logs as params int the constructor .

And then you will create a method send() that trigger the sending process.

And anytime you want to send logs you will proceed as below :

RequestSender request = new RequestSender(string logs);
request.send();


问:
RegEx for accessing a nested object
I have some JS objects and they each have a grandchild property called 'products'.

E.g. ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products

I would like to access the products array regardless of what the specific object out of the above it is.

Tried using regex:

```<code>var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];
</code>```

TypeError: ecom[(((("detail" | "add") | "remove") | "checkout") | "purchase")] is undefined

```<code>var ecomProducts = ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/]['products'];
</code>```

TypeError: ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/] is undefined

How can I access the nested grandchild 'products' object regardless of the parents name?

答:
You can simply loop through the ecom object and check for existence of following props detail','add','remove','checkout','purchase' on ecom object,

something like this

```<code>let outerKey = ['detail','add','remove','checkout','purchase']
let foundProducts = outerKey.reduce((op,inp) => {
      if(ecom[inp] && ecom[inp].products && ecom[inp].products.length){
      op.push(ecom[inp].products)
      }
     return op
},[])
</code>```

Tried using regex:

```<code>var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];
</code>```

No this is not regex this is just logical OR, so you always end with ecom['checkout']['products']

Title: RegEx for accessing a nested object

Body:
I have some JS objects and they each have a grandchild property called 'products'.

E.g. ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products

I would like to access the products array regardless of what the specific object out of the above it is.

Tried using regex:

var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];

TypeError: ecom[(((("detail" | "add") | "remove") | "checkout") | "purchase")] is undefined

var ecomProducts = ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/]['products'];

TypeError: ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/] is undefined

How can I access the nested grandchild 'products' object regardless of the parents name?

Body:
You can simply loop through the ecom object and check for existence of following props detail','add','remove','checkout','purchase' on ecom object,

something like this

let outerKey = ['detail','add','remove','checkout','purchase']
let foundProducts = outerKey.reduce((op,inp) => {
      if(ecom[inp] && ecom[inp].products && ecom[inp].products.length){
      op.push(ecom[inp].products)
      }
     return op
},[])

Tried using regex:

var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];

No this is not regex this is just logical OR, so you always end with ecom['checkout']['products']


问:
How to add string ( ' ) in array value on javascript
I have string value of input type=hidden like this:

```<code>A,B,C
</code>```

then i convert that string to array with .split()in javascript:

var menu = $('#title_list').val();
 var arrayMenu = menu.split(",");

and the results:

```<code>arrayMenu = ["A","B","C"]
</code>```

If i want to make that array value to be like this:

```<code>arrayMenu = ["'A'","'B'","'C'"]
</code>```

how to do it?

答:
You could almost certainly use a regular expression, but a reasonably straightforward way could be:</p>

```<code>for(var i = 0; i < arrayMenu.length; i++) {
   arrayMenu[i] = "'" + arrayMenu[i] + "'";
}
</code>```

Body:
I have string value of input type=hidden like this:

A,B,C

then i convert that string to array with .split()in javascript:

var menu = $('#title_list').val();
 var arrayMenu = menu.split(",");

and the results:

arrayMenu = ["A","B","C"]

If i want to make that array value to be like this:

arrayMenu = ["'A'","'B'","'C'"]

how to do it?

Body:
You could almost certainly use a regular expression, but a reasonably straightforward way could be:

for(var i = 0; i < arrayMenu.length; i++) {
   arrayMenu[i] = "'" + arrayMenu[i] + "'";
}


问:
How do I return the ancestors of an object with LINQ?
I have a District class that looks like this:

```<code>public class District
{
    public int Id { get; set; }
    public string Name { get; set; }
    public District Parent { get; set; }
    public IEnumerable<District> Ancestors { get { /* what goes here? */ } }
}
</code>```

I would like to be able to get a list of each District's ancestors. So if District "1.1.1" is a child of District "1.1", which is a child of District "1", getting Ancestors on District "1.1.1" would return a list that contains the District objects whose names are "1.1" and "1".

Does this involve the yield return statement (I never totally understood that)?
Can it be done in one line?

答:
Here is a generic extension method for obtaining the collection of ancestors for an object, based on the accepted answer :

```<code>static public IEnumerable<T> GetAncestors<T>(this T source, Func<T, T> parentOf)
{
    var Parent = parentOf(source);
    while (Parent != null)
    {
        yield return Parent;
        Parent = parentOf(Parent);
    }
}
</code>```

So I can use it for all hierarchies in my application :

```<code>public IEnumerable<District> Ancestors
{
    get
    {
        return this.GetAncestors(d => d.Parent);
    }
}
</code>```

Or expand all parent nodes of a given TreeView node...

```<code>Node.GetAncestors(node => node.Parent).ToList().ForEach(n => n.Expanded = true);
</code>```

It's really handy.

ContentLicense: CC BY-SA 2.5

Body:
I have a District class that looks like this:

public class District
{
    public int Id { get; set; }
    public string Name { get; set; }
    public District Parent { get; set; }
    public IEnumerable<District> Ancestors { get { /* what goes here? */ } }
}

I would like to be able to get a list of each District's ancestors. So if District "1.1.1" is a child of District "1.1", which is a child of District "1", getting Ancestors on District "1.1.1" would return a list that contains the District objects whose names are "1.1" and "1".

Does this involve the yield return statement (I never totally understood that)?
Can it be done in one line?

Body:
Here is a generic extension method for obtaining the collection of ancestors for an object, based on the accepted answer :

static public IEnumerable<T> GetAncestors<T>(this T source, Func<T, T> parentOf)
{
    var Parent = parentOf(source);
    while (Parent != null)
    {
        yield return Parent;
        Parent = parentOf(Parent);
    }
}

So I can use it for all hierarchies in my application :

public IEnumerable<District> Ancestors
{
    get
    {
        return this.GetAncestors(d => d.Parent);
    }
}

Or expand all parent nodes of a given TreeView node...

Node.GetAncestors(node => node.Parent).ToList().ForEach(n => n.Expanded = true);

It's really handy.


问:
pip: no module named _internal
I have a problem when I try to use pip in any way. I'm using Ubuntu 16.04.4

I should say that I've used it already, and I never had any problem, but starting today when I use any command I always get the same error (as an example using pip --upgrade).

```<code>Traceback (most recent call last):
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal import main
ImportError: No module named _internal
</code>```

I have tried doing sudo apt-get remove python-pip followed by sudo apt-get install python-pip but nothing changed.

答:
you can remove it first, and install again ,it will be ok.
for centos:</p>

```<code>yum remove python-pip
yum install python-pip
</code>```

Title: pip: no module named _internal

Body:
I have a problem when I try to use pip in any way. I'm using Ubuntu 16.04.4

I should say that I've used it already, and I never had any problem, but starting today when I use any command I always get the same error (as an example using pip --upgrade).

Traceback (most recent call last):
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal import main
ImportError: No module named _internal

I have tried doing sudo apt-get remove python-pip followed by sudo apt-get install python-pip but nothing changed.

Body:
you can remove it first, and install again ,it will be ok.
for centos:

yum remove python-pip
yum install python-pip


问:
Can't connect to twilsoc
I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

```<code>index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111
</code>```

Here is on the front end

```<code>    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }
</code>```

here is the server

```<code>app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);
</code>```

答:
Twilio developer evangelist here.

This actually looks like my code . This is good news, because it's from my post on how to proxy to an Express server with React so you can avoid CORS issues. If you are using my repo then you should be able to start both the server and the front end applications by running:

```<code>npm run dev
</code>```

Then you don't need to fetch from an absolute URL, instead you can just use:

```<code>fetch("/chat/token", {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  method: 'POST',
  body: `identity=${encodeURIComponent(this.props.username)}`
});
</code>```

And the webpack dev server will proxy the request through to the Express application.

Let me know if that helps at all.

Quick note on CORS

I noticed you're trying to pass the headers 'Access-Control-Allow-Origin': "*", 'Access-Control-Allow-Headers': "*" from your fetch request. However they are not request headers, but response headers. If you do need CORS headers then you need your Express server to return them as part of the response.

But as I said, the way I set up the code for this post should mean that you don't need CORS at all. So you shouldn't have to worry about this for now.

Title: Can't connect to twilsoc

Body:
I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111

Here is on the front end

    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }

here is the server

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);

Body:
Twilio developer evangelist here.

This actually looks like my code . This is good news, because it's from my post on how to proxy to an Express server with React so you can avoid CORS issues. If you are using my repo then you should be able to start both the server and the front end applications by running:

npm run dev

Then you don't need to fetch from an absolute URL, instead you can just use:

fetch("/chat/token", {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  method: 'POST',
  body: `identity=${encodeURIComponent(this.props.username)}`
});

And the webpack dev server will proxy the request through to the Express application.

Let me know if that helps at all.

Quick note on CORS

I noticed you're trying to pass the headers 'Access-Control-Allow-Origin': "*", 'Access-Control-Allow-Headers': "*" from your fetch request. However they are not request headers, but response headers. If you do need CORS headers then you need your Express server to return them as part of the response.

But as I said, the way I set up the code for this post should mean that you don't need CORS at all. So you shouldn't have to worry about this for now.


问:
How to set base url for rest in spring boot?
I'm trying to to mix mvc and rest in a single spring boot project.

I want to set base path for all rest controllers (eg. example.com/api)
in a single place (I don't want annotate each controller with @RequestMapping('api/products'), instead, just @RequestMapping('/products').

Mvc controllers should be accessible by example.com/whatever

Is it possible?

(I don't use spring data rest, just spring mvc)

答: worked    server.contextPath=/path</p>

Body: worked    server.contextPath=/path


问:
Calculate logarithm of factorial
Here are three methods to calculate logarithm of factorial N: lgN!
The first method uses recursion and store each recursive value in an array
The second method uses recursive without array
The third method uses FOR loop.

After some testing, the third method has best performance, then the second one, the first one has bad performance.

My question is why first method is worse than second one
and though the third method has best performance, its value is different to the others,there is anything wrong in it?

```<code>/**
 * method 1
 * calculate lgN! with recursion and keep every recursive value
     * in an array. It has bad performance, once n reached about 6000, it
     * will throw stackoverflow exception
 * @param a
 * @param n
 * @return
 */
private static double lgNFact1(double[] a ,int n){
    if(n==1)
        a[n-1]=0;
    else
        a[n-1]=Math.log(n) + lgNFact1(a,n-1);
    return a[n-1];
}

/**
 * Method 2 have a little better performance, in my case n can reach 10000!,than throws stackoverflow exception
 * @param n
 * @return
 */
private static double lgNFact2(int n) {
    if(n==1)
        return 0;
    return Math.log(n)+lgNFact2(n-1);
}
/**
     * Method 3, based on logarithm formula, we can use for loop to get lgN!
 * log5!=log5+log4+log3+log2+log1

 * @param n
 * @return
 */
private static double lgNFact3(int n) {
    double sum = 0;
    for(int i=1;i<=n;i++) {
        sum+=Math.log(n);
    }
    return sum;
}
</code>```

Below is test, when n equals 10, we can see the third one is different to above two cases

case1 n=10, result:15.104412573075518

case2 n= 10, result:15.104412573075518

case3 n=10, result:23.025850929940464

答: With the recursive solutions, each call to the function sets up memory locations for that function, hooks up metadata about the caller, etc. before it gets on with the calculation. The for loop simply calculates the value and is done. The first method has to handle copying an array in addition to a number, so it takes a bit longer.</p>

Title: Calculate logarithm of factorial

Body:
Here are three methods to calculate logarithm of factorial N: lgN!
The first method uses recursion and store each recursive value in an array
The second method uses recursive without array
The third method uses FOR loop.

After some testing, the third method has best performance, then the second one, the first one has bad performance.

My question is why first method is worse than second one
and though the third method has best performance, its value is different to the others,there is anything wrong in it?

/**
 * method 1
 * calculate lgN! with recursion and keep every recursive value
     * in an array. It has bad performance, once n reached about 6000, it
     * will throw stackoverflow exception
 * @param a
 * @param n
 * @return
 */
private static double lgNFact1(double[] a ,int n){
    if(n==1)
        a[n-1]=0;
    else
        a[n-1]=Math.log(n) + lgNFact1(a,n-1);
    return a[n-1];
}

/**
 * Method 2 have a little better performance, in my case n can reach 10000!,than throws stackoverflow exception
 * @param n
 * @return
 */
private static double lgNFact2(int n) {
    if(n==1)
        return 0;
    return Math.log(n)+lgNFact2(n-1);
}
/**
     * Method 3, based on logarithm formula, we can use for loop to get lgN!
 * log5!=log5+log4+log3+log2+log1

 * @param n
 * @return
 */
private static double lgNFact3(int n) {
    double sum = 0;
    for(int i=1;i<=n;i++) {
        sum+=Math.log(n);
    }
    return sum;
}

Below is test, when n equals 10, we can see the third one is different to above two cases

case1 n=10, result:15.104412573075518

case2 n= 10, result:15.104412573075518

case3 n=10, result:23.025850929940464


问:
Synchronizing Applications
I have a standalone network device. It needs to be reworked to function as part of a geographically distributed group of these devices.  Synchronization between devices in the group need not occur frequently, not more than hourly.  The application is rails with SQLite.

Mainly, we want to keep certain pieces of information collected on these devices in sync.  Because of the deployment, it isn't feasible to add a large database cluster.

I have been considering CouchDB since replication and handling conflicts resulting from replication is a strong suit of its.

What do you think of CouchDB as a mechanism to keep distributed network devices synchronized?  Any thoughts or suggestions for an alternative approach?

答:
CouchDB is fine. You might have some alternatives with Unix tools.

The simplest key/value database is files in a filesystem. They work great. If you only need key/value storage with basic replication, then rsync can do that. If your conflict resolution policy is, for example, always take the latest timestamped data, then you might get away with rsync.

First of all, you're probably running Unix/Linux. SSH and rsync will be included, unlike CouchDB.

Another advantage of rsync (actually its SSH tunnel) is of course identification, authentication, and authorization. Your device is presumably Unix/Linux, and there are a million ways to wire up Unix authorization. It's not a guarantee but nearly anything is doable: password files, NIS, LDAP, Kerberos, Samba/Active Directory. The list goes on.

With Couch you will have to figure out some kind of user management system.

Will you use oauth?

Will you have to write an authentication plugin?

Will you also replicate the _users database around? What about conflicts in the _users database?

Do you instead have a central _users database? How can you have a central users database if you can't have a central data database?

Couch, like MySQL, is a full-blown server. It will maintenance load that rsync won't.

Remember to compact your databases, compact your views, and run view cleanup

Remember to rotate the log files

Possibly back up your .couch files and your .ini config

In other words, can you do a quick and dirty rsync hack, or do you need the full Couch package?

CouchDB is a uniform, consistent platform regardless of OS. That can be good or bad. Not knowing your specifics, I would guess that rsync over SSH is the best short-term, but Couch is the best long-term. (But with so many software projects, long-term never seems to arrive.)

Title: Synchronizing Applications


问:
cumulative sum by ID with lag
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

```<code>   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160
</code>```

This is what I've tried:

```<code>  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)
</code>```

答:
Here is an option in base R

```<code>df$Sum <- with(df, ave(amount, id, FUN = cumsum) - amount)
df$Sum
#[1]   0 100 120   0  60 270 160
</code>```

Or by removing the last observation, take the cumsum

```<code>with(df, ave(amount, id, FUN  = function(x) c(0, cumsum(x[-length(x)]))))
</code>```

Title: cumulative sum by ID with lag

Body:
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160

This is what I've tried:

  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)

Body:
Here is an option in base R

df$Sum <- with(df, ave(amount, id, FUN = cumsum) - amount)
df$Sum
#[1]   0 100 120   0  60 270 160

Or by removing the last observation, take the cumsum

with(df, ave(amount, id, FUN  = function(x) c(0, cumsum(x[-length(x)]))))


答:
You can just map the values of the array. Assuming you have the following:

let arrayMenu = ['A', 'B', 'C']
arrayMenu = arrayMenu.map((item) => `'${item}'`);
console.log(arrayMenu);```

Title: How to add string ( ' ) in array value on javascript


问:
Package get stored in Temporary file
when i install package in RStudio it gets stored in temporary folder and i cannot load it to the working space. Can anyone help me solve this problem.

The downloaded source packages are in
    ‘/tmp/RtmpFuUEEd/downloaded_packages’

答:
If you go to the Packages tab in the same panel that has the Plots and Help tab (ctrl-7 on windows) you can press Install at the top left, and then specify where the files get saved on the third input box "Install to Library:".

Hope that helps, but let me know if you need more specification.

Title: Package get stored in Temporary file


问:
Use filename as argument in bash alias, with default if it doesn't exist
I'm trying to create an alias for a command that has an argument which can either be a filename or a string:

```<code>command --style filename.style
</code>```

OR

```<code>command --style "fixed"
</code>```

Is there a way to combine this into a one-liner where I have the style parameter defined with something like:

```<code>command --style {`find . -name "filename.style"` || "fixed"}
</code>```

答:
Aliases aren't as good a choice as functions here, since they don't have branching logic support (without jumping through hoops that basically have you assigning a function anyhow). Better to just make the code a function directly:

```<code>foostyle() {
  if [[ -e filename.style ]]; then
    foo --style filename.style "$@"
  else
    foo --style fixed "$@"
  fi
}
</code>```

...will make foostyle whatever run foo --style filename.style whatever if filename.style exists in the current working directory, or foo --style fixed whatever otherwise.

As far as I can tell, that's what you're asking for.

Body:
I'm trying to create an alias for a command that has an argument which can either be a filename or a string:

command --style filename.style

OR

command --style "fixed"

Is there a way to combine this into a one-liner where I have the style parameter defined with something like:

command --style {`find . -name "filename.style"` || "fixed"}

Body:
Aliases aren't as good a choice as functions here, since they don't have branching logic support (without jumping through hoops that basically have you assigning a function anyhow). Better to just make the code a function directly:

foostyle() {
  if [[ -e filename.style ]]; then
    foo --style filename.style "$@"
  else
    foo --style fixed "$@"
  fi
}

...will make foostyle whatever run foo --style filename.style whatever if filename.style exists in the current working directory, or foo --style fixed whatever otherwise.

As far as I can tell, that's what you're asking for.


问:
How to fit contents perfectly under the flex property?
I have 2 containers that called .grid.left and .grid.right. Each .grids, especially .grid.left has some images dynamical ways and those.grids are wrapped by another div called .gallery.

The problem is when I give margin each of the image boxes, the browser makes a little gaps inside of the .gallery like this:

My expectation is to get rid of that gaps from my .gallery and to make the images fit completely no matter how much I set the margins on the images.

I intended to give the margins for the gallery looking better. I want to remain those margins and expand the .grid.right's image only to fit between the image and the .outer div.

Are there any proper ways to resolve this problem?

CodePen

Snippets:

* {
  margin: 0;
  padding: 0;
}

div,
section {
  position: relative;
}

.gallery {
  width: 1200px;
  height: 100%;
  border: 1px solid black;
  box-sizing: border-box;
}

.article {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: row;
  align-items: center;
}

.grid {
  height: 100%;
}

.left {
  width: 60%;
}

.inset-contents {
  width: 100%;
  height: 50%;
}

.top {
  margin-bottom: 1rem;
  background-image: url('https://imgur.com/3ozQvk9.jpg');
  padding-bottom: 50%;
}

.bottom {
  display: flex;
  flex-flow: row;
}

.inner-contents {
  width: 50%;
}

.first {
  background-image: url('https://imgur.com/tOMRVDi.jpg');
  padding-bottom: 50%;
  margin-right: .5rem;
}

.second {
  background-image: url('https://imgur.com/4oewNdx.jpg');
  padding-bottom: 50%;
  margin-left: .5rem;
}

.right {
  width: 40%;
  background-image: url('https://imgur.com/7gB1jHR.jpg');
  padding-bottom: 60%;
  align-content: stretch;
  margin-left: 1rem;
}

.img {
  display: block;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gallery">
  <div class="article">
    <div class="grid left">

      <div class="inset-contents bottom">

      </div>
    </div>

  </div>
</div></code>```

答:
hello If I'm correct you just want to get rid of the gap and wants to expand the images.
You may check this one.

          * {
            margin: 0 auto;
            padding: 0 auto;
          }
          div, section {
            position: relative;
          }
          .gallery {
            width: 1200px;
            height: 100%;
            border: 1px solid black;
            box-sizing: border-box;
          }
          .article {
            width: 100%;
            height: 100%;
            display: flex;
            flex-flow: row;
            align-items: center;
          }
          .grid {
            height: 100%;
          }
          .left {
            width: 60%;
          }
          .inset-contents {
            width: 100%;
            height: 50%;
          }
          .top {

            background-image: url('https://imgur.com/3ozQvk9.jpg');
            padding-bottom: 50%;
          }
          .bottom {
            display: flex;
            flex-flow: row;
          }
          .inner-contents {
            width: 50%;
          }
          .first {
            background-image: url('https://imgur.com/tOMRVDi.jpg');
            padding-bottom: 50%;

          }
          .second {
            background-image: url('https://imgur.com/4oewNdx.jpg');
            padding-bottom: 50%;

          }
          .right {
            width: 40%;
            background-image: url('https://imgur.com/7gB1jHR.jpg');
            padding-bottom: 60%;
            align-content: stretch;

          }
          .img {
            display: block;
            background-repeat: no-repeat;
            background-size: cover;
            background-position: center center;
          }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div class="gallery">
          <div class="article">
            <div class="grid left">

              <div class="inset-contents bottom">

              </div>
            </div>

          </div>
        </div></code>```

You just need to remove all margin that you put in the .gallery child.

Body:
hello If I'm correct you just want to get rid of the gap and wants to expand the images.
You may check this one.

          * {
            margin: 0 auto;
            padding: 0 auto;
          }
          div, section {
            position: relative;
          }
          .gallery {
            width: 1200px;
            height: 100%;
            border: 1px solid black;
            box-sizing: border-box;
          }
          .article {
            width: 100%;
            height: 100%;
            display: flex;
            flex-flow: row;
            align-items: center;
          }
          .grid {
            height: 100%;
          }
          .left {
            width: 60%;
          }
          .inset-contents {
            width: 100%;
            height: 50%;
          }
          .top {

            background-image: url('https://imgur.com/3ozQvk9.jpg');
            padding-bottom: 50%;
          }
          .bottom {
            display: flex;
            flex-flow: row;
          }
          .inner-contents {
            width: 50%;
          }
          .first {
            background-image: url('https://imgur.com/tOMRVDi.jpg');
            padding-bottom: 50%;

          }
          .second {
            background-image: url('https://imgur.com/4oewNdx.jpg');
            padding-bottom: 50%;

          }
          .right {
            width: 40%;
            background-image: url('https://imgur.com/7gB1jHR.jpg');
            padding-bottom: 60%;
            align-content: stretch;

          }
          .img {
            display: block;
            background-repeat: no-repeat;
            background-size: cover;
            background-position: center center;
          }

        <div class="gallery">
          <div class="article">
            <div class="grid left">
              <a class="inset-contents top img"></a>
              <div class="inset-contents bottom">
                <a class="inner-contents first img"></a>
                <a class="inner-contents second img"></a>
              </div>
            </div>
            <a class="grid right img"></a>
          </div>
        </div>

You just need to remove all margin that you put in the .gallery child.


答:
const arrayMenu = ["A","B","C"];

const newArray = arrayMenu.map(arr => `'${arr}'`);

console.log(arrayMenu, newArray);

// Another Solution
arrayMenu.forEach((currentValue, index) => arrayMenu[index] = `'${currentValue}'`);

console.log(arrayMenu);```


问:
Can someone explain how this loop is printing this tuple?
I'm trying to understand the solutions to question 5 from pythonchallenge, but I don't understand how the for loop is printing that data from the tuple. The solution is from here

Data contains a list of tuples, eg. data = [[(' ', 95)], [(' ', 14), ('#', 5), (' ', 70), ('#', 5), (' ', 1) ...]]

for line in data:
    print("".join([k * v for k, v in line]))
```

What should be printed out is an ASCII graphic made up of '#'.

答:
This one is sneaky. It's a list of lists of tuples. The inner list is a row on the terminal, and each tuple is a character followed by the number of times that
character should be printed.

It looks like it's iterating through the list, and for each tuple,
printing out tuple[0] tuple[1]-times.

It prints '' 95 times, then '' 14 times, then '#' 5 times, etc, inserting newlines
inbetween each inner list.

Body:
I'm trying to understand the solutions to question 5 from pythonchallenge, but I don't understand how the for loop is printing that data from the tuple. The solution is from here

Data contains a list of tuples, eg. data = [[(' ', 95)], [(' ', 14), ('#', 5), (' ', 70), ('#', 5), (' ', 1) ...]]

for line in data:
    print("".join([k * v for k, v in line]))

What should be printed out is an ASCII graphic made up of '#'.


问:
pass index to child event listener in parent component in vuejs
I have a list of objects within a v-for loop:

```<code><div v-for="(element, index) in myArray">
    <child @event-fired="handleEvent(index, dataFromChild)"></child>
</div>
</code>```

Now I want once the event is fired from the child component, on my handleEvent method, pass the index and the data from the child component.

But now, if I do something like stated above,I get an error on console stating, property or method dataFromChild is not defined....

答:
Just pass everything into your event handler as a single object.

    <child @event-fired="data => handleEvent({ index, data })"></child>

```

<p>Then, in your event handler, you can destructure it:</p>

```handleEvent({ index, data }) {
    // handle the event
}
```

Body:
I have a list of objects within a v-for loop:

    <child @event-fired="handleEvent(index, dataFromChild)"></child>

Now I want once the event is fired from the child component, on my handleEvent method, pass the index and the data from the child component.

But now, if I do something like stated above,I get an error on console stating, property or method dataFromChild is not defined....

Body:
Just pass everything into your event handler as a single object.

<div v-for="(element, index) in myArray">
    <child @event-fired="data => handleEvent({ index, data })"></child>
</div>

Then, in your event handler, you can destructure it:

handleEvent({ index, data }) {
    // handle the event
}


问:
Mongoose - remove multiple documents in one function call
In documentation there's deleteMany() method

```<code>Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});
</code>```

I want to remove multiple documents that have one common property and the other property varies. Something like this:

Site.deleteMany({ userUID: uid, id: [10, 2, 3, 5]}, function(err) {}

What would be the correct syntax for this?

答:
Yes, $in is a perfect solution :

Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5] } }, function(err) {})

Body:
In documentation there's deleteMany() method

Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});

I want to remove multiple documents that have one common property and the other property varies. Something like this:

Site.deleteMany({ userUID: uid, id: [10, 2, 3, 5]}, function(err) {}

What would be the correct syntax for this?


答: Summed up: Method #1 is copying an array on the stack which takes time and memory and is why it caps out at 6000. Method 2 is recursive and thus is also capped out by how big the stack can grow. It has to spend time allocating memory for each recursive call. Method #3 doesn’t use recursive calls so doesn’t have to bloat the stack and doesn’t have to spend time pushing stack frames.</p>

Title: Calculate logarithm of factorial


问:
Confusion with pouch-transform encryption and replication
My goal is to assure that all data in remote couch db will be encrypted. When I follow this example from pouch-transform docs, my data is not encrypted on remote end point after sync,

```<code>pouch.transform({
      incoming: function (doc) {
        encrypt(doc);
      },
      outgoing: function (doc) {
        decrypt(doc);
      }
    });
</code>```

when I encrypt in outgoing it does, but in this case my data encrypted locally as well. What I'm doing wrong here, isn't the point of encryption to have data encrypted in remote db? So the only way to achieve this will be to create set/get wrappers and encrypt in them? Can I detect somehow document destination in outgoing call?

答:
I've got the problem too. I do not wanna transform the data when replicating, so I've hacked in and added a replicating flag to pass through wrappered functions when replication: https://github.com/pouchdb/pouchdb/pull/7774

And modified the pouch-transform pacakge to pass the option to the outcoming callback:

```<code>{
  // decrypt it here.
  outgoing: async (doc, args: IPouchDBWrapperArgs, type: TransformPouchType) => {
    const {options} = args;
    if (!options.replicating) {
      doc = await this.decryptDoc(doc, options);
    }
    return doc;
  },
};

</code>```

Body:
My goal is to assure that all data in remote couch db will be encrypted. When I follow this example from pouch-transform docs, my data is not encrypted on remote end point after sync,

pouch.transform({
      incoming: function (doc) {
        encrypt(doc);
      },
      outgoing: function (doc) {
        decrypt(doc);
      }
    });

when I encrypt in outgoing it does, but in this case my data encrypted locally as well. What I'm doing wrong here, isn't the point of encryption to have data encrypted in remote db? So the only way to achieve this will be to create set/get wrappers and encrypt in them? Can I detect somehow document destination in outgoing call?

Body:
I've got the problem too. I do not wanna transform the data when replicating, so I've hacked in and added a replicating flag to pass through wrappered functions when replication: https://github.com/pouchdb/pouchdb/pull/7774

And modified the pouch-transform pacakge to pass the option to the outcoming callback:

{
  // decrypt it here.
  outgoing: async (doc, args: IPouchDBWrapperArgs, type: TransformPouchType) => {
    const {options} = args;
    if (!options.replicating) {
      doc = await this.decryptDoc(doc, options);
    }
    return doc;
  },
};


答:
```<code>arrayMenu.forEach((v, i) => arrayMenu[i] = "'"+v+"'");
</code>```

Body:
I have string value of input type=hidden like this:

A,B,C

then i convert that string to array with .split()in javascript:

var menu = $('#title_list').val();
 var arrayMenu = menu.split(",");

and the results:

arrayMenu = ["A","B","C"]

If i want to make that array value to be like this:

arrayMenu = ["'A'","'B'","'C'"]

how to do it?


问:
Kohana 3: has_many and order_by
How can i order a query that uses the has_many association in Kohana 3?</p>

答: Have you tried something like $model->items->order_by('fieldname')->find_all()? __get() method returns Query_Builder object, not a Database_Result, so you can add QBuilder's conditions (where/order_by/etc) for your needs.

Title: Kohana 3: has_many and order_by


答:
You can bind an arrow function expression in your event handler. For example

<child @event-fired="dataFromChild => handleEvent(index, dataFromChild)"/>
```

JSFiddle demo (from the Vue boilerplate) ~ https://jsfiddle.net/zmxksv35/

Title: pass index to child event listener in parent component in vuejs

Body:
You can bind an arrow function expression in your event handler. For example

<child @event-fired="dataFromChild => handleEvent(index, dataFromChild)"/>

JSFiddle demo (from the Vue boilerplate) ~ https://jsfiddle.net/zmxksv35/


问:
How do I fix the include_next of stdlib.h from cstdlib?
I'm building the Retargetable Decompiler (RetDec for short), and am coming across this error:

```<code>In file included from /usr/local/include/c++/8.2.0/ext/string_conversions.h:41,
                 from /usr/local/include/c++/8.2.0/bits/basic_string.h:6391,
                 from /usr/local/include/c++/8.2.0/string:52,
                 from /usr/local/include/c++/8.2.0/stdexcept:39,
                 from /usr/local/include/c++/8.2.0/array:39,
                 from /usr/local/include/c++/8.2.0/tuple:39,
                 from /usr/local/include/c++/8.2.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.2.0/memory:80,
                 from /home/chronos/user/Downloads/git/retdec/build/external/src/yaramod-project/include/yaramod/builder/yara_expression_builder.h:9,
                 from /home/chronos/user/Downloads/git/retdec/build/external/src/yaramod-project/src/builder/yara_expression_builder.cpp:7:
/usr/local/include/c++/8.2.0/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>
               ^~~~~~~~~~
compilation terminated.
make[5]: *** [src/CMakeFiles/yaramod.dir/build.make:74: src/CMakeFiles/yaramod.dir/builder/yara_expression_builder.cpp.o] Error 1
make[4]: *** [CMakeFiles/Makefile2:109: src/CMakeFiles/yaramod.dir/all] Error 2
make[3]: *** [Makefile:130: all] Error 2
</code>```

I've dealt with this error before and have solved it, however I cannot remember how exactly I did it.

How do I fix this?

I've seen this question: Error compiling OpenCV, fatal error: stdlib.h: No such file or directory

The answers there do not help me.

答: Ah, I remember now: You have to replace the instances of -isystem <place where stdlib.h is> with -I <place where stdlib.h is>.

Body:
I'm building the Retargetable Decompiler (RetDec for short), and am coming across this error:

In file included from /usr/local/include/c++/8.2.0/ext/string_conversions.h:41,
                 from /usr/local/include/c++/8.2.0/bits/basic_string.h:6391,
                 from /usr/local/include/c++/8.2.0/string:52,
                 from /usr/local/include/c++/8.2.0/stdexcept:39,
                 from /usr/local/include/c++/8.2.0/array:39,
                 from /usr/local/include/c++/8.2.0/tuple:39,
                 from /usr/local/include/c++/8.2.0/bits/unique_ptr.h:37,
                 from /usr/local/include/c++/8.2.0/memory:80,
                 from /home/chronos/user/Downloads/git/retdec/build/external/src/yaramod-project/include/yaramod/builder/yara_expression_builder.h:9,
                 from /home/chronos/user/Downloads/git/retdec/build/external/src/yaramod-project/src/builder/yara_expression_builder.cpp:7:
/usr/local/include/c++/8.2.0/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>
               ^~~~~~~~~~
compilation terminated.
make[5]: *** [src/CMakeFiles/yaramod.dir/build.make:74: src/CMakeFiles/yaramod.dir/builder/yara_expression_builder.cpp.o] Error 1
make[4]: *** [CMakeFiles/Makefile2:109: src/CMakeFiles/yaramod.dir/all] Error 2
make[3]: *** [Makefile:130: all] Error 2

I've dealt with this error before and have solved it, however I cannot remember how exactly I did it.

How do I fix this?

I've seen this question: Error compiling OpenCV, fatal error: stdlib.h: No such file or directory

The answers there do not help me.


问:
How am I suppose to use mpfr::mpfr_fac_ui function?
I tried finding an example of how to use mpfr::mpfr_fac_ui over the internet but I was unable to, so I decided to ask here.

I have my own iterative factorial

```<code>boost::multiprecision::mpfr_float factorial(int start, int end)
{
    boost::multiprecision::mpfr_float fact = 1;

    for (; start <= end; ++start)
        fact *= start;

    return fact;
}
</code>```

but I want to try built-in factorial.

I don't know what I am doing wrong because when I am testing it like so

```<code>mpfr_t test;
mpfr_init2(test, 1000);

std::cout << mpfr_fac_ui(test, 5, MPFR_RNDN) << std::endl;
std::cout << factorial(1, 5) << std::endl;
</code>```

mpfr_fac_ui does not return any errors (returns 0) and test is 0 while it should be 120.

Am I doing something wrong or I am missing something?

答:
In C, I get 120 as expected with:

```<code>#include <stdio.h>
#include <mpfr.h>

int main (void)
{
  mpfr_t test;
  mpfr_init2 (test, 1000);
  mpfr_fac_ui (test, 5, MPFR_RNDN);
  mpfr_printf ("%Rg\n", test);
  mpfr_clear (test);
  return 0;
}
</code>```

In your program, you do not show how you print the value of test. All what you do is to print the return value of mpfr_fac_ui, which is 0.

Body:
I tried finding an example of how to use mpfr::mpfr_fac_ui over the internet but I was unable to, so I decided to ask here.

I have my own iterative factorial

boost::multiprecision::mpfr_float factorial(int start, int end)
{
    boost::multiprecision::mpfr_float fact = 1;

    for (; start <= end; ++start)
        fact *= start;

    return fact;
}

but I want to try built-in factorial.

I don't know what I am doing wrong because when I am testing it like so

mpfr_t test;
mpfr_init2(test, 1000);

std::cout << mpfr_fac_ui(test, 5, MPFR_RNDN) << std::endl;
std::cout << factorial(1, 5) << std::endl;

mpfr_fac_ui does not return any errors (returns 0) and test is 0 while it should be 120.

Am I doing something wrong or I am missing something?

Body:
In C, I get 120 as expected with:

#include <stdio.h>
#include <mpfr.h>

int main (void)
{
  mpfr_t test;
  mpfr_init2 (test, 1000);
  mpfr_fac_ui (test, 5, MPFR_RNDN);
  mpfr_printf ("%Rg\n", test);
  mpfr_clear (test);
  return 0;
}

In your program, you do not show how you print the value of test. All what you do is to print the return value of mpfr_fac_ui, which is 0.


问:
Zend_Form Jquery & fileUploadErrorIniSize
Edit, I fixed it by changing my JS to:

```<code>$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
    data[$(this).attr('name')] = $(this).val();
});
</code>```

Hello,

As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.

However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.

TPL For Forms:

```<code><?php $this->headScript()->captureStart(); ?>

$(function() {

    $('.zend_form input, .zend_form textarea').blur(function() {
        var formElementId = ($(this).parent().prev().find('label').attr('for'));
        doValidation(formElementId);
    });
});

function doValidation(id) {

    var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
    var data = {};

    $('.zend_form input, .zend_form textarea').each(function() {
        data[$(this).attr('name')] = $(this).val();
    });

    $.post(url, data, function(resp) {
        $('#'+id).parent().find('.errors').remove();
        $('#'+id).parent().append(getErrorHtml(resp[id], id));
    }, 'json');

};

function getErrorHtml(formErrors, id) {

    var o = '';
    if (formErrors != null) {
    var o = '<ul id="errors-'+id+'" class="errors">';

    for (errorKey in formErrors) {
        o += '<li>'+formErrors[errorKey]+'</li>';
    }
    o += '</ul>';
    }
    return o;
}

<?php $this->headScript()->captureEnd(); ?>

<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
    echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>

<?php if (isset($this->errorMsg)) { ?>
    <p><?php echo $this->errorMsg; ?></p>
<?php } ?>

<?php echo $this->form; ?>
</code>```

Which is directed to

```<code><?php

class Administration_JsonController extends Zend_Controller_Action {

    public function validateformAction() {

        $form_name  = $this->_getParam('form_name');
        $form       = new $form_name();
        $data       = $this->_getAllParams();

        $form->isValidPartial($data);
        $json = $form->getMessages();
        $this->_helper->json($json);
    }

}
</code>```

Example of returned json:

```<code>{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}
</code>```

I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed

```<code>$form->isValid($data);
</code>```

to

```<code>$form->isValidPartial($data);
</code>```

but it didn't fix this issue.

Any ideas?

答:
Are you putting an Encrypt type on your form?

I have found two different forum posts about this, including a stack post:

odd Zend_Form_Element_File behavior

You need to add enctype="multipart/form-data" to your form tag.

Basically what is happening is the form is using its default "application/x-www-form-urlencoded" method of encryption before it is sent to the server. File uploading is not supported with this method.

Body:
Edit, I fixed it by changing my JS to:

$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
    data[$(this).attr('name')] = $(this).val();
});

Hello,

As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.

However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.

TPL For Forms:

<?php $this->headScript()->captureStart(); ?>

$(function() {

    $('.zend_form input, .zend_form textarea').blur(function() {
        var formElementId = ($(this).parent().prev().find('label').attr('for'));
        doValidation(formElementId);
    });
});

function doValidation(id) {

    var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
    var data = {};

    $('.zend_form input, .zend_form textarea').each(function() {
        data[$(this).attr('name')] = $(this).val();
    });

    $.post(url, data, function(resp) {
        $('#'+id).parent().find('.errors').remove();
        $('#'+id).parent().append(getErrorHtml(resp[id], id));
    }, 'json');

};

function getErrorHtml(formErrors, id) {

    var o = '';
    if (formErrors != null) {
    var o = '
';

    for (errorKey in formErrors) {
        o += '
'+formErrors[errorKey]+'
';
    }
    o += '
';
    }
    return o;
}

<?php $this->headScript()->captureEnd(); ?>

<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
    echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>

<?php if (isset($this->errorMsg)) { ?>

<?php echo $this->errorMsg; ?>

<?php } ?>

<?php echo $this->form; ?>

Which is directed to

<?php

class Administration_JsonController extends Zend_Controller_Action {

    public function validateformAction() {

        $form_name  = $this->_getParam('form_name');
        $form       = new $form_name();
        $data       = $this->_getAllParams();

        $form->isValidPartial($data);
        $json = $form->getMessages();
        $this->_helper->json($json);
    }

}

Example of returned json:

{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}

I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed

$form->isValid($data);

to

$form->isValidPartial($data);

but it didn't fix this issue.

Any ideas?


问:
How come my string function does not return anything?
Either the function does not return anything or it returns an empty string. I am trying to erase everything before next sequence after the -e text in the string. For example, test -e test/file/path should return test/file/path without the space after -e. However, when the function does not return anything or it returns an empty string. I cannot find anything wrong with my function please help!

```<code>#include <iostream>
using namespace std;

string fileparse(string str) {
    int i;

    for (i = 0; i < str.size(); i++)
        if (str[i] == '-')
            i += 2; //to account for the space after 'e'
    str.erase(str.begin(), str.begin()+i);
    return str;
}

int main()
{

    string str = "test -e test/file/path";
    string vars = fileparse(str);
    cout << vars << endl; //blank
    return 0;
}
</code>```

答: You have to break out of the for loop because you are letting it finish and 'i' has been incrementing. Then when you reference 'i' it will delete the entire string.</p>

Body:
Either the function does not return anything or it returns an empty string. I am trying to erase everything before next sequence after the -e text in the string. For example, test -e test/file/path should return test/file/path without the space after -e. However, when the function does not return anything or it returns an empty string. I cannot find anything wrong with my function please help!

#include <iostream>
using namespace std;

string fileparse(string str) {
    int i;

    for (i = 0; i < str.size(); i++)
        if (str[i] == '-')
            i += 2; //to account for the space after 'e'
    str.erase(str.begin(), str.begin()+i);
    return str;
}

int main()
{

    string str = "test -e test/file/path";
    string vars = fileparse(str);
    cout << vars << endl; //blank
    return 0;
}


问:
django postgresql tests.py RuntimeWarning error
I have a Django app that adds and displays stuff to my postgresql database online at elephantsql.com. My project file setup looks like this:

```<code>website/
    website/
    music/
    playlist/
            __pycache__/
            migrations/
            static/
            templates/
            __init__.py
            admin.py
            apps.py
            models.py
            tests.py
            urls.py
            views.py
    .coverage
    db.sqlite3
    manage.py
</code>```

My project works right now where when I run the server and go to /playlist/ it displays stuff correctly and connects to my postgresql database fine.

My settings.py DATABASES object looks like this:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'kxvmghva',
        'USER': 'kxvmghva',
        'PASSWORD': '--an actual password---',
        'HOST': 'raja.db.elephantsql.com',
        'PORT': '5432',
    }
}
</code>```

Now I'm trying to write test cases in my playlist/tests.py file, but when I try to run these tests I'm getting errors.

my testing file I'm trying to run /playlist/tests.py

```<code>from django.test import TestCase
from .models import plays
from django.utils import timezone

class AnimalTestCase(TestCase):
    def setUp(self):
        print("setup")
        #Animal.objects.create(name="lion", sound="roar")
        #Animal.objects.create(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        print("test")
        #lion = Animal.objects.get(name="lion")
        #cat = Animal.objects.get(name="cat")
        #self.assertEqual(lion.speak(), 'The lion says "roar"')
        #self.assertEqual(cat.speak(), 'The cat says "meow"')
</code>```

When I run the command "python manage.py test playlist" I get these errors:

```<code>C:\Users\marti\Documents\kexp\website>python manage.py test playlist
Creating test database for alias 'default'...
C:\Python36-32\lib\site-packages\django\db\backends\postgresql\base.py:267: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead.
  RuntimeWarning
Got an error creating the test database: permission denied to create database

Type 'yes' if you would like to try deleting the test database 'test_kxvmghva', or 'no' to cancel:
</code>```

if I type 'yes' it leads to this error:

```<code>Destroying old test database for alias 'default'...
Got an error recreating the test database: database "test_kxvmghva" does not exist
</code>```

I've been trying to solve this error by searching it online and have tried stuff like giving my user 'kxvmghva' CREATEDB permissions as well as running this line in my elephantsql db:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO kxvmghva;

But I'm still getting these errors when trying to run the tests.py file for my playlist/ app. This is my first time setting up test cases for a postgresql database in django and I would really appreciate any help or guidance. Thanks.

答:
I suppose the plan you are using for database is free/shared, in case which you do not have rights to create additional databases.

This is not a Django problem but restrictions of the service you are using.

Body:
I have a Django app that adds and displays stuff to my postgresql database online at elephantsql.com. My project file setup looks like this:

website/
    website/
    music/
    playlist/
            __pycache__/
            migrations/
            static/
            templates/
            __init__.py
            admin.py
            apps.py
            models.py
            tests.py
            urls.py
            views.py
    .coverage
    db.sqlite3
    manage.py

My project works right now where when I run the server and go to /playlist/ it displays stuff correctly and connects to my postgresql database fine.

My settings.py DATABASES object looks like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'kxvmghva',
        'USER': 'kxvmghva',
        'PASSWORD': '--an actual password---',
        'HOST': 'raja.db.elephantsql.com',
        'PORT': '5432',
    }
}

Now I'm trying to write test cases in my playlist/tests.py file, but when I try to run these tests I'm getting errors.

my testing file I'm trying to run /playlist/tests.py

from django.test import TestCase
from .models import plays
from django.utils import timezone

class AnimalTestCase(TestCase):
    def setUp(self):
        print("setup")
        #Animal.objects.create(name="lion", sound="roar")
        #Animal.objects.create(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        print("test")
        #lion = Animal.objects.get(name="lion")
        #cat = Animal.objects.get(name="cat")
        #self.assertEqual(lion.speak(), 'The lion says "roar"')
        #self.assertEqual(cat.speak(), 'The cat says "meow"')

When I run the command "python manage.py test playlist" I get these errors:

C:\Users\marti\Documents\kexp\website>python manage.py test playlist
Creating test database for alias 'default'...
C:\Python36-32\lib\site-packages\django\db\backends\postgresql\base.py:267: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead.
  RuntimeWarning
Got an error creating the test database: permission denied to create database

Type 'yes' if you would like to try deleting the test database 'test_kxvmghva', or 'no' to cancel:

if I type 'yes' it leads to this error:

Destroying old test database for alias 'default'...
Got an error recreating the test database: database "test_kxvmghva" does not exist

I've been trying to solve this error by searching it online and have tried stuff like giving my user 'kxvmghva' CREATEDB permissions as well as running this line in my elephantsql db:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO kxvmghva;

But I'm still getting these errors when trying to run the tests.py file for my playlist/ app. This is my first time setting up test cases for a postgresql database in django and I would really appreciate any help or guidance. Thanks.


问:
Is it possible to directly assign the return value of a method to a variable?
In JavaScript, it's possible to do something along these lines:

var qwerty = (function() {
    //some code
    return returnValue;
}
```

<p>This would assign <em>returnValue</em> to <em>qwerty</em>. Is there any way to do something similar in Java? Something like:</p>

<pre class="lang-java prettyprint-override"><code>int num = {
    public int method() {
        //some code
        return val;
    }
}
</code>```

I understand that I could write out a separate method, but I'd like to do it in a way similar to above as it looks neater and cleaner in the code I'm writing.

答:
Because your function doesn't specify any parameters, you're most-likely looking for the IntSupplier functional interface:

```<code>IntSupplier supplier = () -> {
    int val = ...;
    //some code
    return val;
};

int num = supplier.getAsInt();
</code>```

If you really want to inline it, then you can use the following (which is unreadable, so I wouldn't recommend it):

```<code>int num = ((IntSupplier) () -> {
    int val = ...;
    //some code
    return val;
}).getAsInt();
</code>```

Because the above IntSupplier isn't stored in a variable, it's logically equivalent to the following:

```<code>int val = ...;
//some code
int num = val;
</code>```

Body:
In JavaScript, it's possible to do something along these lines:

var qwerty = (function() {
    //some code
    return returnValue;
}

This would assign returnValue to qwerty. Is there any way to do something similar in Java? Something like:

int num = {
    public int method() {
        //some code
        return val;
    }
}

I understand that I could write out a separate method, but I'd like to do it in a way similar to above as it looks neater and cleaner in the code I'm writing.

Body:
Because your function doesn't specify any parameters, you're most-likely looking for the IntSupplier functional interface:

IntSupplier supplier = () -> {
    int val = ...;
    //some code
    return val;
};

int num = supplier.getAsInt();

If you really want to inline it, then you can use the following (which is unreadable, so I wouldn't recommend it):

int num = ((IntSupplier) () -> {
    int val = ...;
    //some code
    return val;
}).getAsInt();

Because the above IntSupplier isn't stored in a variable, it's logically equivalent to the following:

int val = ...;
//some code
int num = val;


问:
Set Button Click handler with a DataTrigger
I'm trying to update some visual properties and the click handler on a button in response to the value of an enum. The visual properties are easy enough, but the click handler is giving me trouble.

The enum has 4 values: Launching, Launched, Terminating, Terminated. The button will launch or kill a process based on the current state. Here's what I have for the visual properties:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>
```

The problem is that Style.Triggers doesn't support EventSetter so I can't update Button.Click with this approach. Now, I could using a single click handler and branch based on the enum, but I want to understand what is possible from the XAML side.

I also tried creating 4 separate styles in Button.Resources then swapping out the styles with DataTrigger but then you end up trying to change the button style using a style and I'm not convinced that works either.

Is there a reasonable way to change Button.Click from XAML in response to a changing data value?

答:
Instead of EventSetter you can do

```<code><Setter Property="Command" Value="{Binding SomeCommand}"/>
</code>```

Actually if you want a button to be clickable only in one state of enum you can just bind to "SomeCommand" and create a command which is enabled only when particular enum type is selected.

for example

```<code><Button Command={Binding SomeCommand} >
   Style...
</Button>
</code>```

In a view model you can do

```<code>SomeCommand = new RelayCommand(SomeMethod, ()=> ProcessState == ProcessState.Terminated);
</code>```

Body:
I'm trying to update some visual properties and the click handler on a button in response to the value of an enum. The visual properties are easy enough, but the click handler is giving me trouble.

The enum has 4 values: Launching, Launched, Terminating, Terminated. The button will launch or kill a process based on the current state. Here's what I have for the visual properties:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

The problem is that Style.Triggers doesn't support EventSetter so I can't update Button.Click with this approach. Now, I could using a single click handler and branch based on the enum, but I want to understand what is possible from the XAML side.

I also tried creating 4 separate styles in Button.Resources then swapping out the styles with DataTrigger but then you end up trying to change the button style using a style and I'm not convinced that works either.

Is there a reasonable way to change Button.Click from XAML in response to a changing data value?

Body:
Instead of EventSetter you can do

<Setter Property="Command" Value="{Binding SomeCommand}"/>

Actually if you want a button to be clickable only in one state of enum you can just bind to "SomeCommand" and create a command which is enabled only when particular enum type is selected.

for example

<Button Command={Binding SomeCommand} >
   Style...
</Button>

In a view model you can do

SomeCommand = new RelayCommand(SomeMethod, ()=> ProcessState == ProcessState.Terminated);


问:
truncate or delete all data in table with NHibernate
with NHibernateSession.Delete(entity); i can delete entity. How can i truncate or delete all data in table with NHibernate.

i can do with HQL like: session.createQuery ( "truncate tablename"). ExecuteUpdate () but is there any other options?

答: Batch, data oriented operations are not really what NHibernate is intended for.  You could use session.createSQLQuery() and then just specify whatever SQL you would under normal situations.  However, you should consider whether you really need to use NHibernate for this particular task - it probably doesn't make sense to.</p>


问:
Why isnt my GPA method calculating properly after passing it the correct parameters?
Hey everyone Im trying to solve this JAVA homework for class and Ive been stuck for the better part of the afternoon trying to get my GPA constructor to provide me the correct result.

I need the output to be the name of the student and its GPA. Currently the First Name and Last Name are being printed correctly but for the GPA Ive been getting Null and just right now I seem to be getting just a reference for it.

This is my main class code

```<code>package assignment2;

/**
*
* @author javyc
*/
import java.text.NumberFormat;
import java.util.HashSet;
public class Assignment2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Classes[]courseArray = new Classes[2];
    courseArray[0] = new Classes("Javier", "Ruiz", "Winter 2018", 3);
    courseArray[1] = new Classes("Gabriela", "Ruiz", "Fall 2018", 3);

    double[] gpa = new double[2];
        gpa[0] = 4.00;
        gpa[1] = 4.00;

        Students ArizonaStudent = new Students("Javier", "Ruiz","MIS", "2020", courseArray, gpa);
        gpa = ArizonaStudent.getGpa();
        NumberFormat formatting = NumberFormat.getNumberInstance();
        formatting.setMaximumFractionDigits(2);

        System.out.println(ArizonaStudent.getStudentFirstName()+ " " + ArizonaStudent.getStudentLastName() + "" + gpa);
        //System.out.println(ArizonaStudent.getCourses(1));
}

}
</code>```

This is my Student class code

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assignment2;

/**
 *
 * @author javyc
*/
public class Students {
private String studentFirstName;
private String studentLastName;
private String department;
private String gradYear;

private Classes[] courses;
private double[] gpa1;

public Students(String studentFN, String studentLN, String dept, String graduationYear, Classes[]coursesList, double[]gpaList){
    studentFirstName = studentFN;
    studentLastName = studentLN;
    department = dept;
    gradYear = graduationYear;
    setCourses(coursesList);
    setGPA(gpaList);
}

public String getStudentFirstName(){
    return studentFirstName;
}
public String getStudentLastName(){
    return studentLastName;
}
public String getStudentDepartment(){
    return department;
}
public String getStudentGraduationYear(){
    return gradYear;
}
public Classes[]getCourses(){
    return courses;
}
public double[]getGpa(){
    return gpa1;
}

public void setStudentFirstName(String studentFN){
    studentFirstName = studentFN;
}
public void setStudentLastName(String studentLN){
    studentLastName = studentLN;
}
public void setDepartment(String department){
    this.department = department;
}
public void setGraduationYear(String gradYear){
    this.gradYear = gradYear;
}
public void setCourses(Classes[]courses){
    this.courses=courses;
}
public void setGPA(double[]gpa1){
    this.gpa1=gpa1;
}
 public class GPA{
public double gradePointAverage(){
    int totalCreds = 0;
    double gpaTotal = 0.0;
    for (int i = 0; i<courses.length;i++){
        totalCreds += courses[i].getCredits();
        gpaTotal += courses[i].getCredits()* gpa1[i];
        return gpaTotal = gpaTotal/totalCreds;
    }
    return gpaTotal = gpaTotal/totalCreds;
}
}
}
</code>```

This is my classes code

```<code>/*
 * To change this license header, choose License Headers in Project     Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assignment2;

/**
 *
 * @author javyc
 */
public class Classes {
//We will start by declaring the attributes of the Classes offered at UA
private String professorFirstName;
private String professorLastName;
private String semesterOffered;
private int creditTotal = 0;

public Classes(String profMainName, String profLastName, String semester, int credits)
    {
    professorFirstName = profMainName;
    professorLastName = profLastName;
    semesterOffered = semester;
    creditTotal = credits;
    }
public String returnFirstName(){
    return professorFirstName;
}
public String returnLastName(){
    return professorLastName;
}
public String returnSemester(){
    return semesterOffered;
}
public int getCredits(){
    return creditTotal;
}
public void establishedSemester(String semesterOffered){
    this.semesterOffered = semesterOffered;
}
public void establishFirstName(String professorFirstName){
    this.professorFirstName = professorFirstName;
}
public void establishLastName(String professorLastName){
    this.professorLastName = professorLastName;
}
public void establishCredits(Integer creditTotal){
    this.creditTotal = creditTotal;
}

}
</code>```

答:
There are a couple design issues.  I'm not sure what the original assignment requirements were, but is your class supposed to be Student or Students?  Student objects would then each represent a SINGLE student.  So, shouldn't that student just have a single GPA?

If you're setting the GPA for a student, I would assume you should pass the object's setGPA method a double, not a double array.  Does this make sense?

Body:
Hey everyone Im trying to solve this JAVA homework for class and Ive been stuck for the better part of the afternoon trying to get my GPA constructor to provide me the correct result.

I need the output to be the name of the student and its GPA. Currently the First Name and Last Name are being printed correctly but for the GPA Ive been getting Null and just right now I seem to be getting just a reference for it.

This is my main class code

package assignment2;

/**
*
* @author javyc
*/
import java.text.NumberFormat;
import java.util.HashSet;
public class Assignment2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Classes[]courseArray = new Classes[2];
    courseArray[0] = new Classes("Javier", "Ruiz", "Winter 2018", 3);
    courseArray[1] = new Classes("Gabriela", "Ruiz", "Fall 2018", 3);

    double[] gpa = new double[2];
        gpa[0] = 4.00;
        gpa[1] = 4.00;

        Students ArizonaStudent = new Students("Javier", "Ruiz","MIS", "2020", courseArray, gpa);
        gpa = ArizonaStudent.getGpa();
        NumberFormat formatting = NumberFormat.getNumberInstance();
        formatting.setMaximumFractionDigits(2);

        System.out.println(ArizonaStudent.getStudentFirstName()+ " " + ArizonaStudent.getStudentLastName() + "" + gpa);
        //System.out.println(ArizonaStudent.getCourses(1));
}

}

This is my Student class code

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assignment2;

/**
 *
 * @author javyc
*/
public class Students {
private String studentFirstName;
private String studentLastName;
private String department;
private String gradYear;

private Classes[] courses;
private double[] gpa1;

public Students(String studentFN, String studentLN, String dept, String graduationYear, Classes[]coursesList, double[]gpaList){
    studentFirstName = studentFN;
    studentLastName = studentLN;
    department = dept;
    gradYear = graduationYear;
    setCourses(coursesList);
    setGPA(gpaList);
}

public String getStudentFirstName(){
    return studentFirstName;
}
public String getStudentLastName(){
    return studentLastName;
}
public String getStudentDepartment(){
    return department;
}
public String getStudentGraduationYear(){
    return gradYear;
}
public Classes[]getCourses(){
    return courses;
}
public double[]getGpa(){
    return gpa1;
}

public void setStudentFirstName(String studentFN){
    studentFirstName = studentFN;
}
public void setStudentLastName(String studentLN){
    studentLastName = studentLN;
}
public void setDepartment(String department){
    this.department = department;
}
public void setGraduationYear(String gradYear){
    this.gradYear = gradYear;
}
public void setCourses(Classes[]courses){
    this.courses=courses;
}
public void setGPA(double[]gpa1){
    this.gpa1=gpa1;
}
 public class GPA{
public double gradePointAverage(){
    int totalCreds = 0;
    double gpaTotal = 0.0;
    for (int i = 0; i<courses.length;i++){
        totalCreds += courses[i].getCredits();
        gpaTotal += courses[i].getCredits()* gpa1[i];
        return gpaTotal = gpaTotal/totalCreds;
    }
    return gpaTotal = gpaTotal/totalCreds;
}
}
}

This is my classes code

/*
 * To change this license header, choose License Headers in Project     Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assignment2;

/**
 *
 * @author javyc
 */
public class Classes {
//We will start by declaring the attributes of the Classes offered at UA
private String professorFirstName;
private String professorLastName;
private String semesterOffered;
private int creditTotal = 0;

public Classes(String profMainName, String profLastName, String semester, int credits)
    {
    professorFirstName = profMainName;
    professorLastName = profLastName;
    semesterOffered = semester;
    creditTotal = credits;
    }
public String returnFirstName(){
    return professorFirstName;
}
public String returnLastName(){
    return professorLastName;
}
public String returnSemester(){
    return semesterOffered;
}
public int getCredits(){
    return creditTotal;
}
public void establishedSemester(String semesterOffered){
    this.semesterOffered = semesterOffered;
}
public void establishFirstName(String professorFirstName){
    this.professorFirstName = professorFirstName;
}
public void establishLastName(String professorLastName){
    this.professorLastName = professorLastName;
}
public void establishCredits(Integer creditTotal){
    this.creditTotal = creditTotal;
}

}


问:
How to complete multiple ajax calls before starting next chained function?
I can get the emails, usernames, etc of multiple users in a SharePoint person picker control. Unfortunately, Id is not one of the available values. To get this, I'm assuming you need to perform multiple ajax calls, and in some cases you need to ensure these calls complete before performing another function.

I've experimented with when.done, when.apply.done and promises.all variations with no luck. I'm just not doing it right.

This is how I populate the emails array from my people picker control:

```<code>var ToCon = $("div[title='To Contacts'] > input").val();
var Fjson = JSON.parse(ToCon);
for (var i = 0; i < Fjson.length; i++) {
  EmailArray.push(Fjson[i].EntityData.Email);
}
</code>```

Here is my function to get the users Id based on their email address:

```<code>function GetUserId(X) {

        $.ajax({
            url: xhost + "/_api/web/SiteUsers?$select=Id&$filter=Email eq '" + X + "'",
            type: "GET", headers: { "Accept": "application/json;odata=verbose", }, //verbose
            success: function (data) {
                var xuserid = data.d.results[0].Id;
                return xuserid;
            },
            error: function (error) { alert(JSON.stringify(error)); }
        });
    }
</code>```

How do I call the GetUserId(X) function for each item in EmailArray, AND make sure it completes before moving on to another chained function?

答:
You can wait for all promises to complete using $.when.apply as you mentioned.  Here's the syntax:

```<code>var promises = [];

promises.push(loadSomeData());
promises.push(loadMoreData());

$.when.apply($, promises)
.fail(function(err)  {
    console.log(err);

})
.done(function (result1, result2)  {
    console.log(result1);
    console.log(result2);
});
</code>```

Notice that in the done call, there are 2 arguments, which match the number of promises you added in the array.  The first promise is the first argument, second promise is the second argument and so on.

Here's another way you can get the user using JSOM:

```<code>function getUser(email) {
    var context = SP.ClientContext.get_current();
    var user = context.get_site().get_rootWeb().ensureUser(email);
    context.load(user);
    context.executeQueryAsync(function (sender, args) {
        console.log("Success: " + user.get_id());
    }, function (sender, args) {
        console.error(args.get_message());
    });
}
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    getUser("my@email.com");
}, "SP.js")
</code>```

Also, if you want a better way to deal with all these promises, have a look at jQuery Deferred.  You can create your own promises and resolve them when the calls have finished.

```<code>function getUserAsPromise(email) {
    var deferred = $.Deferred();
    var context = SP.ClientContext.get_current();
    var user = context.get_site().get_rootWeb().ensureUser(email);
    this.context.load(user);
    this.context.executeQueryAsync(
        function (sender, args) {
            deferred.resolve(user);
        },
        function (sender, args) {
            deferred.reject(sender, args);
        }
    );
    return deferred.promise();
}
getUserAsPromise("my@email.com")
    .fail(function (sender, args) {
        console.error(args.get_message());
    })
    .done(function (user) {
        console.log("Success: " + user.get_id());
    });
</code>```

Body:
I can get the emails, usernames, etc of multiple users in a SharePoint person picker control. Unfortunately, Id is not one of the available values. To get this, I'm assuming you need to perform multiple ajax calls, and in some cases you need to ensure these calls complete before performing another function.

I've experimented with when.done, when.apply.done and promises.all variations with no luck. I'm just not doing it right.

This is how I populate the emails array from my people picker control:

var ToCon = $("div[title='To Contacts'] > input").val();
var Fjson = JSON.parse(ToCon);
for (var i = 0; i < Fjson.length; i++) {
  EmailArray.push(Fjson[i].EntityData.Email);
}

Here is my function to get the users Id based on their email address:

function GetUserId(X) {

        $.ajax({
            url: xhost + "/_api/web/SiteUsers?$select=Id&$filter=Email eq '" + X + "'",
            type: "GET", headers: { "Accept": "application/json;odata=verbose", }, //verbose
            success: function (data) {
                var xuserid = data.d.results[0].Id;
                return xuserid;
            },
            error: function (error) { alert(JSON.stringify(error)); }
        });
    }

How do I call the GetUserId(X) function for each item in EmailArray, AND make sure it completes before moving on to another chained function?

Body:
You can wait for all promises to complete using $.when.apply as you mentioned.  Here's the syntax:

var promises = [];

promises.push(loadSomeData());
promises.push(loadMoreData());

$.when.apply($, promises)
.fail(function(err)  {
    console.log(err);

})
.done(function (result1, result2)  {
    console.log(result1);
    console.log(result2);
});

Notice that in the done call, there are 2 arguments, which match the number of promises you added in the array.  The first promise is the first argument, second promise is the second argument and so on.

Here's another way you can get the user using JSOM:

function getUser(email) {
    var context = SP.ClientContext.get_current();
    var user = context.get_site().get_rootWeb().ensureUser(email);
    context.load(user);
    context.executeQueryAsync(function (sender, args) {
        console.log("Success: " + user.get_id());
    }, function (sender, args) {
        console.error(args.get_message());
    });
}
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    getUser("my@email.com");
}, "SP.js")

Also, if you want a better way to deal with all these promises, have a look at jQuery Deferred.  You can create your own promises and resolve them when the calls have finished.

function getUserAsPromise(email) {
    var deferred = $.Deferred();
    var context = SP.ClientContext.get_current();
    var user = context.get_site().get_rootWeb().ensureUser(email);
    this.context.load(user);
    this.context.executeQueryAsync(
        function (sender, args) {
            deferred.resolve(user);
        },
        function (sender, args) {
            deferred.reject(sender, args);
        }
    );
    return deferred.promise();
}
getUserAsPromise("my@email.com")
    .fail(function (sender, args) {
        console.error(args.get_message());
    })
    .done(function (user) {
        console.log("Success: " + user.get_id());
    });


问:
Thread starvation while locking in a loop in Python
I have an application which is acquiring a lock in a loop in one thread to
perform some task. There's also a second thread that also wants to acquire the lock from
time to time. The problem is, this second thread barely even gets the chance to
perform it's work, as the first one almost always locks first. I hope the
following code will clarify what I'm trying to say:

```<code>import time
from threading import Lock, Thread

lock = Lock()

def loop():
    while True:
        with lock:
            time.sleep(0.1)

thread = Thread(target=loop)
thread.start()

before = time.time()
lock.acquire()
print('Took {}'.format(time.time() - before))
</code>```

If the application gets to print you'll notice that it needed way more than
just 0.1s. But sometimes it also happens that it just waits indefinitely. I've tested this both in Python 2.7.11 and Python 3.4.3 on Debian Linux 8 and it works identically.

This behaviour is counter-intuitive for me. After all when the lock is released
in loop, the lock.acquire was already waiting for its release and it should
immediately acquire the lock. But instead it looks like the loop gets to acquire
the lock first, even though it wasn't waiting for its release at all at the
release moment.

The solution I've found is to sleep between each loop iteration in unlocked state, but that
doesn't strike me as an elegant solution, neither does it explain to me what's
happening.

What am I missing?

答:
To add to @freakish's useful answer, for me the practical solution was to add a tiny sleep right before the greedy thread acquires the lock. In your case:

```<code>def loop():
    while True:
        # give time for competing threads to acquire lock
        time.sleep(0.001)
        with lock:
            time.sleep(0.1)
</code>```

Sleeping for 0 seconds (as suggested in the comments) didn't work for me.

Body:
I have an application which is acquiring a lock in a loop in one thread to
perform some task. There's also a second thread that also wants to acquire the lock from
time to time. The problem is, this second thread barely even gets the chance to
perform it's work, as the first one almost always locks first. I hope the
following code will clarify what I'm trying to say:

import time
from threading import Lock, Thread

lock = Lock()

def loop():
    while True:
        with lock:
            time.sleep(0.1)

thread = Thread(target=loop)
thread.start()

before = time.time()
lock.acquire()
print('Took {}'.format(time.time() - before))

If the application gets to print you'll notice that it needed way more than
just 0.1s. But sometimes it also happens that it just waits indefinitely. I've tested this both in Python 2.7.11 and Python 3.4.3 on Debian Linux 8 and it works identically.

This behaviour is counter-intuitive for me. After all when the lock is released
in loop, the lock.acquire was already waiting for its release and it should
immediately acquire the lock. But instead it looks like the loop gets to acquire
the lock first, even though it wasn't waiting for its release at all at the
release moment.

The solution I've found is to sleep between each loop iteration in unlocked state, but that
doesn't strike me as an elegant solution, neither does it explain to me what's
happening.

What am I missing?

Body:
To add to @freakish's useful answer, for me the practical solution was to add a tiny sleep right before the greedy thread acquires the lock. In your case:

def loop():
    while True:
        # give time for competing threads to acquire lock
        time.sleep(0.001)
        with lock:
            time.sleep(0.1)

Sleeping for 0 seconds (as suggested in the comments) didn't work for me.