问:
Starting Consul in docker does not expose http ports
I followed the instructions in  cosul docker hub documentation to start the server in an Eucalyptus cloud. However other than using local host the Http port is not getting exposed out

```<code>export  CONSUL_LOCAL_CONFIG=/root/consul.json
</code>```

From 1

```<code>docker run -d --net=host -e 'CONSUL_LOCAL_CONFIG={"skip_leave_on_interrupt": true}' consul agent -server -bind=127.0.0.1 -bootstrap-expect=1
</code>```

Putting bind address as 127.0.0.1 is not ever starting the server; Giving the IP adress, the server is starting but bot accessible out. I tried -P and -p 8500:8500 also. Still not able to connect from another machine.

Note that this machine had a private IP as well as public IP.

So I am guessing that is the reason why -net-host is not starting on the bind address
Still not clear. Two similar threads I found which may explain this

Docker container doesn't expose ports when --net=host is mentioned in the docker run command

https://github.com/docker/docker/issues/13914

答:
Why you are not try docker-compose

this is a simple docker.yml file for consul

```<code>version: '2'
services:
  consul:
    container_name: consul
    hostname: consul
    image: progrium/consul
    volumes:
      - /data
      - /config
      - ./consul/consul_ui:/ui
    ports:
      - "8300:8300"
      - "8400:8400"
      - "8500:8500"
      - "8600:8600"
    environment:
    - DOCKER_IP=$DOCKER_IP
    command: -server -bootstrap -data-dir /data -ui-dir /ui
</code>```

Body:
I followed the instructions in  cosul docker hub documentation to start the server in an Eucalyptus cloud. However other than using local host the Http port is not getting exposed out

export  CONSUL_LOCAL_CONFIG=/root/consul.json

From 1

docker run -d --net=host -e 'CONSUL_LOCAL_CONFIG={"skip_leave_on_interrupt": true}' consul agent -server -bind=127.0.0.1 -bootstrap-expect=1

Putting bind address as 127.0.0.1 is not ever starting the server; Giving the IP adress, the server is starting but bot accessible out. I tried -P and -p 8500:8500 also. Still not able to connect from another machine.

Note that this machine had a private IP as well as public IP.

So I am guessing that is the reason why -net-host is not starting on the bind address
Still not clear. Two similar threads I found which may explain this

Docker container doesn't expose ports when --net=host is mentioned in the docker run command

https://github.com/docker/docker/issues/13914

Body:
Why you are not try docker-compose

this is a simple docker.yml file for consul

version: '2'
services:
  consul:
    container_name: consul
    hostname: consul
    image: progrium/consul
    volumes:
      - /data
      - /config
      - ./consul/consul_ui:/ui
    ports:
      - "8300:8300"
      - "8400:8400"
      - "8500:8500"
      - "8600:8600"
    environment:
    - DOCKER_IP=$DOCKER_IP
    command: -server -bootstrap -data-dir /data -ui-dir /ui


来源: stackexchange

问:
Cannot initialize type 'SelectListItem' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
I am trying to create a SelectListItem list to use on my view.

I tried using Linq to pass it to ViewBag like this:

```<code>    public ActionResult Create()
    {
        ViewBag.EmailAccounts = db.EmailAccounts.Select(e => new SelectListItem { e.ID, e.Name });
        return View();
    }
</code>```

But it gives me this error:

Cannot initialize type 'SelectListItem' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

I got the idea to do it this way from here: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

What concept am I missing here?

答:
you are missing property names in object initializer:</p>

```<code>new SelectListItem { Value = e.ID, Text = e.Name }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a SelectListItem list to use on my view.

I tried using Linq to pass it to ViewBag like this:

    public ActionResult Create()
    {
        ViewBag.EmailAccounts = db.EmailAccounts.Select(e => new SelectListItem { e.ID, e.Name });
        return View();
    }

But it gives me this error:

Cannot initialize type 'SelectListItem' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

I got the idea to do it this way from here: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

What concept am I missing here?

Body:
you are missing property names in object initializer:

new SelectListItem { Value = e.ID, Text = e.Name }


问:
ms access graphic load on subform
here i have a question about ms access graphic.

i need to display a graphic (subform), when i give 2 parameters on a form.
i wrote the control between in my query wizard, to control the display of the graphic, n it work great.

On the form where i need the graphic display, i give it textbox and a command button to executing the loaded subform. My question is what the event procedure should i give to the command button so the graphic will load below it text?
please anyone would solve my problems?
thankyou very much
i give it screenshot of my database
pic

答:
Include these parameters in an SQL statement that is the RowSource for the graph. Show the query statement that is your graph's RowSource if you need help with building that statement.

Why do you need a subform? Why not graph on the main form?

The button doesn't need to 'load' the graph, just needs to refresh the form with code in button Click event: Me.Refresh.

Title: ms access graphic load on subform


问:
Are there text processing function that operate on word level in R?
I am trying to find a group of functions in R that would operate on word level. e.g. a function that could return the position of the word. For example given the following sentence and query

```<code>sentence <- "A sample sentence for demo"
query <- "for"
</code>```

the function would return 4. for is 4th word.

It would be great if I could get a utility function that would allow me to extend query both in left and right direction.
e.g. extend(query, 'right') would return for demo and extend(query, 'left') would return sentence for

I have already gone through functions like grep, gregexp, word from stringr package and others. All seem to operate on character level.

答:
If you use scan, it will split input at whitespace:

```<code>> s.scan <- scan(text=sentence, what="")
Read 5 items
> which(s.scan == query)
[1] 4
</code>```

Need the what="" to tell scan to expect character rather than numeric input. Might need to replace punctuation using gsub with patt="[[:punct:]]" if your input is ever full English sentences. May also need to look at the tm (text mining) package if you are trying to classify parts of speech or handle large documents.

Body:
I am trying to find a group of functions in R that would operate on word level. e.g. a function that could return the position of the word. For example given the following sentence and query

sentence <- "A sample sentence for demo"
query <- "for"

the function would return 4. for is 4th word.

It would be great if I could get a utility function that would allow me to extend query both in left and right direction.
e.g. extend(query, 'right') would return for demo and extend(query, 'left') would return sentence for

I have already gone through functions like grep, gregexp, word from stringr package and others. All seem to operate on character level.

Body:
If you use scan, it will split input at whitespace:

> s.scan <- scan(text=sentence, what="")
Read 5 items
> which(s.scan == query)
[1] 4

Need the what="" to tell scan to expect character rather than numeric input. Might need to replace punctuation using gsub with patt="[[:punct:]]" if your input is ever full English sentences. May also need to look at the tm (text mining) package if you are trying to classify parts of speech or handle large documents.


问:
Merging text of list items while keeping the same order using jquery
I have two arrays:

```<code><ul id="titles">
  <li>title 1</li>
  <li>title 2</li>
</ul>
</code>```

and

```<code><ul id="descs">
  <li>desc 1</li>
  <li>desc 2</li>
</ul>
</code>```

I'm looking for the result:

```<code><ul id="titles">
  <li>title 1 <span>desc 1</span></li>
  <li>title 2 <span>desc 2</span></li>
</ul>
</code>```

The code I'm using:

```<code>var li_D = $('#descs li').map(function() {
  return $(this).text();
}).get();
var li_T = $('#titles li').append(function(){
  return"<span>"+li_D+"</span>"
});
</code>```

but it returns this result:

```<code><ul id="titles">
  <li>title 1<span>desc 1,desc 2</span></li>
  <li>title 2<span>desc 1,desc 2</span></li>
</ul>
</code>```

JSfiddle

How do I merge the list items from each ul to get each title with its description?

答:
Use .html( function ) to changing html of every li. In the callback of function get text of relevant element in #descs using .eq().

$('#titles li').html(function(i, html) {
  return html + " "+ $("#descs li").eq(i).text() +"";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#titles span {color: red}</code>```

title 1

title 2

desc 1

desc 2

```

Body:
I have two arrays:

title 1

title 2

and

desc 1

desc 2

I'm looking for the result:

title 1 desc 1

title 2 desc 2

The code I'm using:

var li_D = $('#descs li').map(function() {
  return $(this).text();
}).get();
var li_T = $('#titles li').append(function(){
  return""+li_D+""
});

but it returns this result:

title 1desc 1,desc 2

title 2desc 1,desc 2

JSfiddle

How do I merge the list items from each ul to get each title with its description?

Body:
Use .html( function ) to changing html of every li. In the callback of function get text of relevant element in #descs using .eq().

$('#titles li').html(function(i, html) {
  return html + " <span>"+ $("#descs li").eq(i).text() +"</span>";
});

#titles span {color: red}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="titles">
  <li>title 1</li>
  <li>title 2</li>
</ul>
<ul id="descs">
  <li>desc 1</li>
  <li>desc 2</li>
</ul>


问:
How to evaluate BASH-Like commands (if/elif/else) statements within Python 2.7
I am creating a Hacking Sim game.

Within my game, I am trying to implement BASH scripts for players to use.

Do note:

Players can share scripts with other players

All "BASH" commands are custom, and handled by my game

Commands are currently handled by argparse

This game is for Windows, written in Python2.7

Here is an example of how i process commands:

```<code>class Console():
    def do_echo(self, args):
        cmd_echo = argparse.ArgumentParser(description="Prints out whatever you pass it", prog='echo')
        cmd_echo.add_argument("text",  metavar=("<text>"), help="The text to echo (\"in quotes\")", default=None)

        # Processes the command - Capture '--help' or argument errors (e.g: Typos)
        try: arg = cmd_echo.parse_args(args)
        except SystemExit: return # Voids the SystemExit that argparse calls, while allowing other errors

        print arg.text

def run(command)
    sys_args = shlex.split(command)
    if 'do_'+sys_args[0].lower() in dir(Console):
        function = sys_args[0] ; sys_args.pop(0)
        fn = 'Console().do_%s(%s)' % (function,sys_args)
        eval(fn)
</code>```

When processing scripts(.sh) I am just using for line in f.readlines(): run(line). (Yes, I know "eval is badddd" but i actually TRIED to exploit the process and came up with nothing.) Commands sent from the In-Game Terminal are parsed the same way.

However, i need to know how to processif/else/for/etc..

How can i implement this in my current code?

答:
Ultimately if you want user programmable scripts you'll need to do some sort of interpreting and execution. Also, depending on how important security is to you, you have to consider the context with which those scripts are executing, and what they can do.

I highly suggest you start with something like: http://norvig.com/lispy.html. This is a really simple example of implementing a interpreted language on top of python. Best of luck!

Body:
I am creating a Hacking Sim game.

Within my game, I am trying to implement BASH scripts for players to use.

Do note:

Players can share scripts with other players

All "BASH" commands are custom, and handled by my game

Commands are currently handled by argparse

This game is for Windows, written in Python2.7

Here is an example of how i process commands:

class Console():
    def do_echo(self, args):
        cmd_echo = argparse.ArgumentParser(description="Prints out whatever you pass it", prog='echo')
        cmd_echo.add_argument("text",  metavar=("<text>"), help="The text to echo (\"in quotes\")", default=None)

        # Processes the command - Capture '--help' or argument errors (e.g: Typos)
        try: arg = cmd_echo.parse_args(args)
        except SystemExit: return # Voids the SystemExit that argparse calls, while allowing other errors

        print arg.text

def run(command)
    sys_args = shlex.split(command)
    if 'do_'+sys_args[0].lower() in dir(Console):
        function = sys_args[0] ; sys_args.pop(0)
        fn = 'Console().do_%s(%s)' % (function,sys_args)
        eval(fn)

When processing scripts(.sh) I am just using for line in f.readlines(): run(line). (Yes, I know "eval is badddd" but i actually TRIED to exploit the process and came up with nothing.) Commands sent from the In-Game Terminal are parsed the same way.

However, i need to know how to processif/else/for/etc..

How can i implement this in my current code?


问:
Retrieving images from Google Cloud Storage in Node.js without public URL
I'm trying to return images to my users to view on the DOM without creating public links to images (This route is protected by my server's auth before getting images back). This is what I have tried so far, but this might be the wrong way to go about it.

I'm following the Google Cloud Storage with Node.js guide to add image uploading to my project. I now have the upload working and images are saving in Google Cloud Storage. The guide shows how to retrieve a public URL:

https://cloud.google.com/nodejs/getting-started/using-cloud-storage

I'm trying to use file streaming instead of the public URL so that my images aren't made public. I'm guessing it would look similar to the streams in this repository:
https://github.com/GoogleCloudPlatform/google-cloud-node

But I'm trying to return the images on an HTTP response and not simply store them locally on my file system.

My client side Javascript is getting a response that looks like a giant blob. ����JFIF���Photoshop 3.08BIM� The metadata makes me think that this is, in fact, the correct image, but I'm not sure how to get it back to looking like an image.

Here is my Node server file. The upload to Google Cloud Storage, the /post, is working, I can see the images being added.

The /get is returning what looks like a giant blob that seems like it is the image I want (just as a weird blob that I don't know how to convert).

My code looks like this:

```<code>var express = require('express');
var router = express.Router();
const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'server/firebase-service-account.json',
  projectId: process.env.FIREBASE_PROJECT_ID
});

const bucket = storage.bucket(process.env.FIREBASE_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res, next) => {
  console.log('req.body', req.body);
  console.log('req.file', req.file);
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
    return;
  });

  blobStream.on('finish', () => {
    res.status(200).send('The image has been successfully uploaded to google cloud storage');
  });

  blobStream.end(req.file.buffer);
});

router.get('/', function (req, res, next) {
  var stream = bucket.file('Toast.jpg').createReadStream();

  stream.pipe(res);

  stream.on('data', function (data) {
    res.write(data);
  });

  stream.on('error', function (err) {
    console.log('error reading stream', err);
  });

  stream.on('end', function () {
    res.set({
      "Content-Disposition": 'attachment; filename="Toast.jpg"',
      "Content-Type": 'image/jpg'
    });
    res.end();
  });
});

module.exports = router;
</code>```

Is this close? Is there a better way to secure my images with my auth?

答:
I was thinking about it the wrong way. I needed to just route my <img src="" to the correct location.

HTML

```<code><img src="/uploads/1234">
</code>```

Server Node

```<code>var express = require('express');
var router = express.Router();
const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'server/firebase-service-account.json',
  projectId: process.env.FIREBASE_PROJECT_ID
});

const bucket = storage.bucket(process.env.FIREBASE_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res, next) => {
  console.log('req.body', req.body);
  console.log('req.file', req.file);
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
    return;
  });

  blobStream.on('finish', () => {
    res.status(200).send('The image has been successfully uploaded to google cloud storage');
  });

  blobStream.end(req.file.buffer);
});

router.get('/:imageId', function (req, res, next) {
  var stream = bucket.file('Toast.jpg').createReadStream();

  res.writeHead(200, {'Content-Type': 'image/jpg' });

  stream.on('data', function (data) {
    res.write(data);
  });

  stream.on('error', function (err) {
    console.log('error reading stream', err);
  });

  stream.on('end', function () {
    res.end();
  });
});

module.exports = router;
</code>```

I would still love feedback on whether this is the correct way to solve this problem. (Obviously, the hardcoding will need to go.)

Body:
I'm trying to return images to my users to view on the DOM without creating public links to images (This route is protected by my server's auth before getting images back). This is what I have tried so far, but this might be the wrong way to go about it.

I'm following the Google Cloud Storage with Node.js guide to add image uploading to my project. I now have the upload working and images are saving in Google Cloud Storage. The guide shows how to retrieve a public URL:

https://cloud.google.com/nodejs/getting-started/using-cloud-storage

I'm trying to use file streaming instead of the public URL so that my images aren't made public. I'm guessing it would look similar to the streams in this repository:
https://github.com/GoogleCloudPlatform/google-cloud-node

But I'm trying to return the images on an HTTP response and not simply store them locally on my file system.

My client side Javascript is getting a response that looks like a giant blob. ����JFIF���Photoshop 3.08BIM� The metadata makes me think that this is, in fact, the correct image, but I'm not sure how to get it back to looking like an image.

Here is my Node server file. The upload to Google Cloud Storage, the /post, is working, I can see the images being added.

The /get is returning what looks like a giant blob that seems like it is the image I want (just as a weird blob that I don't know how to convert).

My code looks like this:

var express = require('express');
var router = express.Router();
const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'server/firebase-service-account.json',
  projectId: process.env.FIREBASE_PROJECT_ID
});

const bucket = storage.bucket(process.env.FIREBASE_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res, next) => {
  console.log('req.body', req.body);
  console.log('req.file', req.file);
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
    return;
  });

  blobStream.on('finish', () => {
    res.status(200).send('The image has been successfully uploaded to google cloud storage');
  });

  blobStream.end(req.file.buffer);
});

router.get('/', function (req, res, next) {
  var stream = bucket.file('Toast.jpg').createReadStream();

  stream.pipe(res);

  stream.on('data', function (data) {
    res.write(data);
  });

  stream.on('error', function (err) {
    console.log('error reading stream', err);
  });

  stream.on('end', function () {
    res.set({
      "Content-Disposition": 'attachment; filename="Toast.jpg"',
      "Content-Type": 'image/jpg'
    });
    res.end();
  });
});

module.exports = router;

Is this close? Is there a better way to secure my images with my auth?

Body:
I was thinking about it the wrong way. I needed to just route my <img src="" to the correct location.

HTML

<img src="/uploads/1234">

Server Node

var express = require('express');
var router = express.Router();
const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'server/firebase-service-account.json',
  projectId: process.env.FIREBASE_PROJECT_ID
});

const bucket = storage.bucket(process.env.FIREBASE_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res, next) => {
  console.log('req.body', req.body);
  console.log('req.file', req.file);
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
    return;
  });

  blobStream.on('finish', () => {
    res.status(200).send('The image has been successfully uploaded to google cloud storage');
  });

  blobStream.end(req.file.buffer);
});

router.get('/:imageId', function (req, res, next) {
  var stream = bucket.file('Toast.jpg').createReadStream();

  res.writeHead(200, {'Content-Type': 'image/jpg' });

  stream.on('data', function (data) {
    res.write(data);
  });

  stream.on('error', function (err) {
    console.log('error reading stream', err);
  });

  stream.on('end', function () {
    res.end();
  });
});

module.exports = router;

I would still love feedback on whether this is the correct way to solve this problem. (Obviously, the hardcoding will need to go.)


问:
I have a return to top of the page button in my website, how can I animate scrolling back to the top?
I already have a button in my html and css that appears when the user scrolls down 20px. When you click the button, it sends the user back to the top of the page. I would like it to animate scrolling back to the top, instead of jumping straight there. Here's my code:

HTML:

```<code><button onclick="topFunction()" id="myBtn" title="Return To Top"><i class="fa fa-angle-up fa-lg"></i></button>
</code>```

CSS:

```<code>#myBtn {
display: none;
font-size: 2em;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: rgba(0, 0, 0, 0.5);
color: white;
cursor: pointer;
padding: 15px;
border-radius: 10px;
-webkit-transition: color 0.5s;
transition: color 0.5s;
}

#myBtn:hover {

color: #00ff0a;

}
</code>```

Javascript:

```<code>window.onscroll = function() {scrollFunction()};

function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("myBtn").style.display = "block";
} else {
    document.getElementById("myBtn").style.display = "none";
}
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0; // For Chrome, Safari and Opera
document.documentElement.scrollTop = 0; // For IE and Firefox
}
</code>```

Any help is welcome

答:
Use the .animate() function with scrollTop like this:

```<code>function topFunction() {
   $("html, body").animate({scrollTop: "0"});
}
</code>```

Body:
I already have a button in my html and css that appears when the user scrolls down 20px. When you click the button, it sends the user back to the top of the page. I would like it to animate scrolling back to the top, instead of jumping straight there. Here's my code:

HTML:

<button onclick="topFunction()" id="myBtn" title="Return To Top"></button>

CSS:

#myBtn {
display: none;
font-size: 2em;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: rgba(0, 0, 0, 0.5);
color: white;
cursor: pointer;
padding: 15px;
border-radius: 10px;
-webkit-transition: color 0.5s;
transition: color 0.5s;
}

#myBtn:hover {

color: #00ff0a;

}

Javascript:

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("myBtn").style.display = "block";
} else {
    document.getElementById("myBtn").style.display = "none";
}
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0; // For Chrome, Safari and Opera
document.documentElement.scrollTop = 0; // For IE and Firefox
}

Any help is welcome

Body:
Use the .animate() function with scrollTop like this:

function topFunction() {
   $("html, body").animate({scrollTop: "0"});
}


问:
UrlOpen Redirected to default page
The default data link is http://tools.morningstar.co.uk/uk/fundscreener/results.aspx?LanguageId=en-GB&Universe=FOGBR%24%24ALL&CurrencyId=GBP&URLKey=t92wz0sj7c&Site=uk

But, I do not want data on this default page. I want the data under Portfolio tab. So, I used Firefox to determine the url of the portfolio and attempted  following python code:

```<code>testpage = urlopen('http://tools.morningstar.co.uk/uk/fundscreener/results.aspx?LanguageId=en-GB&Universe=FOGBR%24%24ALL&CurrencyId=GBP&URLKey=t92wz0sj7c&Site=uk&tabAction=Portfolio')
</code>```

However, page is always redirected to the default link. How do I get to the portfolio page?

答:
You need to pay attention to the request that is being made along with all the headers and the data.

For getting the "portfolio" data, if you inspect, you will see that POST request is being along with log of data is sent and payload data (form data) is to used to send the portfolio data back in response.

What you need to do is mimic the request to fetch the response data and then handle that according to your need. You can do something like this :

```<code>import requests
from lxml import html

headers = {
    'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    'accept-language':'en-US,en;q=0.8,ms;q=0.6'
}

url = "http://tools.morningstar.co.uk/uk/fundscreener/results.aspx?LanguageId=en-GB&Universe=FOGBR%24%24ALL&CurrencyId=GBP&URLKey=t92wz0sj7c&Site=uk"

payload = {
    'ctl00_ContentPlaceHolder1_aFundScreenerResultControl_ScriptManager1_HiddenField':';;AjaxControlToolkit, Version=3.5.7.123, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e:en-GB:5a4df314-b4a2-4da2-a207-9284f1b1e96c:de1feab2:f2c8e708:720a52bf:f9cec9bc:589eaa30:a67c2700:ab09e3fe:87104b7c:8613aea7:3202a5a2:be6fb298',
    '__EVENTTARGET':'TabAction',
    '__EVENTARGUMENT':'Portfolio',
    '__LASTFOCUS':'',
    '__VIEWSTATE':'[encoded data, 7916 characters]',
    '__VIEWSTATEGENERATOR':'7400285C',
    '__VIEWSTATEENCRYPTED':'',
    '__EVENTVALIDATION':'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',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$ddlPageSize':'20',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnFilterBySelection':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnSelectedIndex':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnSelectedFunds':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnCustomImageFileIds':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnSelectedSecurityCount':'0',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnTabs':'Snapshot,ShortTerm,Performance,Portfolio,FeesAndDetails',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnSelectedRow':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnCheckedColumns':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnExportLimit':'50',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnExportCount':'0',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$toExport':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnAllowAllFundsExport':'true',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$txtSaveSearch':'',
    'ctl00$__RequestVerificationToken':'e_BrPK0DxBjkgMrhfkdyFJjp1nPzltSn0h20aUjHJPSe3W4w3FRsFQNo_YY3Ml0D1CkNGqC5PEJBigtZuvdbiYrldSMrUoOQFUjaPifPbM41'
}

r = requests.post(url, headers = headers, data = payload)
print(r.content)

root = html.fromstring(r.content)
</code>```

You can now fetch the elements you need from root using xpath such as :

```<code>root.xpath('//input[@class="some_class"]')
</code>```

Refer to scraping and lxml documentation for more understanding.

I have used all the payload data from the request, you can remove some and check for what is absolutely necessary for the request.

Also, follow the website rules about scraping and scrape gracefully without putting too much pressure on the website.

Title: UrlOpen Redirected to default page

Body:
The default data link is http://tools.morningstar.co.uk/uk/fundscreener/results.aspx?LanguageId=en-GB&Universe=FOGBR%24%24ALL&CurrencyId=GBP&URLKey=t92wz0sj7c&Site=uk

But, I do not want data on this default page. I want the data under Portfolio tab. So, I used Firefox to determine the url of the portfolio and attempted  following python code:

testpage = urlopen('http://tools.morningstar.co.uk/uk/fundscreener/results.aspx?LanguageId=en-GB&Universe=FOGBR%24%24ALL&CurrencyId=GBP&URLKey=t92wz0sj7c&Site=uk&tabAction=Portfolio')

However, page is always redirected to the default link. How do I get to the portfolio page?

Body:
You need to pay attention to the request that is being made along with all the headers and the data.

For getting the "portfolio" data, if you inspect, you will see that POST request is being along with log of data is sent and payload data (form data) is to used to send the portfolio data back in response.

What you need to do is mimic the request to fetch the response data and then handle that according to your need. You can do something like this :

import requests
from lxml import html

headers = {
    'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    'accept-language':'en-US,en;q=0.8,ms;q=0.6'
}

url = "http://tools.morningstar.co.uk/uk/fundscreener/results.aspx?LanguageId=en-GB&Universe=FOGBR%24%24ALL&CurrencyId=GBP&URLKey=t92wz0sj7c&Site=uk"

payload = {
    'ctl00_ContentPlaceHolder1_aFundScreenerResultControl_ScriptManager1_HiddenField':';;AjaxControlToolkit, Version=3.5.7.123, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e:en-GB:5a4df314-b4a2-4da2-a207-9284f1b1e96c:de1feab2:f2c8e708:720a52bf:f9cec9bc:589eaa30:a67c2700:ab09e3fe:87104b7c:8613aea7:3202a5a2:be6fb298',
    '__EVENTTARGET':'TabAction',
    '__EVENTARGUMENT':'Portfolio',
    '__LASTFOCUS':'',
    '__VIEWSTATE':'[encoded data, 7916 characters]',
    '__VIEWSTATEGENERATOR':'7400285C',
    '__VIEWSTATEENCRYPTED':'',
    '__EVENTVALIDATION':'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',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$ddlPageSize':'20',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnFilterBySelection':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnSelectedIndex':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnSelectedFunds':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnCustomImageFileIds':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnSelectedSecurityCount':'0',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$hdnTabs':'Snapshot,ShortTerm,Performance,Portfolio,FeesAndDetails',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnSelectedRow':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnCheckedColumns':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnExportLimit':'50',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnExportCount':'0',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$toExport':'',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$msExportToExcel$hdnAllowAllFundsExport':'true',
    'ctl00$ContentPlaceHolder1$aFundScreenerResultControl$txtSaveSearch':'',
    'ctl00$__RequestVerificationToken':'e_BrPK0DxBjkgMrhfkdyFJjp1nPzltSn0h20aUjHJPSe3W4w3FRsFQNo_YY3Ml0D1CkNGqC5PEJBigtZuvdbiYrldSMrUoOQFUjaPifPbM41'
}

r = requests.post(url, headers = headers, data = payload)
print(r.content)

root = html.fromstring(r.content)

You can now fetch the elements you need from root using xpath such as :

root.xpath('//input[@class="some_class"]')

Refer to scraping and lxml documentation for more understanding.

I have used all the payload data from the request, you can remove some and check for what is absolutely necessary for the request.

Also, follow the website rules about scraping and scrape gracefully without putting too much pressure on the website.


问:
Not getting "Git remote heroku added" and getting error: "fatal: The remote end hung up unexpectedly" when pushing to heroku master
I am brand new to Heroku and Ruby on Rails. When I run "heroku create" I do not get "Git remote heroku added". Also, when I try to "git push heroku master" I get "fatal: The remote end hung up unexpectedly". On the sites like Stackflow there are similar situations but with additional error messages. Mine is only "fatal: The remote end hung up unexpectedly".  I also already edited the gem file. I notice that instead of loading the "first_app" that I'm trying to install, it installs the http: //murmuring-ravine-4822.herokuapp.com | git@heroku.com:murmuring-ravine-4822.git.
Please help,
Alex</p>

答:
Add application to Heroku git remote repository using below command.

```<code>heroku git:remote -a your-app-name
</code>```

Then push application to Heroku master repository.

Useful link: Creating a Heroku remote.

Body:
Add application to Heroku git remote repository using below command.

heroku git:remote -a your-app-name

Then push application to Heroku master repository.

Useful link: Creating a Heroku remote.


问:
Where should i save my tornado custom options
I am working on a python/tornado web application.

I have several options to save in my app.
Thoses options can by changed by the user, and those options will be access very often.
I have created an sqlite database but there is some disk operation and i am asking you what is the best location for those options.
Does tornado embed a feature for custom user options ?

Thanks

答: Yes, there is the tornado.options package, which does pretty much what you need. Keep in mind, however, that the values saved here are not persisted between requests; if you need that kind of functionality, you will have to implement an external persistence solution, which you already have done with SQLite.


答:
you could use the jQuery .animate() method, and the scrollTop property.

Example:

```<code>$(function(){
    $("#myBtn").click(function(e){
        e.preventDefault();
        $("html, body").animate({"scrollTop": "0px"}, 600);
    })
});
</code>```

Title: I have a return to top of the page button in my website, how can I animate scrolling back to the top?

Body:
you could use the jQuery .animate() method, and the scrollTop property.

Example:

$(function(){
    $("#myBtn").click(function(e){
        e.preventDefault();
        $("html, body").animate({"scrollTop": "0px"}, 600);
    })
});


问:
Picking a completly random element from a string list, simpler C# - Hangman
So i got my hangman up and running but the what i dont like is the way my program picks the random word (which isnt completely random and can be guessed, pseudo)..

NOTE: Some parts in the code are in Slovene language. I changed the important ones to english.

I'm trying to make a simpler and actually random way to pick that word. I did try to implement various other options but without success...

Also i do not really understand how DateTime.Now.Ticks picks a word.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace HANGMAN //moj imenski prostor

{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random((int)DateTime.Now.Ticks);

        string[] WORDBANK = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF" };

        string WordToGuess = WORDBANK[random.Next(0, WORDBANK.Length)];
        string WordToGuessUppercase = WordToGuess.ToUpper();

        StringBuilder displayToPlayer = new StringBuilder(WordToGuess.Length);
        for (int i = 0; i < WordToGuess.Length; i++)
            displayToPlayer.Append('_');

        List<char> correctGuesses = new List<char>();
        List<char> incorrectGuesses = new List<char>();

        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine("__________________________________________________________________");
        Console.WriteLine();
        Console.Write("VISLICE - Maturitetna Naloga pri predmetu Informatika");
        Console.WriteLine();
        Console.WriteLine("__________________________________________________________________");
        Console.WriteLine();
        Console.WriteLine("-> Imas 5 poizkusov <-");
        Console.WriteLine();
        Thread.Sleep(500);

        int lives = 5;
        bool won = false;
        int lettersRevealed = 0;

        string input;
        char Guess;

        while (!won && lives > 0)
        {
            Thread.Sleep(500);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Ugani besedo, izberi crko: ");
            Console.WriteLine();

            input = Console.ReadLine().ToUpper();
            Ugib = input[0];

            if (correctGuesses.Contains(Guess))
            {
                Thread.Sleep(500);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Crko '{0}' si ze uporabil, bila je pravilna!", Guess);
                Console.WriteLine("____________________________________________");
                continue;
            }

            else if (nepravilniUgibi.Contains(Ugib))
            {
                Thread.Sleep(500);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Crko '{0}' si ze uporabil, bila je napacna!", Guess);
                Console.WriteLine("___________________________________________");
                continue;
            }

            if (WordToGuessUppercase.Contains(Guess))
            {
                pravilniUgibi.Add(Ugib);

                for (int i = 0; i < WordToGuess.Length; i++)
                {
                    if (WordToGuessUppercase[i] == Guess)
                    {
                        displayToPlayer[i] = WordToGuess[i];
                        lettersRevealed++;
                    }
                }

                if (lettersRevealed == WordToGuess.Length)
                    won = true;
            }
            else
            {
                incorrectGuesses.Add(Guess);

                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Narobe, crke '{0}', ni v besedi!", Guess);
                Console.WriteLine("________________________________");
                Console.WriteLine();
                poizkusi--;
            }

            Console.WriteLine(displayToPlayer.ToString());
        }

        if (won)
        {
            Console.WriteLine();
            Thread.Sleep(500);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Zmaga!");
            Console.WriteLine();
            Thread.Sleep(1000);
            Console.WriteLine("KONEC IGRE");
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine();
            Thread.Sleep(1000);
            Console.WriteLine("Zal si to igro zgubil. Poskusi ponovno! Pravilna beseda je bila '{0}'", WordToGuess);
        }

    }
}
</code>```

}

答:
The random number generator is fine. The ticks in the Random constructor will seed the generator with a different number each time your program runs. You can expect that no two sequences will be the same: C# - Random number with seed (be careful not no create new instances of Random faster than the tick count increments).

Note that calling the constructor as new Random(System.DateTime.Now.Ticks) is almost the same as calling the parameterless constructor, new Random(), because that seeds it with the value of Environment.TickCount - which is the number of ticks since the machine booted - in the current implementation of the .NET framework.

Pseudo-random: yes.

There is a whole bunch of questions dealing with the implementation, its theoretical background, and true random sources, start here: https://stackoverflow.com/a/4440760/1132334

Regarding the code, you have a simple mistake in the call to Next:

Instead of

```<code>string WordToGuess = WORDBANK[random.Next(0, WordToGuess.Length)];
</code>```

write

```<code>string WordToGuess = WORDBANK[random.Next(0, WORDBANK.Length)];
</code>```

The forward reference WordToGuess.Length does not compile in C#, you intended to use the length of the wordbank array for sure. The second int argument is the exclusive upper bound, documented here.

Body:
So i got my hangman up and running but the what i dont like is the way my program picks the random word (which isnt completely random and can be guessed, pseudo)..

NOTE: Some parts in the code are in Slovene language. I changed the important ones to english.

I'm trying to make a simpler and actually random way to pick that word. I did try to implement various other options but without success...

Also i do not really understand how DateTime.Now.Ticks picks a word.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace HANGMAN //moj imenski prostor

{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random((int)DateTime.Now.Ticks);

        string[] WORDBANK = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF" };

        string WordToGuess = WORDBANK[random.Next(0, WORDBANK.Length)];
        string WordToGuessUppercase = WordToGuess.ToUpper();

        StringBuilder displayToPlayer = new StringBuilder(WordToGuess.Length);
        for (int i = 0; i < WordToGuess.Length; i++)
            displayToPlayer.Append('_');

        List<char> correctGuesses = new List<char>();
        List<char> incorrectGuesses = new List<char>();

        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine("__________________________________________________________________");
        Console.WriteLine();
        Console.Write("VISLICE - Maturitetna Naloga pri predmetu Informatika");
        Console.WriteLine();
        Console.WriteLine("__________________________________________________________________");
        Console.WriteLine();
        Console.WriteLine("-> Imas 5 poizkusov <-");
        Console.WriteLine();
        Thread.Sleep(500);

        int lives = 5;
        bool won = false;
        int lettersRevealed = 0;

        string input;
        char Guess;

        while (!won && lives > 0)
        {
            Thread.Sleep(500);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Ugani besedo, izberi crko: ");
            Console.WriteLine();

            input = Console.ReadLine().ToUpper();
            Ugib = input[0];

            if (correctGuesses.Contains(Guess))
            {
                Thread.Sleep(500);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Crko '{0}' si ze uporabil, bila je pravilna!", Guess);
                Console.WriteLine("____________________________________________");
                continue;
            }

            else if (nepravilniUgibi.Contains(Ugib))
            {
                Thread.Sleep(500);
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Crko '{0}' si ze uporabil, bila je napacna!", Guess);
                Console.WriteLine("___________________________________________");
                continue;
            }

            if (WordToGuessUppercase.Contains(Guess))
            {
                pravilniUgibi.Add(Ugib);

                for (int i = 0; i < WordToGuess.Length; i++)
                {
                    if (WordToGuessUppercase[i] == Guess)
                    {
                        displayToPlayer[i] = WordToGuess[i];
                        lettersRevealed++;
                    }
                }

                if (lettersRevealed == WordToGuess.Length)
                    won = true;
            }
            else
            {
                incorrectGuesses.Add(Guess);

                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Narobe, crke '{0}', ni v besedi!", Guess);
                Console.WriteLine("________________________________");
                Console.WriteLine();
                poizkusi--;
            }

            Console.WriteLine(displayToPlayer.ToString());
        }

        if (won)
        {
            Console.WriteLine();
            Thread.Sleep(500);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Zmaga!");
            Console.WriteLine();
            Thread.Sleep(1000);
            Console.WriteLine("KONEC IGRE");
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine();
            Thread.Sleep(1000);
            Console.WriteLine("Zal si to igro zgubil. Poskusi ponovno! Pravilna beseda je bila '{0}'", WordToGuess);
        }

    }
}

}

Body:
The random number generator is fine. The ticks in the Random constructor will seed the generator with a different number each time your program runs. You can expect that no two sequences will be the same: C# - Random number with seed (be careful not no create new instances of Random faster than the tick count increments).

Note that calling the constructor as new Random(System.DateTime.Now.Ticks) is almost the same as calling the parameterless constructor, new Random(), because that seeds it with the value of Environment.TickCount - which is the number of ticks since the machine booted - in the current implementation of the .NET framework.

Pseudo-random: yes.

There is a whole bunch of questions dealing with the implementation, its theoretical background, and true random sources, start here: https://stackoverflow.com/a/4440760/1132334

Regarding the code, you have a simple mistake in the call to Next:

Instead of

string WordToGuess = WORDBANK[random.Next(0, WordToGuess.Length)];

write

string WordToGuess = WORDBANK[random.Next(0, WORDBANK.Length)];

The forward reference WordToGuess.Length does not compile in C#, you intended to use the length of the wordbank array for sure. The second int argument is the exclusive upper bound, documented here.


问:
Tensorflow: Linear regression with non-negative constraints
I am trying to implement a linear regression model in Tensorflow, with additional constraints (coming from the domain) that the W and b terms must be non-negative.

I believe there are a couple of ways to do this.

We can modify the cost function to penalize negative weights [Lagrangian approach] [See:TensorFlow - best way to implement weight constraints

We can compute the gradients ourselves and project them on [0, infinity] [Projected gradient approach]

Approach 1: Lagrangian

When I tried the first approach, I would often end up with negative b.

I had modified the cost function from:

```<code>cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
</code>```

to:

```<code>cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
nn_w = tf.reduce_sum(tf.abs(W) - W)
nn_b = tf.reduce_sum(tf.abs(b) - b)
constraint = 100.0*nn_w + 100*nn_b
cost_with_constraint = cost + constraint
</code>```

Keeping the coefficient of nn_b and nn_w to be very high leads to instability and very high cost.

Here is the complete code.

```<code>import numpy as np
import tensorflow as tf

n_samples = 50
train_X = np.linspace(1, 50, n_samples)
train_Y = 10*train_X + 6 +40*np.random.randn(50)

X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(np.random.randn(), name="weight")
b = tf.Variable(np.random.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Gradient descent
learning_rate=0.0001
# Initializing the variables
init = tf.global_variables_initializer()

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
nn_w = tf.reduce_sum(tf.abs(W) - W)
nn_b = tf.reduce_sum(tf.abs(b) - b)
constraint = 1.0*nn_w + 100*nn_b
cost_with_constraint = cost + constraint
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_with_constraint)

training_epochs=200
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    cost_array = np.zeros(training_epochs)
    W_array = np.zeros(training_epochs)
    b_array = np.zeros(training_epochs)

    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})
            W_array[epoch] = sess.run(W)
            b_array[epoch] = sess.run(b)
            cost_array[epoch] = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
</code>```

The following is the mean of b across 10 different runs.

```<code>0   -1.101268
1    0.169225
2    0.158363
3    0.706270
4   -0.371205
5    0.244424
6    1.312516
7   -0.069609
8   -1.032187
9   -1.711668
</code>```

Clearly, the first approach is not optimal. Further, there is a lot of art involved in choosing the coefficient of penalty terms.

Approach 2: Projected gradient

I then thought to use the second approach, which is more guaranteed to work.

```<code>gr = tf.gradients(cost, [W, b])
</code>```

We manually compute the gradients and update the W and b.

```<code> with tf.Session() as sess:
    sess.run(init)

    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            W_del, b_del = sess.run(gr, feed_dict={X: x, Y: y})
            W = max(0, (W - W_del)*learning_rate) #Project the gradient on [0, infinity]
            b = max(0, (b - b_del)*learning_rate) # Project the gradient on [0, infinity]
</code>```

This approach seems to be very slow.

I am wondering if there is a better way to run the second approach, or guarantee the results with the first approach. Can we somehow allow the optimizer to ensure that the learnt weights are non-negative?

Edit: How to do this in Autograd

https://github.com/HIPS/autograd/issues/207

答:
If you modify your linear model to:

```<code>pred = tf.add(tf.multiply(X, tf.abs(W)), tf.abs(b))
</code>```

it will have the same effect as using only positive W and b values.

The reason your second approach is slow is that you clip the W and b values outside of the tensorflow graph. (Also it will not converge because (W - W_del)*learning_rate must instead be W - W_del*learning_rate)

edit:

You can implement the clipping using tensorflow graph like this:

```<code>train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

with tf.control_dependencies([train_step]):
    clip_W = W.assign(tf.maximum(0., W))
    clip_b = b.assign(tf.maximum(0., b))
    train_step_with_clip = tf.group(clip_W, clip_b)
</code>```

In this case W and b values will be clipped to 0 and not to small positive numbers.

Here is a small mnist example with clipping:

```<code>import tensorflow as tf

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

x = tf.placeholder(tf.uint8, [None, 28, 28])
x_vec = tf.cast(tf.reshape(x, [-1, 784]), tf.float32) / 255.

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x_vec, W) + b

y_target = tf.placeholder(tf.uint8, [None])
y_target_one_hot = tf.one_hot(y_target, 10)

cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_target_one_hot, logits=y))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

with tf.control_dependencies([train_step]):
    clip_W = W.assign(tf.maximum(0., W))
    clip_b = b.assign(tf.maximum(0., b))
    train_step_with_clip = tf.group(clip_W, clip_b)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_target_one_hot, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
  tf.global_variables_initializer().run()

  for i in range(1000):
    sess.run(train_step_with_clip, feed_dict={
        x: x_train[(i*100)%len(x_train):((i+1)*100)%len(x_train)],
        y_target: y_train[(i*100)%len(x_train):((i+1)*100)%len(x_train)]})

    if not i%100:
      print("Min_W:", sess.run(tf.reduce_min(W)))
      print("Min_b:", sess.run(tf.reduce_min(b)))

  print("Accuracy:", sess.run(accuracy, feed_dict={
      x: x_test,
      y_target: y_test}))
</code>```

Body:
I am trying to implement a linear regression model in Tensorflow, with additional constraints (coming from the domain) that the W and b terms must be non-negative.

I believe there are a couple of ways to do this.

We can modify the cost function to penalize negative weights [Lagrangian approach] [See:TensorFlow - best way to implement weight constraints

We can compute the gradients ourselves and project them on [0, infinity] [Projected gradient approach]

Approach 1: Lagrangian

When I tried the first approach, I would often end up with negative b.

I had modified the cost function from:

cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)

to:

cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
nn_w = tf.reduce_sum(tf.abs(W) - W)
nn_b = tf.reduce_sum(tf.abs(b) - b)
constraint = 100.0*nn_w + 100*nn_b
cost_with_constraint = cost + constraint

Keeping the coefficient of nn_b and nn_w to be very high leads to instability and very high cost.

Here is the complete code.

import numpy as np
import tensorflow as tf

n_samples = 50
train_X = np.linspace(1, 50, n_samples)
train_Y = 10*train_X + 6 +40*np.random.randn(50)

X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(np.random.randn(), name="weight")
b = tf.Variable(np.random.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Gradient descent
learning_rate=0.0001
# Initializing the variables
init = tf.global_variables_initializer()

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
nn_w = tf.reduce_sum(tf.abs(W) - W)
nn_b = tf.reduce_sum(tf.abs(b) - b)
constraint = 1.0*nn_w + 100*nn_b
cost_with_constraint = cost + constraint
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_with_constraint)

training_epochs=200
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    cost_array = np.zeros(training_epochs)
    W_array = np.zeros(training_epochs)
    b_array = np.zeros(training_epochs)

    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})
            W_array[epoch] = sess.run(W)
            b_array[epoch] = sess.run(b)
            cost_array[epoch] = sess.run(cost, feed_dict={X: train_X, Y: train_Y})

The following is the mean of b across 10 different runs.

0   -1.101268
1    0.169225
2    0.158363
3    0.706270
4   -0.371205
5    0.244424
6    1.312516
7   -0.069609
8   -1.032187
9   -1.711668

Clearly, the first approach is not optimal. Further, there is a lot of art involved in choosing the coefficient of penalty terms.

Approach 2: Projected gradient

I then thought to use the second approach, which is more guaranteed to work.

gr = tf.gradients(cost, [W, b])

We manually compute the gradients and update the W and b.

 with tf.Session() as sess:
    sess.run(init)

    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            W_del, b_del = sess.run(gr, feed_dict={X: x, Y: y})
            W = max(0, (W - W_del)*learning_rate) #Project the gradient on [0, infinity]
            b = max(0, (b - b_del)*learning_rate) # Project the gradient on [0, infinity]

This approach seems to be very slow.

I am wondering if there is a better way to run the second approach, or guarantee the results with the first approach. Can we somehow allow the optimizer to ensure that the learnt weights are non-negative?

Edit: How to do this in Autograd

https://github.com/HIPS/autograd/issues/207

Body:
If you modify your linear model to:

pred = tf.add(tf.multiply(X, tf.abs(W)), tf.abs(b))

it will have the same effect as using only positive W and b values.

The reason your second approach is slow is that you clip the W and b values outside of the tensorflow graph. (Also it will not converge because (W - W_del)*learning_rate must instead be W - W_del*learning_rate)

edit:

You can implement the clipping using tensorflow graph like this:

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

with tf.control_dependencies([train_step]):
    clip_W = W.assign(tf.maximum(0., W))
    clip_b = b.assign(tf.maximum(0., b))
    train_step_with_clip = tf.group(clip_W, clip_b)

In this case W and b values will be clipped to 0 and not to small positive numbers.

Here is a small mnist example with clipping:

import tensorflow as tf

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

x = tf.placeholder(tf.uint8, [None, 28, 28])
x_vec = tf.cast(tf.reshape(x, [-1, 784]), tf.float32) / 255.

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x_vec, W) + b

y_target = tf.placeholder(tf.uint8, [None])
y_target_one_hot = tf.one_hot(y_target, 10)

cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_target_one_hot, logits=y))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

with tf.control_dependencies([train_step]):
    clip_W = W.assign(tf.maximum(0., W))
    clip_b = b.assign(tf.maximum(0., b))
    train_step_with_clip = tf.group(clip_W, clip_b)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_target_one_hot, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
  tf.global_variables_initializer().run()

  for i in range(1000):
    sess.run(train_step_with_clip, feed_dict={
        x: x_train[(i*100)%len(x_train):((i+1)*100)%len(x_train)],
        y_target: y_train[(i*100)%len(x_train):((i+1)*100)%len(x_train)]})

    if not i%100:
      print("Min_W:", sess.run(tf.reduce_min(W)))
      print("Min_b:", sess.run(tf.reduce_min(b)))

  print("Accuracy:", sess.run(accuracy, feed_dict={
      x: x_test,
      y_target: y_test}))

ContentLicense: CC BY-SA 4.0


问:
Angular directive to detect scrolling within an ng-repeat container
In my Angular app, I've created a simple directive to do something on scroll, based on the answer provided to a similar question here.

Here is the code to my onScroll directive:

```<code>(function() {
    'use strict';

    angular
        .module('proverbial')
        .directive('onScroll', Directive);

    Directive.$inject = [ '$document' ];
    function Directive($document) {

        var directive = {
            link: link,
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            element.bind('scroll', function(e) {
                console.warn(e)
                if (element[ 0 ].scrollTop + element[ 0 ].offsetHeight >= element[ 0 ].scrollHeight) {
                    scope.$apply(attr.onScroll);
                }
            });
        }
    }
})();
</code>```

This is to be used in the following HTML template:

```<code><div class="absolute" on-scroll="vm.totalDisplayed += 100">
    <span class="card hover"
    ng-repeat="proverb in vm.proverbs | limitTo: vm.totalDisplayed">
        <a>{{proverb.text | maxLength: 90}}</a>
    </span>
</div>
</code>```

The intention is to keep increasing vm.totalDisplayed on page scroll, to create an effect similar to lazy-loading.

However, when I scroll down to the end of what has been already loaded with ng-repeat, nothing happens. The console.warn(e) never triggers.

On the browser console I can see that the containing
 does indeed scroll up past the browser's window.

What's missing?

答:
You have a minor mistake in your code:

```<code>if (element[ 0 ].scrollTop + element[ 0 ].offsetHeight >= element[ 0 ].scrollHeight) {
    scope.$apply(attr.onScroll);
}
</code>```

attr is undefined. Should be attrs.

Furthermore, I can't reproduce the problem. I've created a Plunker from your code and the warning shows just fine. Only thing what I find weird is that I couldn't get vm.totalDisplayed += 100 to work. vm.totalDisplayed = vm.totalDisplayed + 100 worked though.

http://plnkr.co/edit/ooMFG4ZAZzxJf9zuChyA

Body:
In my Angular app, I've created a simple directive to do something on scroll, based on the answer provided to a similar question here.

Here is the code to my onScroll directive:

(function() {
    'use strict';

    angular
        .module('proverbial')
        .directive('onScroll', Directive);

    Directive.$inject = [ '$document' ];
    function Directive($document) {

        var directive = {
            link: link,
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            element.bind('scroll', function(e) {
                console.warn(e)
                if (element[ 0 ].scrollTop + element[ 0 ].offsetHeight >= element[ 0 ].scrollHeight) {
                    scope.$apply(attr.onScroll);
                }
            });
        }
    }
})();

This is to be used in the following HTML template:

        {{proverb.text | maxLength: 90}}

The intention is to keep increasing vm.totalDisplayed on page scroll, to create an effect similar to lazy-loading.

However, when I scroll down to the end of what has been already loaded with ng-repeat, nothing happens. The console.warn(e) never triggers.

On the browser console I can see that the containing
 does indeed scroll up past the browser's window.

What's missing?

Body:
You have a minor mistake in your code:

if (element[ 0 ].scrollTop + element[ 0 ].offsetHeight >= element[ 0 ].scrollHeight) {
    scope.$apply(attr.onScroll);
}

attr is undefined. Should be attrs.

Furthermore, I can't reproduce the problem. I've created a Plunker from your code and the warning shows just fine. Only thing what I find weird is that I couldn't get vm.totalDisplayed += 100 to work. vm.totalDisplayed = vm.totalDisplayed + 100 worked though.

http://plnkr.co/edit/ooMFG4ZAZzxJf9zuChyA


问:
Having issues with my email
I'm having trouble using my code below for an email in on of my programs.
I'm getting this error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials u15sm14739609wrc.10 - gsmtp

```<code>at SendEmail.main(SendEmail.java:36)
</code>```

Caused by: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials u15sm14739609wrc.10 - gsmtp

```<code>at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:932)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:843)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:748)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:31)
</code>```

Here is my code:

```<code>import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

   public static void main(String [] args) {

   final String username = "ae513309@mail.com"; //sender's email
   final String password = "xxxxxxxxxxx";//sender's password

   Properties props = new Properties();
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtp.host", "smtp.gmail.com"); //This is the smtp server address
   props.put("mail.smtp.port", "587");//This is the port for the smtp server

   Session session = Session.getInstance(props, new javax.mail.Authenticator(){
       protected PasswordAuthentication getPasswordAuthentication(){
           return new PasswordAuthentication(username, password);
       }
   });

   try{
       Message message = new MimeMessage(session);
       message.setFrom(new InternetAddress("ae513309@mail.com")); //from sender's email address
       message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("be513309@mail.com")); //to receivere's email address
       message.setSubject("Module Registration"); //Sets the subject of the email
       message.setContent("You're selected modules have been registered","text/html; charset=utf-8");//sets the body of the email
       Transport.send(message);//sends the entire message object

       System.out.println("Email was sent!");
   }
   catch (MessagingException fnfe){
       throw new RuntimeException(fnfe);//if the email address is bad or doesn't exist
   }
  }
}
</code>```

答:
=> OP, did you read JavaMail with Gmail: 535-5.7.1 Username and Password not accepted ? – @RC.

Thanks @RC. :) I used the code in the link and tweaked a few things in it :)

Title: Having issues with my email

Body:
I'm having trouble using my code below for an email in on of my programs.
I'm getting this error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials u15sm14739609wrc.10 - gsmtp

at SendEmail.main(SendEmail.java:36)

Caused by: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials u15sm14739609wrc.10 - gsmtp

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:932)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:843)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:748)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:31)

Here is my code:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

   public static void main(String [] args) {

   final String username = "ae513309@mail.com"; //sender's email
   final String password = "xxxxxxxxxxx";//sender's password

   Properties props = new Properties();
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtp.host", "smtp.gmail.com"); //This is the smtp server address
   props.put("mail.smtp.port", "587");//This is the port for the smtp server

   Session session = Session.getInstance(props, new javax.mail.Authenticator(){
       protected PasswordAuthentication getPasswordAuthentication(){
           return new PasswordAuthentication(username, password);
       }
   });

   try{
       Message message = new MimeMessage(session);
       message.setFrom(new InternetAddress("ae513309@mail.com")); //from sender's email address
       message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("be513309@mail.com")); //to receivere's email address
       message.setSubject("Module Registration"); //Sets the subject of the email
       message.setContent("You're selected modules have been registered","text/html; charset=utf-8");//sets the body of the email
       Transport.send(message);//sends the entire message object

       System.out.println("Email was sent!");
   }
   catch (MessagingException fnfe){
       throw new RuntimeException(fnfe);//if the email address is bad or doesn't exist
   }
  }
}


问:
fixing column data type and duplicate column problem
This is my programs complete code, the only problem is i want to fix the amount of decimal places that show up in my gridview. The problem is if i do this on the asp side the location of the column gets thrown off and the column is duplicated. I figured if i just remade the table on the asp side it would work only problem is if i remove the sql for that particular column the asp side column cannot get data.</p>

```<code> Imports System.Data.Sql
    Imports System.Data.SqlClient
    Imports System.Data
    Partial Class _Default
        Inherits System.Web.UI.Page
        Public saocmd As New SqlCommand()
        Public saoda As New SqlDataAdapter(saocmd)

        Dim saods As New DataSet

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            saocmd.Connection = conn
            conn.Open()

            Dim ds As New DataSet

            saocmd.CommandText = "SELECT B603SalesAsOFMASTER.SDESCR, B603SalesAsOFMASTER.DYYYY, B603SalesAsOFMASTER.AsOFSales, B603SalesAsOFMASTER.ASOFPAX, B603SalesAsOFMASTER.YESales, B603SalesAsOFMASTER.YEPAX, B603SalesAsOFMASTER.PCTofSales, B601SalesAsOF.Sales AS [Current Sales], B601SalesAsOF.PAX AS [Current PAX] FROM B603SalesAsOFMASTER INNER JOIN B601SalesAsOF ON B603SalesAsOFMASTER.SDESCR = B601SalesAsOF.SDESCR WHERE (B603SalesAsOFMASTER.DYYYY = '2008') AND (B601SalesAsOF.DYYYY = '2010')"
            saoda.Fill(saods, "salesasoftable")

            Dim pctofpax As New DataColumn
            pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
            pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
            saods.Tables("salesasoftable").Columns.Add(pctofpax)

            Dim avgppax As New DataColumn
            avgppax = New DataColumn("AVG PAX", GetType(Double))
            avgppax.Expression = "[Current Sales] / [Current PAX]"
            saods.Tables("salesasoftable").Columns.Add(avgppax)

            Dim projectedye As New DataColumn
            projectedye = New DataColumn("Projected YE Sales", GetType(Double))
            projectedye.Expression = "[Current Sales] / PCTofSales"
            saods.Tables("salesasoftable").Columns.Add(projectedye)

            Dim projectedyep As New DataColumn
            projectedyep = New DataColumn("Projected YE PAX", GetType(Double))
            projectedyep.Expression = "[Current PAX] / PCTPAX1"
            saods.Tables("salesasoftable").Columns.Add(projectedyep)

            GridView1.DataSource = saods

            GridView1.DataBind()

            saoda.FillSchema(saods, SchemaType.Mapped)

            conn.Close()
        End Sub
    End Class

ASP Side

     <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>

            <span lang="en-us">Sales As Of Analysis</span><br />
           <asp:GridView ID="GridView1" runat="server" BackColor="White"
                  BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
                  GridLines="Vertical">
        <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
        <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="#DCDCDC" />
        <Columns>
             <asp:Boundfield DataField="SDESCR"
                             HeaderText="Regions">
             </asp:Boundfield>

             <asp:Boundfield DataField="DYYYY"
                             HeaderText="DYYYY">
             </asp:Boundfield>

            <asp:Boundfield DataField="asofsales"
                             HeaderText="As Of Sales"
                             DataFormatString="{0:c}">
            </asp:Boundfield>
        </Columns>
    </asp:GridView>

        </div>
        </form>
    </body>
    </html>
</code>```

答: the answer was to turn off autogenerate columns!</p>

ContentLicense: CC BY-SA 2.5

Body:
This is my programs complete code, the only problem is i want to fix the amount of decimal places that show up in my gridview. The problem is if i do this on the asp side the location of the column gets thrown off and the column is duplicated. I figured if i just remade the table on the asp side it would work only problem is if i remove the sql for that particular column the asp side column cannot get data.

 Imports System.Data.Sql
    Imports System.Data.SqlClient
    Imports System.Data
    Partial Class _Default
        Inherits System.Web.UI.Page
        Public saocmd As New SqlCommand()
        Public saoda As New SqlDataAdapter(saocmd)

        Dim saods As New DataSet

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            saocmd.Connection = conn
            conn.Open()

            Dim ds As New DataSet

            saocmd.CommandText = "SELECT B603SalesAsOFMASTER.SDESCR, B603SalesAsOFMASTER.DYYYY, B603SalesAsOFMASTER.AsOFSales, B603SalesAsOFMASTER.ASOFPAX, B603SalesAsOFMASTER.YESales, B603SalesAsOFMASTER.YEPAX, B603SalesAsOFMASTER.PCTofSales, B601SalesAsOF.Sales AS [Current Sales], B601SalesAsOF.PAX AS [Current PAX] FROM B603SalesAsOFMASTER INNER JOIN B601SalesAsOF ON B603SalesAsOFMASTER.SDESCR = B601SalesAsOF.SDESCR WHERE (B603SalesAsOFMASTER.DYYYY = '2008') AND (B601SalesAsOF.DYYYY = '2010')"
            saoda.Fill(saods, "salesasoftable")

            Dim pctofpax As New DataColumn
            pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
            pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
            saods.Tables("salesasoftable").Columns.Add(pctofpax)

            Dim avgppax As New DataColumn
            avgppax = New DataColumn("AVG PAX", GetType(Double))
            avgppax.Expression = "[Current Sales] / [Current PAX]"
            saods.Tables("salesasoftable").Columns.Add(avgppax)

            Dim projectedye As New DataColumn
            projectedye = New DataColumn("Projected YE Sales", GetType(Double))
            projectedye.Expression = "[Current Sales] / PCTofSales"
            saods.Tables("salesasoftable").Columns.Add(projectedye)

            Dim projectedyep As New DataColumn
            projectedyep = New DataColumn("Projected YE PAX", GetType(Double))
            projectedyep.Expression = "[Current PAX] / PCTPAX1"
            saods.Tables("salesasoftable").Columns.Add(projectedyep)

            GridView1.DataSource = saods

            GridView1.DataBind()

            saoda.FillSchema(saods, SchemaType.Mapped)

            conn.Close()
        End Sub
    End Class

ASP Side

     <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title></title>

        <form id="form1" runat="server">

            Sales As Of Analysis

           <asp:GridView ID="GridView1" runat="server" BackColor="White"
                  BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
                  GridLines="Vertical">
        <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
        <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="#DCDCDC" />
        <Columns>
             <asp:Boundfield DataField="SDESCR"
                             HeaderText="Regions">
             </asp:Boundfield>

             <asp:Boundfield DataField="DYYYY"
                             HeaderText="DYYYY">
             </asp:Boundfield>

            <asp:Boundfield DataField="asofsales"
                             HeaderText="As Of Sales"
                             DataFormatString="{0:c}">
            </asp:Boundfield>
        </Columns>
    </asp:GridView>

        </form>


问:
Add class to element on submit of form when fields are null
I have a form that has several fields all within the class Contact that have a common header.

I need that header to turn red whenever the user hits submit with any contact field unfilled. These fields (first_name, last_name, company, Marketing_Phone, email) already have the class error added when submitted empty.

These fields are all in the class wrap_contact with the label Contact Information *. This label does not receive the class error on submit. This is what I need to add. I gave the label an id of label2. So my if then is if first_name, last_name, company, Marketing_phone, or email is null on submit then label2 has the error class added.

I attempted adding the following code, but it did not work.

```<code> $( "#pardot-form" ).submit(function( event ) {
    var someElements = document.querySelector("p.error,input[name=263882_11763pi_263882_11763]}");

    if (someElements !== "") {
       document.getElementById('p.label2').addClass = 'error';
    }

 };
</code>```

This form is visible online at http://link.rubiconglobal.com/l/263882/2017-03-24/7ssj.

答: The problem is that your submit still occurs and the page is reloaded. You will need to add event.preventDefault() and event.stopPropagation() to prevent submit action from occurring and reloading the page. Alternatively, since you are using jQuery, you can simply return false which does both. See: https://stackoverflow.com/a/1357151/1736092

Body:
I have a form that has several fields all within the class Contact that have a common header.

I need that header to turn red whenever the user hits submit with any contact field unfilled. These fields (first_name, last_name, company, Marketing_Phone, email) already have the class error added when submitted empty.

These fields are all in the class wrap_contact with the label Contact Information *. This label does not receive the class error on submit. This is what I need to add. I gave the label an id of label2. So my if then is if first_name, last_name, company, Marketing_phone, or email is null on submit then label2 has the error class added.

I attempted adding the following code, but it did not work.

 $( "#pardot-form" ).submit(function( event ) {
    var someElements = document.querySelector("p.error,input[name=263882_11763pi_263882_11763]}");

    if (someElements !== "") {
       document.getElementById('p.label2').addClass = 'error';
    }

 };

This form is visible online at http://link.rubiconglobal.com/l/263882/2017-03-24/7ssj.


问:
Mocking static method not working
The code I have written simply mocks a static method using powermock.

On running the test case, no last call on a mock available is thrown.

On debugging, found out it is thrown during expect statement.

Stack trace for the exception throwm :

```<code>java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:466)
at org.easymock.EasyMock.expect(EasyMock.java:444)
at junit.util.mock.Test.test1(Test.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
....
....
</code>```

Test class written:

```<code>import static org.junit.Assert.assertEquals;

import static org.powermock.api.easymock.PowerMock.mockStatic;
import static  org.powermock.api.support.membermodification.MemberMatcher.constructor;

import org.easymock.EasyMock;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.easymock.EasyMock.expect;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.easymock.PowerMock.replayAll;

import Testing;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Testing.class})
public class Test {

 @org.junit.Test
 public void test1() {
mockStatic(Testing.class);
expect(Testing.getWord()).andReturn("my Cal").anyTimes();
PowerMock.replay(Testing.class);
PowerMock.verify(Testing.class);
assertEquals(Testing.getWord(),"my Cal");
}
}
</code>```

Class under test :

```<code>public class Testing {
public static String getWord() {
    return "from test";
    }
}
</code>```

答:
I tried you code and it worked perfectly. So I'm not sure what to say. One thing that is not correct is that the verify should be at the end. But that's not what cause the issue.

I can give you the dependencies I used in case it was related to that.

```<code><dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>3.4</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-core</artifactId>
  <version>1.6.6</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-api-easymock</artifactId>
  <version>1.6.6</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-module-junit4</artifactId>
  <version>1.6.6</version>
</dependency>
</code>```

Title: Mocking static method not working

Body:
The code I have written simply mocks a static method using powermock.

On running the test case, no last call on a mock available is thrown.

On debugging, found out it is thrown during expect statement.

Stack trace for the exception throwm :

java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:466)
at org.easymock.EasyMock.expect(EasyMock.java:444)
at junit.util.mock.Test.test1(Test.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
....
....

Test class written:

import static org.junit.Assert.assertEquals;

import static org.powermock.api.easymock.PowerMock.mockStatic;
import static  org.powermock.api.support.membermodification.MemberMatcher.constructor;

import org.easymock.EasyMock;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.easymock.EasyMock.expect;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.easymock.PowerMock.replayAll;

import Testing;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Testing.class})
public class Test {

 @org.junit.Test
 public void test1() {
mockStatic(Testing.class);
expect(Testing.getWord()).andReturn("my Cal").anyTimes();
PowerMock.replay(Testing.class);
PowerMock.verify(Testing.class);
assertEquals(Testing.getWord(),"my Cal");
}
}

Class under test :

public class Testing {
public static String getWord() {
    return "from test";
    }
}

Body:
I tried you code and it worked perfectly. So I'm not sure what to say. One thing that is not correct is that the verify should be at the end. But that's not what cause the issue.

I can give you the dependencies I used in case it was related to that.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>3.4</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-core</artifactId>
  <version>1.6.6</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-api-easymock</artifactId>
  <version>1.6.6</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-module-junit4</artifactId>
  <version>1.6.6</version>
</dependency>