问:
Cannot import seaborn in ipython but works fine in python console
I have this wired problem on company issued windows 7 laptop.

install python 3.5 (anaconda), and other packages with conda. But I have a problem:

I cannot use seaborn in Jupyter (Ipython) notebook.

Checked if seaborn is properly installed by conda:

```<code>>conda list
...
seaborn                   0.7.0                    py35_0
...
</code>```

sure enough seaborn 0.7.0 is listed

run python in terminal and import seaborn, it worked fine:

```<code>[py3] >python
Python 3.5.1 |Continuum Analytics, Inc.| ...
>>> import seaborn
>>>
</code>```

run ipython in terminal, but I cannot import seaborn:

```<code>[py3] >ipython
Python 3.5.1 |Anaconda 2.5.0 (64-bit)| ....
In [1]: import seaborn
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-085c0287ecb5> in <module>()
----> 1 import seaborn

ImportError: No module named 'seaborn'
</code>```

I have remove and then installed scipy, numpy, seaborn. But still no luck.

Any hint?

Thanks!!

答: I get this error, and I can confirm that it has nothing to do with having the wrong virtualenv. If I import seaborn from the ipython console, it imports without error; if I do the same from the notebook, the module cannot be found. I have confirmed that the notebook is running from the virtualenv.

Body:
I have this wired problem on company issued windows 7 laptop.

install python 3.5 (anaconda), and other packages with conda. But I have a problem:

I cannot use seaborn in Jupyter (Ipython) notebook.

Checked if seaborn is properly installed by conda:

>conda list
...
seaborn                   0.7.0                    py35_0
...

sure enough seaborn 0.7.0 is listed

run python in terminal and import seaborn, it worked fine:

[py3] >python
Python 3.5.1 |Continuum Analytics, Inc.| ...
>>> import seaborn
>>>

run ipython in terminal, but I cannot import seaborn:

[py3] >ipython
Python 3.5.1 |Anaconda 2.5.0 (64-bit)| ....
In [1]: import seaborn
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-085c0287ecb5> in <module>()
----> 1 import seaborn

ImportError: No module named 'seaborn'

I have remove and then installed scipy, numpy, seaborn. But still no luck.

Any hint?

Thanks!!


来源: stackexchange

问:
How to make match() work with date in excel vba?
I'm having problem making the match() work in excel VBA. The code is:

```<code>x = Application.Match("Sep 2008", Range("F1:F1"), 0)
</code>```

The value in cell F1 is 9/1/2008.

Even if I changed Sep 2008 to 9/1/2008, it still doesn't return any value.

Any idea how to fix it?

答:
This way it works using this method:

Nbr,L, C as Integer

Datedeb as date

```<code>nbr = WorksheetFunction.Match(CLng(CDate(Datedeb)), Range(Cells(L, C), Cells(L + 100, C)), 0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having problem making the match() work in excel VBA. The code is:

x = Application.Match("Sep 2008", Range("F1:F1"), 0)

The value in cell F1 is 9/1/2008.

Even if I changed Sep 2008 to 9/1/2008, it still doesn't return any value.

Any idea how to fix it?

Body:
This way it works using this method:

Nbr,L, C as Integer

Datedeb as date

nbr = WorksheetFunction.Match(CLng(CDate(Datedeb)), Range(Cells(L, C), Cells(L + 100, C)), 0)


问:
.htaccess: remove html extension, force www and https
I developed a simple and pure html site with this pages:

```<code>index.html
page1.html
page2.html
etc
</code>```

And I would like to configure .htaccess to:

```<code>-Force https
-Force www
-Remove .html extension (/page1.html -> /page1)
-Redirect index.html -> /
-When someone types /page1.html to be redirected to /page1 (without html) or (if not possible) to 404 error page
</code>```

How should I configure my .htaccess?

Thanks in advance

答:
To remove .html and to force https://www , you can use the following rule :

```<code>RewriteEngine on
#force https+www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule (.*) https://www.%1/$1 [NE,L,R]
#Remove .html
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*?)/?$ /$1.html [L]
</code>```

Clear your browser cache before testing these rules.

Body:
I developed a simple and pure html site with this pages:

index.html
page1.html
page2.html
etc

And I would like to configure .htaccess to:

-Force https
-Force www
-Remove .html extension (/page1.html -> /page1)
-Redirect index.html -> /
-When someone types /page1.html to be redirected to /page1 (without html) or (if not possible) to 404 error page

How should I configure my .htaccess?

Thanks in advance

Body:
To remove .html and to force https://www , you can use the following rule :

RewriteEngine on
#force https+www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule (.*) https://www.%1/$1 [NE,L,R]
#Remove .html
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*?)/?$ /$1.html [L]

Clear your browser cache before testing these rules.


问:
Scrolling some div and same time scrolling body
First of all I didn't want to start trying this before asking, I am wondering how it is done to have like:

```<code>body{width: 100%; height: 150%; background: url('someimg.png') no-repeat; background-size: 100% 100%}
div{width: 100%; margin-top: 300px; height: 100%; background: red;}//and this div contains other elements so his content became scrollable
</code>```

Now You know some examples where while you scroll down the back is scrolling as well as front, but back is a lot slower than front in way like if i scrolled down 30% I want to body with 150% height scroll down for 30% and div with like 300% height scroll down for his 30% in same time so it looks like the background image is scrolling as well but slower.

I want to ask you which way is used for this?

```<code> CSS3, JAVASCRIPT or SOMETHING ELSE? OR MIXED?
</code>```

答:
Okay, so i think you are looking for the parallax effect. You can do that by manually coding it yourself using jquery or sometimes just CSS as well, but it might take a lot of time if you are just starting out, i would recommend that you use plugins like:

1. Parallax.js

2. Skrollr

3. Parallax-Scroll

and more... just google parallax scroll plugins, as some of them are quite easy to use which will save a lot of time.

Body:
First of all I didn't want to start trying this before asking, I am wondering how it is done to have like:

body{width: 100%; height: 150%; background: url('someimg.png') no-repeat; background-size: 100% 100%}
div{width: 100%; margin-top: 300px; height: 100%; background: red;}//and this div contains other elements so his content became scrollable

Now You know some examples where while you scroll down the back is scrolling as well as front, but back is a lot slower than front in way like if i scrolled down 30% I want to body with 150% height scroll down for 30% and div with like 300% height scroll down for his 30% in same time so it looks like the background image is scrolling as well but slower.

I want to ask you which way is used for this?

 CSS3, JAVASCRIPT or SOMETHING ELSE? OR MIXED?


问:
Other way to set a dimension of ImageButton
I am working with ImageButton in Android studio and during the development of the code I need to change the dimension of my ImageButtons.

I fuond in a previous question a part of solution.

stackoverflow.com/questions/10992241/set-imagebutton-height-and-width-in-code

```<code>android.view.ViewGroup.LayoutParams params1 = button1.getLayoutParams();
    params1.height = size;
    params1.width = size;
    button1.setLayoutParams(params1);
android.view.ViewGroup.LayoutParams params2 = button2.getLayoutParams();
    params2.height = size;
    params2.width = size;
    button2.setLayoutParams(params2);
android.view.ViewGroup.LayoutParams params3 = button3.getLayoutParams();
    params3.height = size;
    params3.width = size;
    button3.setLayoutParams(params3);
</code>```

Is there an other way to manage ImageButtons without repeat the follow code for all?

```<code>android.view.ViewGroup.LayoutParams params1 = button1.getLayoutParams();
    params1.height = size;
    params1.width = size;
</code>```

答:
You could name your buttons in layout in a sequential way (you may change them according to screen name, action name as you wish)

Like : button_1, button_2, button_3 etc.

You could get list of such button this way:

```<code>List<ImageButton> toBeResizedButtons() {

    ArrayList<ImageButton> buttons = new ArrayList<>();

    for (int i = 1; i <= NUMBER_OF_BUTTONS ; i++) {
        int id = getResources().getIdentifier("button_" + i, "id", getPackageName());
        buttons.add((ImageButton) findViewById(id));
    }

    return buttons;
}
</code>```

You could resize all of those in a single statement like this

```<code>for(ImageButton b : toBeResizedButtons()) {

     resize(b, size);
}
</code>```

Where resize() assumes you have a fixed size to resize them.

```<code>void resize(View v, int size) {

    android.view.ViewGroup.LayoutParams params = v.getLayoutParams();
    params.height = size;
    params.width = size;
}
</code>```

Body:
I am working with ImageButton in Android studio and during the development of the code I need to change the dimension of my ImageButtons.

I fuond in a previous question a part of solution.

stackoverflow.com/questions/10992241/set-imagebutton-height-and-width-in-code

android.view.ViewGroup.LayoutParams params1 = button1.getLayoutParams();
    params1.height = size;
    params1.width = size;
    button1.setLayoutParams(params1);
android.view.ViewGroup.LayoutParams params2 = button2.getLayoutParams();
    params2.height = size;
    params2.width = size;
    button2.setLayoutParams(params2);
android.view.ViewGroup.LayoutParams params3 = button3.getLayoutParams();
    params3.height = size;
    params3.width = size;
    button3.setLayoutParams(params3);

Is there an other way to manage ImageButtons without repeat the follow code for all?

android.view.ViewGroup.LayoutParams params1 = button1.getLayoutParams();
    params1.height = size;
    params1.width = size;

Body:
You could name your buttons in layout in a sequential way (you may change them according to screen name, action name as you wish)

Like : button_1, button_2, button_3 etc.

You could get list of such button this way:

List<ImageButton> toBeResizedButtons() {

    ArrayList<ImageButton> buttons = new ArrayList<>();

    for (int i = 1; i <= NUMBER_OF_BUTTONS ; i++) {
        int id = getResources().getIdentifier("button_" + i, "id", getPackageName());
        buttons.add((ImageButton) findViewById(id));
    }

    return buttons;
}

You could resize all of those in a single statement like this

for(ImageButton b : toBeResizedButtons()) {

     resize(b, size);
}

Where resize() assumes you have a fixed size to resize them.

void resize(View v, int size) {

    android.view.ViewGroup.LayoutParams params = v.getLayoutParams();
    params.height = size;
    params.width = size;
}


问:
"HTTP Error 403.14 - Forbidden" error when running the webapp
What is the reason for the error page I get when I run my webapp in Visual Studio. The URL is http://localhost:5000/
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

答:
Reason: http://localhost:5000 refers to the root of the webserver. So, for the above request, it tries to read the root folder of the server. However, IIS (express) by default doesn't allow you to view the file system. Therefore it shows above error.

Most probably you don't need to access the root of the server, instead you might need to access your webapp (ex: http://localhost:5000/myapp).

However, if you know exactly what you are doing then you can enable IIS to show the root directory (file system) using the following config in the Web.config of your application

Important: Below config should not be activated in a production or any
  publicly reachable environment which is obviously a high critical
  security issue.

```<code>  <system.webServer>
    <directoryBrowse enabled="true" />
    <modules runAllManagedModulesForAllRequests="true"></modules>
  </system.webServer>
</code>```

Body:
Reason: http://localhost:5000 refers to the root of the webserver. So, for the above request, it tries to read the root folder of the server. However, IIS (express) by default doesn't allow you to view the file system. Therefore it shows above error.

Most probably you don't need to access the root of the server, instead you might need to access your webapp (ex: http://localhost:5000/myapp).

However, if you know exactly what you are doing then you can enable IIS to show the root directory (file system) using the following config in the Web.config of your application

Important: Below config should not be activated in a production or any
  publicly reachable environment which is obviously a high critical
  security issue.

  <system.webServer>
    <directoryBrowse enabled="true" />
    <modules runAllManagedModulesForAllRequests="true"></modules>
  </system.webServer>


问:
Completely remove a div if screen width is less than 800 (mobile device)
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

```<code>    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);
</code>```

答:
You can use CSS media queries:

```<code>@media only screen and (max-width: 800px) {
    div {
        display: none;
    }
}
</code>```

If you want to stick with javascript, try the .offsetWidth property of DOM elements

Body:
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);

Body:
You can use CSS media queries:

@media only screen and (max-width: 800px) {
    div {
        display: none;
    }
}

If you want to stick with javascript, try the .offsetWidth property of DOM elements


问:
Passing arguments to a class
I am trying to create a mixin for a Polymer 2.0 components (class based syntax) with something like below. Is there a way to pass the options to the class the way I am doing it right now?

Polymer element definition with the mixin:

```<code>class PodcastListView extends PolymerApolloBehavior(Polymer.Element, myOptions) {
   //some code
}
</code>```

The mixin class:

```<code>export const PolymerApolloBehavior = (superclass, options) => class extends superclass {
    constructor() {
       console.log(options);
    }
}
</code>```

答:
I can suggest you function-wrapper for your PodcastListView class that will makes a new one with new behavior. It will look something like this:

```<code>export const PolymerApolloBehavior = (original, options) => {
  let result = Object.assign({}, original)
  const originalConstructor = result.prototype.constructor
  result.prototype.constructor = () => {
    console.log(options) // your behavior
    originalConstructor() // original constructor
  }
  // any changes of class
  return result
}
</code>```

And now you can apply your new behavior:

```<code>export default PolymerApolloBehavior(PodcastListView, {behaviorOptions})
</code>```

Title: Passing arguments to a class

Body:
I am trying to create a mixin for a Polymer 2.0 components (class based syntax) with something like below. Is there a way to pass the options to the class the way I am doing it right now?

Polymer element definition with the mixin:

class PodcastListView extends PolymerApolloBehavior(Polymer.Element, myOptions) {
   //some code
}

The mixin class:

export const PolymerApolloBehavior = (superclass, options) => class extends superclass {
    constructor() {
       console.log(options);
    }
}

Body:
I can suggest you function-wrapper for your PodcastListView class that will makes a new one with new behavior. It will look something like this:

export const PolymerApolloBehavior = (original, options) => {
  let result = Object.assign({}, original)
  const originalConstructor = result.prototype.constructor
  result.prototype.constructor = () => {
    console.log(options) // your behavior
    originalConstructor() // original constructor
  }
  // any changes of class
  return result
}

And now you can apply your new behavior:

export default PolymerApolloBehavior(PodcastListView, {behaviorOptions})


问:
How does group by works in sequelize?
I am looking for group by queries through Sequelize and cannot seem to find any documentation.

    SELECT column, count(column)
    FROM table
    GROUP BY column
```

答:
Example: how to add an convenient alias to the grouped function column.

I did this as a separate response mostly because it wouldn't format well in a comment...  otherwise I would have just added it to Sampat's answer.

```<code>function getSumsBySomeId() {
  const criteria = {
    attributes: ['some_id', [sequelize.fn('sum', sequelize.col('some_count')), 'some_count_sum']],
    group: ['some_id'],
    raw: true
  };
  return Table.getAll(criteria);
}
</code>```

YIELDS:

```<code>{ some_id: 42, some_count_sum: 100 },
{ some_id: 43, some_count_sum: 150 }
...
etc.
</code>```

ContentLicense: CC BY-SA 4.0

Title: How does group by works in sequelize?

Body:
Example: how to add an convenient alias to the grouped function column.

I did this as a separate response mostly because it wouldn't format well in a comment...  otherwise I would have just added it to Sampat's answer.

function getSumsBySomeId() {
  const criteria = {
    attributes: ['some_id', [sequelize.fn('sum', sequelize.col('some_count')), 'some_count_sum']],
    group: ['some_id'],
    raw: true
  };
  return Table.getAll(criteria);
}

YIELDS:

{ some_id: 42, some_count_sum: 100 },
{ some_id: 43, some_count_sum: 150 }
...
etc.


答:
Use CSS @media rules:

```<code>@media (max-width: 800px) {
    .div {
        display:none;
    }
}
</code>```

https://fiddle.jshell.net/Luc2zrbd/

Title: Completely remove a div if screen width is less than 800 (mobile device)

Body:
Use CSS @media rules:

@media (max-width: 800px) {
    .div {
        display:none;
    }
}

https://fiddle.jshell.net/Luc2zrbd/


问:
Turn Vector Into ones, zeros matrix in MATLAB
Say I have a 1xn dimensional vector with values between 0 - 9 like this:

```<code>A = [4 3 7 9 0]
</code>```

I want to convert this to an nx10 matrix like so:

```<code>A = [0 0 0 0 1 0 0 0 0 0
     0 0 0 1 0 0 0 0 0 0
     0 0 0 0 0 0 0 1 0 0
     0 0 0 0 0 0 0 0 0 1
     1 0 0 0 0 0 0 0 0 0]
</code>```

Where everything is zero, except for the column in the ith row represented by the ith element in the original vector A.

I can easily do this with a for loop:

```<code>newA = zeros(n,10);
for (i = 1:n)
    newA(i,A(i)) = 1;
end
A = newA;
</code>```

But is there a vectorized way to do this without a for loop?

答:
You can use bsxfun:

```<code>result = double(bsxfun(@eq, A(:)+1, 1:max(A)+1));
</code>```

Or sparse:

```<code>result = full(sparse(1:numel(A), A+1, 1));
</code>```

Body:
Say I have a 1xn dimensional vector with values between 0 - 9 like this:

A = [4 3 7 9 0]

I want to convert this to an nx10 matrix like so:

A = [0 0 0 0 1 0 0 0 0 0
     0 0 0 1 0 0 0 0 0 0
     0 0 0 0 0 0 0 1 0 0
     0 0 0 0 0 0 0 0 0 1
     1 0 0 0 0 0 0 0 0 0]

Where everything is zero, except for the column in the ith row represented by the ith element in the original vector A.

I can easily do this with a for loop:

newA = zeros(n,10);
for (i = 1:n)
    newA(i,A(i)) = 1;
end
A = newA;

But is there a vectorized way to do this without a for loop?

Body:
You can use bsxfun:

result = double(bsxfun(@eq, A(:)+1, 1:max(A)+1));

Or sparse:

result = full(sparse(1:numel(A), A+1, 1));


问:
Significant lag when loading image using UIImage from URL asynchronously
I am trying to write an iPad app that loads an image from a URL. I am using the following image loading code:

```<code>    url = [NSURL URLWithString:theURLString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    img = [[UIImage alloc] initWithData:data];
    [imageView setImage:img];
    [img release];
    NSLog(@"Image reloaded");
</code>```

All of that code gets added to a NSOperationQueue as an operation so it will load asynchronously and not cause my app to lock up if the image's websever is slow. I added the NSLog line so I could see in the console when this code finished executing.

I have noticed consistently that the image is updated in my app about 5 seconds AFTER the code finishes executing. However if I use this code on it's own without putting it in the NSOperationQUeue it seems to update the image almost immediately.

The lag is not caused entirely by a slow web server... I can load the image URL in Safari and it takes less than a second to load, or I can load it with the same code without the NSOperationQueue and it loads much more quickly.

Is there any way to reduce the lag before my image is displayed but keep using a NSOperationQueue?

答:
According to the documentation, the code you have written is invalid. UIKit objects may not be called anywhere but on the main thread. I'll bet that what you're doing happens to work in most respects but doesn't successfully alter the display, with the screen being updated by coincidence for some other reason.

Apple strongly recommend that threads are not the way to perform asynchronous URL fetches if you want to remain battery efficient. Instead you should be using NSURLConnection and allowing the runloop to organise asynchronous behaviour. It's not that hard to write a quick method that just accumulates data to an NSData as it comes then posts the whole thing on to a delegate when the connection is complete but assuming you'd rather stick with what you've got I'd recommend:

```<code>url = [NSURL URLWithString:theURLString];
NSData *data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:@selector(setImageViewImage:) withObject:data waitUntilDone:YES];

...

- (void)setImageViewImage:(NSData *)data
{
    img = [[UIImage alloc] initWithData:data];
    [imageView setImage:img];
    [img release];
    NSLog(@"Image reloaded");
}
</code>```

performSelectorOnMainThread does what the name says — the object is sent to will schedule the selector requested with the object given as a single parameter on the main thread as soon as the run loop can get to it. In this case 'data' is an autoreleased object on the pool in the thread implicitly created by the NSOperation. Because you need it to remain valid until it has been used, I've used waitUntilDone:YES. An alternative would be to make data something that you explicitly own and have the main thread method release it.

The main disadvantage of this method is that if the image returns in a compressed form (such as a JPEG or a PNG), it'll be decompressed on the main thread. To avoid that without making empirical guesses about the behaviour of UIImage that go above and beyond what is documented to be safe, you'd need to drop to the C level and use CoreGraphics. But I'm taking it as given that doing so is beyond the scope of this question.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to write an iPad app that loads an image from a URL. I am using the following image loading code:

    url = [NSURL URLWithString:theURLString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    img = [[UIImage alloc] initWithData:data];
    [imageView setImage:img];
    [img release];
    NSLog(@"Image reloaded");

All of that code gets added to a NSOperationQueue as an operation so it will load asynchronously and not cause my app to lock up if the image's websever is slow. I added the NSLog line so I could see in the console when this code finished executing.

I have noticed consistently that the image is updated in my app about 5 seconds AFTER the code finishes executing. However if I use this code on it's own without putting it in the NSOperationQUeue it seems to update the image almost immediately.

The lag is not caused entirely by a slow web server... I can load the image URL in Safari and it takes less than a second to load, or I can load it with the same code without the NSOperationQueue and it loads much more quickly.

Is there any way to reduce the lag before my image is displayed but keep using a NSOperationQueue?

Body:
According to the documentation, the code you have written is invalid. UIKit objects may not be called anywhere but on the main thread. I'll bet that what you're doing happens to work in most respects but doesn't successfully alter the display, with the screen being updated by coincidence for some other reason.

Apple strongly recommend that threads are not the way to perform asynchronous URL fetches if you want to remain battery efficient. Instead you should be using NSURLConnection and allowing the runloop to organise asynchronous behaviour. It's not that hard to write a quick method that just accumulates data to an NSData as it comes then posts the whole thing on to a delegate when the connection is complete but assuming you'd rather stick with what you've got I'd recommend:

url = [NSURL URLWithString:theURLString];
NSData *data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:@selector(setImageViewImage:) withObject:data waitUntilDone:YES];

...

- (void)setImageViewImage:(NSData *)data
{
    img = [[UIImage alloc] initWithData:data];
    [imageView setImage:img];
    [img release];
    NSLog(@"Image reloaded");
}

performSelectorOnMainThread does what the name says — the object is sent to will schedule the selector requested with the object given as a single parameter on the main thread as soon as the run loop can get to it. In this case 'data' is an autoreleased object on the pool in the thread implicitly created by the NSOperation. Because you need it to remain valid until it has been used, I've used waitUntilDone:YES. An alternative would be to make data something that you explicitly own and have the main thread method release it.

The main disadvantage of this method is that if the image returns in a compressed form (such as a JPEG or a PNG), it'll be decompressed on the main thread. To avoid that without making empirical guesses about the behaviour of UIImage that go above and beyond what is documented to be safe, you'd need to drop to the C level and use CoreGraphics. But I'm taking it as given that doing so is beyond the scope of this question.


问:
Bigcommerece issue regarding save_new_account
I want to add user in mailchimp list whenever user registerd in bigcommerece shop. I see it wil redirect on login.php?action=create_account url after registration but how could I put code in create_account function?

Can anybody give me the path of that function's file? Where i could put my mailchimp api code?

答:
create_account is not actually a function, but rather a URL query argument value that allows Bigcommerce to securely create the user account on the server. You do not have access to modify the code that creates the account.

I recommend using the free Mailchimp app that will do this for you automatically. Just install the app, authenticate your Mailchimp account, select the list you want users added to and it will do everything for you.

You can find the app here: https://www.bigcommerce.com/apps/mailchimp/


问:
resize and replace image using PHP
I am trying to resize and replace an image uploaded by the user but the most I can do is resize and output as another file.  I have used the library image magician to resize.

If someone can explain how I can do it without using the library it would be better.

```<code>public function add() {
     $f=Base::instance()->get('FILES');
     $fext=pathinfo ($f['usrimg']['name'],PATHINFO_EXTENSION);
     $this->copyFrom('POST');
     $this->save();
     $newName=str_pad($this->_id,5,"0").'.'.$fext;
     move_uploaded_file($f['usrimg']['tmp_name'], $newName);
     $this->load('id='.$this->_id);
     $this->set('photo',$newName);
     $this->update();

     require_once('php_image_magician.php');
     $magicianObj = new imageLib($newName);
     $magicianObj->resizeImage(100, 200);
     $magicianObj->saveImage('q.jpg', 100);
}
</code>```

答:
If you want to use gd library, for example you can use this code for resizing jpeg images:

```<code>  $image=file_get_contents('image.jpg');
  $src=imagecreatefromstring($image);
  $x=imagesx($src);
  $y=imagesy($src);
  $y1=100; //new width
  $x1=intval($y1*$x/$y); //new height proprtional to new width
  $dst=imagecreatetruecolor($x1,$y1);
  imagecopyresized($dst,$src,0,0,0,0,$x1,$y1,$x,$y);
  header("Content-Type: image/jpeg");
  imagejpeg($dst);
</code>```

Title: resize and replace image using PHP

Body:
I am trying to resize and replace an image uploaded by the user but the most I can do is resize and output as another file.  I have used the library image magician to resize.

If someone can explain how I can do it without using the library it would be better.

public function add() {
     $f=Base::instance()->get('FILES');
     $fext=pathinfo ($f['usrimg']['name'],PATHINFO_EXTENSION);
     $this->copyFrom('POST');
     $this->save();
     $newName=str_pad($this->_id,5,"0").'.'.$fext;
     move_uploaded_file($f['usrimg']['tmp_name'], $newName);
     $this->load('id='.$this->_id);
     $this->set('photo',$newName);
     $this->update();

     require_once('php_image_magician.php');
     $magicianObj = new imageLib($newName);
     $magicianObj->resizeImage(100, 200);
     $magicianObj->saveImage('q.jpg', 100);
}

Body:
If you want to use gd library, for example you can use this code for resizing jpeg images:

  $image=file_get_contents('image.jpg');
  $src=imagecreatefromstring($image);
  $x=imagesx($src);
  $y=imagesy($src);
  $y1=100; //new width
  $x1=intval($y1*$x/$y); //new height proprtional to new width
  $dst=imagecreatetruecolor($x1,$y1);
  imagecopyresized($dst,$src,0,0,0,0,$x1,$y1,$x,$y);
  header("Content-Type: image/jpeg");
  imagejpeg($dst);


问:
Xcode, C++ and SFML. Library issues
I am trying to compile a simpel code that will show me a window by using Xcode with my mac.
Everything seems to work and I get "Build Succeeded". But then nothing happens and I get the message:

dyld: Library not loaded: @rpath/libsfml-audio.2.4.dylib

Referenced
from:
/Users/zeeshanaslam/Library/Developer/Xcode/DerivedData/test-frpvsmylufuctqaphblszdoivflt/Build/Products/Debug/test

Reason: image not found

I am very new to programming, so please could any one help me with this problem.

My code is:

```<code>#include <SFML/Graphics.hpp>

int main(){
    sf::RenderWindow window(sf::VideoMode(640,480),"TEST");

    while (window.isOpen()){
        sf::Event evnt;

        while (window.pollEvent(evnt)){
            if(evnt.type == evnt.Closed)
                window.close();
        }

        window.clear();
        window.display();
    }
}
</code>```

I am not sure if its the code or Xcode is what causing the problem.

答:
I managed to run this code completely fine (OS X 10.11.6, Xcode 8.2.1). Here were my steps to getting it to run:

brew install sfml in the terminal.

Added /usr/local/sfml/cellar/sfml/2.4.2/include to my header search path in xcode.

In /usr/local/sfml/cellar/sfml/2.4.2/lib, I dragged the audio, graphics, network, system and window dylibs into xcode. This is sufficient for xcode to link (and run) your code.

Title: Xcode, C++ and SFML. Library issues

Body:
I am trying to compile a simpel code that will show me a window by using Xcode with my mac.
Everything seems to work and I get "Build Succeeded". But then nothing happens and I get the message:

dyld: Library not loaded: @rpath/libsfml-audio.2.4.dylib

Referenced
from:
/Users/zeeshanaslam/Library/Developer/Xcode/DerivedData/test-frpvsmylufuctqaphblszdoivflt/Build/Products/Debug/test

Reason: image not found

I am very new to programming, so please could any one help me with this problem.

My code is:

#include <SFML/Graphics.hpp>

int main(){
    sf::RenderWindow window(sf::VideoMode(640,480),"TEST");

    while (window.isOpen()){
        sf::Event evnt;

        while (window.pollEvent(evnt)){
            if(evnt.type == evnt.Closed)
                window.close();
        }

        window.clear();
        window.display();
    }
}

I am not sure if its the code or Xcode is what causing the problem.


问:
Mutiple quotation marks in HTML / Javascript
Sorry for the stupid question. I tried looking for an answer somewhere, but couldn't find any. I can't get this code to work:

```<code><div onmouseover="this.style.backgroundImage = 'url('#')'";>
</div>
</code>```

Help?

答:
Escape single quotes:</p>

```<code><div onmouseover="this.style.backgroundImage = 'url(\'#\')'">
</div>
</code>```

Body:
Sorry for the stupid question. I tried looking for an answer somewhere, but couldn't find any. I can't get this code to work:

Help?

Body:
Escape single quotes:

<div onmouseover="this.style.backgroundImage = 'url(\'#\')'">
</div>


问:
What's a good bit of JS or JQuery for horizontally scrolling news ticker
I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list.

The produced HTML needs to be standards compliant as well.

I have tried liScroll but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists.

I have also tried this News Ticker but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle.

Any suggestions are appreciated.

Edit

So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible.

Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping.

答:
Here's 2 other solutions that seem a bit simpler to implement:

newsticker

News ticker (BBC style)

OwnerDisplayName: Graphain

LastEditorDisplayName: Dustman

OwnerDisplayName: travis


问:
lesscss-maven-plugin from biz.gabrys.maven.plugins : using <compilerOptions>
I succeed to compile less to css. But i cannot figure out how pass Compiler Options to the compiler in order to generate the mapping source file too.

From the doc, it should be a thing like :

```<code><compilerOptions>
  <compilerOption>dumpLineNumbers:all</compilerOption>
</compilerOptions>
</code>```

But i get :

```<code>[INFO] Compiling 1 source to C:\workspaces\neon-dev\project\src\main\webapp\css
lesscss: couldn't open file dumpLineNumbers:all
</code>```

Any hints ?

答:
You have to pass options in command line style, e.g.:

```<code><compilerOptions>
    <compilerOption>--line-numbers=all</compilerOption>
</compilerOptions>
</code>```

See all available options: http://lesscss.org/usage/index.html#command-line-usage-options.

Version 2.0 of the biz.gabrys.maven.plugins:lesscss-maven-plugin will have a simpler configuration e.g.:

```<code><options>
    <lineNumbers>all</lineNumbers>
</options>
</code>```

Body:
I succeed to compile less to css. But i cannot figure out how pass Compiler Options to the compiler in order to generate the mapping source file too.

From the doc, it should be a thing like :

<compilerOptions>
  <compilerOption>dumpLineNumbers:all</compilerOption>
</compilerOptions>

But i get :

[INFO] Compiling 1 source to C:\workspaces\neon-dev\project\src\main\webapp\css
lesscss: couldn't open file dumpLineNumbers:all

Any hints ?

Body:
You have to pass options in command line style, e.g.:

<compilerOptions>
    <compilerOption>--line-numbers=all</compilerOption>
</compilerOptions>

See all available options: http://lesscss.org/usage/index.html#command-line-usage-options.

Version 2.0 of the biz.gabrys.maven.plugins:lesscss-maven-plugin will have a simpler configuration e.g.:

<options>
    <lineNumbers>all</lineNumbers>
</options>


问:
Why does my form not appear when connecting to a socket in the Load event?
The form from this code does not appear. How can I get it to show? Through the console, everything works.</p>

```<code> void Form1_Load(object sender, EventArgs e)
        {
            String host = Dns.GetHostName();//name kompa
            //ip pc
            IPAddress ip = Dns.GetHostByName(host).AddressList[0];
            const int port = 2222;
            label1.Text = host;
            label2.Text = "Сервер запущен на " + ip.ToString() + ":" + port.ToString();
            server.serversocket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.serversocket.Bind(new IPEndPoint(ip, port));
            server.serversocket.Listen(100);

            //ошибочка в цикле
            while (server.work)
            {
                MessageBox.Show("dsff");
                Socket handle = server.serversocket.Accept();
                richTextBox1.AppendText("новое подключение" + handle.RemoteEndPoint.ToString());
                new user(handle);

            }
</code>```

答:
You are blocking the ui thread. Using a separate thread for the synchronous socket server would be a solution. The other option would be to use an asynchronous socket so that the execution of the application is not blocked while it waits for a connection. Based on the socket code samples. </p>

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        InitSocketServer();
    }

    internal void InitSocketServer()
    {
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        var ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
        try
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(localEndPoint);
            listener.Listen(100);
            listener.BeginAccept(AcceptCallback, listener);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        string data = null;

        while (true)
        {
            var bytes = new byte[1024];
            int bytesRec = handler.Receive(bytes);
            data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
            if (data.IndexOf("<EOF>") > -1)
            {
                break;
            }
        }

        MessageBox.Show(handler.RemoteEndPoint + " : " + data);

        byte[] msg = Encoding.ASCII.GetBytes(data);

        handler.Send(msg);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Test button click");
    }
}
</code>```

Body:
The form from this code does not appear. How can I get it to show? Through the console, everything works.

 void Form1_Load(object sender, EventArgs e)
        {
            String host = Dns.GetHostName();//name kompa
            //ip pc
            IPAddress ip = Dns.GetHostByName(host).AddressList[0];
            const int port = 2222;
            label1.Text = host;
            label2.Text = "Сервер запущен на " + ip.ToString() + ":" + port.ToString();
            server.serversocket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.serversocket.Bind(new IPEndPoint(ip, port));
            server.serversocket.Listen(100);

            //ошибочка в цикле
            while (server.work)
            {
                MessageBox.Show("dsff");
                Socket handle = server.serversocket.Accept();
                richTextBox1.AppendText("новое подключение" + handle.RemoteEndPoint.ToString());
                new user(handle);

            }

Body:
You are blocking the ui thread. Using a separate thread for the synchronous socket server would be a solution. The other option would be to use an asynchronous socket so that the execution of the application is not blocked while it waits for a connection. Based on the socket code samples.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        InitSocketServer();
    }

    internal void InitSocketServer()
    {
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        var ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
        try
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(localEndPoint);
            listener.Listen(100);
            listener.BeginAccept(AcceptCallback, listener);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        string data = null;

        while (true)
        {
            var bytes = new byte[1024];
            int bytesRec = handler.Receive(bytes);
            data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
            if (data.IndexOf("<EOF>") > -1)
            {
                break;
            }
        }

        MessageBox.Show(handler.RemoteEndPoint + " : " + data);

        byte[] msg = Encoding.ASCII.GetBytes(data);

        handler.Send(msg);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Test button click");
    }
}


问:
Merge multiple arrays based on their index using javascript
I need to merge two arrays into a single array.  I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

    <title></title>

```

答:
You could use Array#reduce and Array#map for an arbitrary count of arrays with same length.

var a1 = [1, 2, 3, 4],
    a2 = ["a", "b", "c", "d"],
    a3 = [9, 8, 7, 6],
    a4 = ["z", "y", "x", "w"],
    result = [a1, a2, a3, a4].reduce((a, b) => a.map((v, i) => v + b[i]));

console.log(result);```
</div>
</div>
</p>

<p>ES5</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a1 = [1, 2, 3, 4],
    a2 = ["a", "b", "c", "d"],
    a3 = [9, 8, 7, 6],
    a4 = ["z", "y", "x", "w"],
    result = [a1, a2, a3, a4].reduce(function (a, b) {
        return a.map(function (v, i) {
            return v + b[i];
        });
    });

console.log(result);</code>```

Body:
You could use Array#reduce and Array#map for an arbitrary count of arrays with same length.

var a1 = [1, 2, 3, 4],
    a2 = ["a", "b", "c", "d"],
    a3 = [9, 8, 7, 6],
    a4 = ["z", "y", "x", "w"],
    result = [a1, a2, a3, a4].reduce((a, b) => a.map((v, i) => v + b[i]));

console.log(result);

ES5

var a1 = [1, 2, 3, 4],
    a2 = ["a", "b", "c", "d"],
    a3 = [9, 8, 7, 6],
    a4 = ["z", "y", "x", "w"],
    result = [a1, a2, a3, a4].reduce(function (a, b) {
        return a.map(function (v, i) {
            return v + b[i];
        });
    });

console.log(result);


答:
this is a naive implementation, the setinterval runs anyway and checks if it must "operate", the div is hidden under a certain window width, you can modify this logic by clearing and restarting the interval on desidered width, inside the resize function handler, and debouncing the resize event.</p>

```<code>function isMobilewidth () {
  return $(window).width() <= 800;
}

$(window).on('resize', function() {
    $('.chatMessages').toggle(isMobilewidth());
});

setInterval(function(){
  if (!isMobilewidth())
    $( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);
</code>```

Body:
So i've been looking around and i can't really find i good solution on this so i hope some of you could help me out...
I am trying to remove a div so it doesn't exist if my screen size is around the size of a mobile... I know there is display none which makes the div invisible but since i got a setInterval function on that div it stil load each 5 second... So my question is:

Can i remove a div completely if my screen is less than x pixels

or is it possible to only run my setinterval function when the width is more than x?

Thanks for your time!

    setInterval(function(){
$( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);

Body:
this is a naive implementation, the setinterval runs anyway and checks if it must "operate", the div is hidden under a certain window width, you can modify this logic by clearing and restarting the interval on desidered width, inside the resize function handler, and debouncing the resize event.

function isMobilewidth () {
  return $(window).width() <= 800;
}

$(window).on('resize', function() {
    $('.chatMessages').toggle(isMobilewidth());
});

setInterval(function(){
  if (!isMobilewidth())
    $( ".chatMessages" ).load( "getMeddelanden.php" );
},5000);


问:
How to delete quotation marks from a text file using batch file?
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

```<code>echo %name%>./User_Records/%username%.txt
</code>```

in the text file it is saving as

```<code>"Firstname Lastname"
</code>```

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

```<code>Firstname Lastname
</code>```

答:
The bat file you are using should really be altered, especially as the line you've provided from it has some issues, (mostly already mentioned).

SetLocal EnableDelayedExpansion
(Echo=!name:"=!)>"User_Records\%username%.txt"
EndLocal
```

<p>If you have no control over that bat file then something like this should do what you want:</p>

<pre class="lang-bat prettyprint-override"><code>@For /F "UseBackQ Delims=" %%A In ("User_Records\%username%.txt") Do @Echo(%%~A
</code>```

Alternatively:

@Set/P "FullName="<"User_Records\%username%.txt"
@Echo(%FullName:"=%
```

Body:
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

echo %name%>./User_Records/%username%.txt

in the text file it is saving as

"Firstname Lastname"

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

Firstname Lastname

Body:
The bat file you are using should really be altered, especially as the line you've provided from it has some issues, (mostly already mentioned).

SetLocal EnableDelayedExpansion
(Echo=!name:"=!)>"User_Records\%username%.txt"
EndLocal

If you have no control over that bat file then something like this should do what you want:

@For /F "UseBackQ Delims=" %%A In ("User_Records\%username%.txt") Do @Echo(%%~A

Alternatively:

@Set/P "FullName="<"User_Records\%username%.txt"
@Echo(%FullName:"=%


问:
Pie Chart not rendering React Chart.js
I'm trying to render a simple pie chart in a react component, using the Chart.js library.

I've managed to render a Line chart, but for some reason my Pie chart is just rendering an empty canvas. Is it a problem with the chartData not being valid? I'm not getting any kind of error.

```<code>import React, { Component, PropTypes } from 'react';
import * as axios from 'axios';
import s from './Test.css';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import cx from 'classnames';

var PieChart = require("react-chartjs").Pie;

class Test extends Component {

  constructor(props) {
    super(props);
    this.chartData = {
      datasets: [{
        data: [100, 200, 300],
        backgroundColor: ["#FF6384", "#36A2EB", "FFCE56"]
      }]
    };
    this.chartOptions = {
      scale: {
        reverse: true,
        ticks: {
          beginAtZero: true
        }
      }
    };
  };

  render() {
    return(<div className={s.graphic}><PieChart data={this.chartData} options={this.chartOptions} width="600" height="250" /></div>);
  }
}

export default withStyles(s)(Test);
</code>```

答:
Apologies for the first (non) answer. I've actually got somewhere:

The problem was my CSS.

```<code>canvas {
    width: 100% !important;
    height: auto !important;
}
</code>```

For some reason still not known to me forcing the pie chart sizes causes it not to render. Removing the css solved the rendering problem.

Title: Pie Chart not rendering React Chart.js

Body:
I'm trying to render a simple pie chart in a react component, using the Chart.js library.

I've managed to render a Line chart, but for some reason my Pie chart is just rendering an empty canvas. Is it a problem with the chartData not being valid? I'm not getting any kind of error.

import React, { Component, PropTypes } from 'react';
import * as axios from 'axios';
import s from './Test.css';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import cx from 'classnames';

var PieChart = require("react-chartjs").Pie;

class Test extends Component {

  constructor(props) {
    super(props);
    this.chartData = {
      datasets: [{
        data: [100, 200, 300],
        backgroundColor: ["#FF6384", "#36A2EB", "FFCE56"]
      }]
    };
    this.chartOptions = {
      scale: {
        reverse: true,
        ticks: {
          beginAtZero: true
        }
      }
    };
  };

  render() {
    return(
<PieChart data={this.chartData} options={this.chartOptions} width="600" height="250" />
);
  }
}

export default withStyles(s)(Test);

Body:
Apologies for the first (non) answer. I've actually got somewhere:

The problem was my CSS.

canvas {
    width: 100% !important;
    height: auto !important;
}

For some reason still not known to me forcing the pie chart sizes causes it not to render. Removing the css solved the rendering problem.


问:
VB.NET 2010 - Process.Start("filePath\Test.bat") not opening test.bat?
I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.

Code:

```<code>    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim url As New System.Uri("http://example/one/")
    Dim req As System.Net.WebRequest
    req = System.Net.WebRequest.Create(url)
    Dim resp As System.Net.WebResponse
    Dim filePath As String
    filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
    Try
        resp = req.GetResponse()
        resp.Close()
        req = Nothing
        Process.Start("filePath\Test.exe")
    Catch ex As Exception
        req = Nothing
        Me.Close()
    End Try
End Sub
</code>```

Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.

I hope you can help me :)

答:
You need to use cmd for opening batfiles:

```<code>Process.Start("cmd", "/c foobar/test.bat")
</code>```

be carefull, if the filepath contains spaces you have to add extra "" to make it work:)
your problem was, that a .bat file is not a process to start, only a file

Body:
I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.

Code:

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim url As New System.Uri("http://example/one/")
    Dim req As System.Net.WebRequest
    req = System.Net.WebRequest.Create(url)
    Dim resp As System.Net.WebResponse
    Dim filePath As String
    filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
    Try
        resp = req.GetResponse()
        resp.Close()
        req = Nothing
        Process.Start("filePath\Test.exe")
    Catch ex As Exception
        req = Nothing
        Me.Close()
    End Try
End Sub

Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.

I hope you can help me :)

Body:
You need to use cmd for opening batfiles:

Process.Start("cmd", "/c foobar/test.bat")

be carefull, if the filepath contains spaces you have to add extra "" to make it work:)
your problem was, that a .bat file is not a process to start, only a file


问:
typeof typeof x returns string and not object since type of null is object
I am new to js, trying to learn js, can you guys tell me why typeof typeof x returns string, providing code snippet below, if i understand this simple concept it will help me more:

```<code>var x=null;
console.log(typeof typeof x);
</code>```

答:
typeof x returns a string representation of the type of x. So, naturally, typeof typeof x is string.

From MDN:

The typeof operator returns a string indicating the type of the unevaluated operand.

Body:
I am new to js, trying to learn js, can you guys tell me why typeof typeof x returns string, providing code snippet below, if i understand this simple concept it will help me more:

var x=null;
console.log(typeof typeof x);


问:
Powershell script in VSTS Build Definition not updating AssemblyVersion.cs
I have a Project hosted in VSTS and I'm experimenting with the Build Definitions. I'm trying to execute a powershell script that updates the AssemblyVersion.cs before the Project is built. When I run the script locally it works fine, but when it's ran during the Build process, the script runs without error, but the AssemblyVersion.cs is not updated.

```<code>$regex = '\[assembly: AssemblyVersion\("(.*)"\)\]'
$assemblyInfoPath = "..\Properties\AssemblyInfo.cs"

(Get-Content $assemblyInfoPath) | ForEach-Object {
    if($_ -match $regex)
    {
        # Get current version, and update revision number
        $version = [version]$matches[1]
        $newVersion = "{0}.{1}.{2}.{3}" -f $version.Major, $version.Minor, $version.Build, ($version.Revision + 1)
        '[assembly: AssemblyVersion("{0}")]' -f $newVersion

        Write-Host "Version updated to: $newVersion"
    }
    else
    {
        $_
    }
} | Set-Content $assemblyInfoPath
</code>```

The Build output states that the version has been updated, but when I view AssemblyInfo.cs in the File Viewer it shows the old version.

答: The build process doesn't check in/commit changes made to source code automatically at the end of the process. You have to write a script to do that.</p>

Body:
I have a Project hosted in VSTS and I'm experimenting with the Build Definitions. I'm trying to execute a powershell script that updates the AssemblyVersion.cs before the Project is built. When I run the script locally it works fine, but when it's ran during the Build process, the script runs without error, but the AssemblyVersion.cs is not updated.

$regex = '\[assembly: AssemblyVersion\("(.*)"\)\]'
$assemblyInfoPath = "..\Properties\AssemblyInfo.cs"

(Get-Content $assemblyInfoPath) | ForEach-Object {
    if($_ -match $regex)
    {
        # Get current version, and update revision number
        $version = [version]$matches[1]
        $newVersion = "{0}.{1}.{2}.{3}" -f $version.Major, $version.Minor, $version.Build, ($version.Revision + 1)
        '[assembly: AssemblyVersion("{0}")]' -f $newVersion

        Write-Host "Version updated to: $newVersion"
    }
    else
    {
        $_
    }
} | Set-Content $assemblyInfoPath

The Build output states that the version has been updated, but when I view AssemblyInfo.cs in the File Viewer it shows the old version.


问:
C: Nested Ifs or Gotos
What is the best way to manage resources for a C program. Should I use a nested if structure or should I use goto statements?

I am aware there is a lot of taboo about goto statements. However, I think it is justified for local resource clean up. I have supplied two samples. One compares a nested if structure and another uses goto statements. I personally find the goto statements make the code easier to read. For those who might argue that the nested if prompt better structure, imagine if the datatype was something other than a char*, like a Windows handle. I feel that the nested if structure would get out of hand with a series of CreateFile functions or any other function that takes large quantities of parameters.

This article demonstrates that local goto statements create RAII for C code. The code is neat an easy to follow. Imagine that as a series of nested if statements.

I understand that goto is taboo in many other languages because their exists other control mechanisms like try/catch etc, however, in C it seems appropriate.

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

#define STRING_MAX 10

void gotoExample()
{
    char *string1, *string2, *string3, *string4, *string5;

    if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string1;
    if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string2;
    if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string3;
    if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string4;
    if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string5;

    //important code goes here

gotoExample_string5:
    free(string4);
gotoExample_string4:
    free(string3);
gotoExample_string3:
    free(string2);
gotoExample_string2:
    free(string1);
gotoExample_string1:
}

void nestedIfExample()
{
    char *string1, *string2, *string3, *string4, *string5;

    if (string1 = (char*) calloc(STRING_MAX, sizeof(char)))
    {
        if (string2 = (char*) calloc(STRING_MAX, sizeof(char)))
        {
            if (string3 = (char*) calloc(STRING_MAX, sizeof(char)))
            {
                if (string4 = (char*) calloc(STRING_MAX, sizeof(char)))
                {
                    if (string5 = (char*) calloc(STRING_MAX, sizeof(char)))
                    {
                        //important code here
                        free(string5);
                    }
                    free(string4);
                }
                free(string3);
            }
            free(string2);
        }
        free(string1);
    }
}

int main(int argc, char* argv[])
{
    nestedIfExample();
    gotoExample();
    return 0;
}
</code>```

I would also like to quote Linus Torvalds on goto statements inside the Linux Kernel.

And sometimes structure is bad, and
  gets into the way, and using a  "goto"
  is just much clearer.

For example, it is quite common to
  have conditionals THAT DO NOT NEST.

In which case you have two
  possibilities

use goto, and be happy, since it doesn't enforce nesting

This makes the code more readable,
  since the code just does what     the
  algorithm says it should do.

duplicate the code, and rewrite it in a nesting form so that you can

  use the structured jumps.

This often makes the code much LESS
  readable, harder to maintain,     and
  bigger.

The Pascal language is a prime example
  of the latter problem. Because it
  doesn't have a "break" statement,
  loops in (traditional) Pascal end up
  often looking like total shit, because
  you have to add totally arbitrary
  logic to say "I'm done now".

Is goto acceptable for resource management? Should I use nested if statements or is there a better way?

Update: Examples of Good Gotos In C

答:
For me, I prefer this style of goto error handling.  Taking Nick D's snippet one step further, it uses one general goto label for error handling.  </p>

```<code>void gotoExample()
{
    char *string1, *string2, *string3, *string4, *string5;
    string1 = string2 = string3 = string4 = string5 = NULL;

    if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;

    //important code goes here

HANDLE_ERROR:
  if (string5)
    free(string5);

  if (string4)
    free(string4);

  if (string3)
    free(string3);

  if (string2)
    free(string2);

  if (string1)
    free(string1);

}
</code>```

Title: C: Nested Ifs or Gotos

Body:
What is the best way to manage resources for a C program. Should I use a nested if structure or should I use goto statements?

I am aware there is a lot of taboo about goto statements. However, I think it is justified for local resource clean up. I have supplied two samples. One compares a nested if structure and another uses goto statements. I personally find the goto statements make the code easier to read. For those who might argue that the nested if prompt better structure, imagine if the datatype was something other than a char*, like a Windows handle. I feel that the nested if structure would get out of hand with a series of CreateFile functions or any other function that takes large quantities of parameters.

This article demonstrates that local goto statements create RAII for C code. The code is neat an easy to follow. Imagine that as a series of nested if statements.

I understand that goto is taboo in many other languages because their exists other control mechanisms like try/catch etc, however, in C it seems appropriate.

#include <stdlib.h>

#define STRING_MAX 10

void gotoExample()
{
    char *string1, *string2, *string3, *string4, *string5;

    if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string1;
    if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string2;
    if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string3;
    if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string4;
    if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto gotoExample_string5;

    //important code goes here

gotoExample_string5:
    free(string4);
gotoExample_string4:
    free(string3);
gotoExample_string3:
    free(string2);
gotoExample_string2:
    free(string1);
gotoExample_string1:
}

void nestedIfExample()
{
    char *string1, *string2, *string3, *string4, *string5;

    if (string1 = (char*) calloc(STRING_MAX, sizeof(char)))
    {
        if (string2 = (char*) calloc(STRING_MAX, sizeof(char)))
        {
            if (string3 = (char*) calloc(STRING_MAX, sizeof(char)))
            {
                if (string4 = (char*) calloc(STRING_MAX, sizeof(char)))
                {
                    if (string5 = (char*) calloc(STRING_MAX, sizeof(char)))
                    {
                        //important code here
                        free(string5);
                    }
                    free(string4);
                }
                free(string3);
            }
            free(string2);
        }
        free(string1);
    }
}

int main(int argc, char* argv[])
{
    nestedIfExample();
    gotoExample();
    return 0;
}

I would also like to quote Linus Torvalds on goto statements inside the Linux Kernel.

And sometimes structure is bad, and
  gets into the way, and using a  "goto"
  is just much clearer.

For example, it is quite common to
  have conditionals THAT DO NOT NEST.

In which case you have two
  possibilities

use goto, and be happy, since it doesn't enforce nesting

This makes the code more readable,
  since the code just does what     the
  algorithm says it should do.

duplicate the code, and rewrite it in a nesting form so that you can

  use the structured jumps.

This often makes the code much LESS
  readable, harder to maintain,     and
  bigger.

The Pascal language is a prime example
  of the latter problem. Because it
  doesn't have a "break" statement,
  loops in (traditional) Pascal end up
  often looking like total shit, because
  you have to add totally arbitrary
  logic to say "I'm done now".

Is goto acceptable for resource management? Should I use nested if statements or is there a better way?

Update: Examples of Good Gotos In C

Body:
For me, I prefer this style of goto error handling.  Taking Nick D's snippet one step further, it uses one general goto label for error handling.

void gotoExample()
{
    char *string1, *string2, *string3, *string4, *string5;
    string1 = string2 = string3 = string4 = string5 = NULL;

    if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;
    if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
        goto HANDLE_ERROR;

    //important code goes here

HANDLE_ERROR:
  if (string5)
    free(string5);

  if (string4)
    free(string4);

  if (string3)
    free(string3);

  if (string2)
    free(string2);

  if (string1)
    free(string1);

}


问:
java.net.UnknownHostException: appengine.google.com
Got this error. Any idea how to get rid of it?

Yesterday it was working fine but today I got these errors. I saw a known issue with this - link. But I didn't find any solution yet..

```<code> Oct 16, 2012 4:01:59 PM com.google.appengine.tools.info.RemoteVersionFactory getVersion

INFO: Unable to access https://appengine.google.com/api/updatecheck?runtime=java&release=1.7.1&timestamp=1345058163&api_versions=['1.0']
java.net.UnknownHostException: appengine.google.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:559)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:395)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:530)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:911)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at java.net.URL.openStream(URL.java:1010)
    at com.google.appengine.tools.info.RemoteVersionFactory.getVersion(RemoteVersionFactory.java:76)
    at com.google.appengine.tools.info.UpdateCheck.checkForUpdates(UpdateCheck.java:99)
    at com.google.appengine.tools.info.UpdateCheck.doNagScreen(UpdateCheck.java:174)
    at com.google.appengine.tools.info.UpdateCheck.maybePrintNagScreen(UpdateCheck.java:142)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:289)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
    at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:249)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:225)
Oct 16, 2012 4:01:59 PM com.google.apphosting.utils.jetty.JettyLogger info
INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
Oct 16, 2012 4:02:00 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed D:\WorkSpace\GAE\GST\war\WEB-INF/appengine-web.xml
Oct 16, 2012 4:02:00 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
INFO: Successfully processed D:\WorkSpace\GAE\GST\war\WEB-INF/web.xml
Oct 16, 2012 4:02:02 PM com.google.appengine.tools.development.DevAppServerImpl start
</code>```

答: This error is related to internet connection. I changed to other connection, it works</p>

Body:
Got this error. Any idea how to get rid of it?

Yesterday it was working fine but today I got these errors. I saw a known issue with this - link. But I didn't find any solution yet..

 Oct 16, 2012 4:01:59 PM com.google.appengine.tools.info.RemoteVersionFactory getVersion

INFO: Unable to access https://appengine.google.com/api/updatecheck?runtime=java&release=1.7.1&timestamp=1345058163&api_versions=['1.0']
java.net.UnknownHostException: appengine.google.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:559)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:395)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:530)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:911)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at java.net.URL.openStream(URL.java:1010)
    at com.google.appengine.tools.info.RemoteVersionFactory.getVersion(RemoteVersionFactory.java:76)
    at com.google.appengine.tools.info.UpdateCheck.checkForUpdates(UpdateCheck.java:99)
    at com.google.appengine.tools.info.UpdateCheck.doNagScreen(UpdateCheck.java:174)
    at com.google.appengine.tools.info.UpdateCheck.maybePrintNagScreen(UpdateCheck.java:142)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:289)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
    at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:249)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:225)
Oct 16, 2012 4:01:59 PM com.google.apphosting.utils.jetty.JettyLogger info
INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
Oct 16, 2012 4:02:00 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed D:\WorkSpace\GAE\GST\war\WEB-INF/appengine-web.xml
Oct 16, 2012 4:02:00 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
INFO: Successfully processed D:\WorkSpace\GAE\GST\war\WEB-INF/web.xml
Oct 16, 2012 4:02:02 PM com.google.appengine.tools.development.DevAppServerImpl start


问:
restrict access to the second form page
Helloo, I have a mutistep form functionality where
in "Step1" ( page 1 ) i have a form with three radioButton

And in step 2 (page2 ) I have another form.
So, My problem is that I want to restrict access to page2 via URL like if I type in Browser Addressbar : localhost/page1.php then it should load page1.php  but when I write localhost/page2.php then it should restrict user to have access for page2  and I would like to be redirected to localhost/page1.php

so i tried this :

page1 :

```<code>  <form class="type" action="page2.php" method="post">
   <label style="text-align:center;"> Type de compte :  </label>
                </br> </br>
   <input  type="radio" name="typeCompte" value="enseig"  required>
                 Enseignant </br>
   <input type="radio" name="typeCompte" value="etud" required>
                  Etudiant </br>
   <input type="radio"  name="typeCompte" value="admin" required>
                  Adminstrateur </br>
    </br></br>
   <input type="submit" class="make" name="submit" value="Valider">
   </form>

   <?php
    if(isset($_POST['submit']))
    {
       $_SESSION['log']=1;
    }
   ?>
</code>```

page 2 :

```<code> <?php
      session_start();
      if($_SESSION['log']!=1)
          header("location: page1.php");//redirecting to first page
 ?>
</code>```

答:
to check for session you can use isset command

```<code><?php session_start();

//if ! means not isset check if the session is active
if(!isset($_SESSION['log']))
header("location:page1.php");
?>
</code>```

in your page where you assign the session for log you can use it to assign any value for the user that you might need later. however do some reading about .htaccess and put your limited access file in a different dir
 on page 1

```<code>$t='1';
$_SESSION['log']=$t;
</code>```

and very very important on the first line after <?php on page 1 you must have

```<code>session_start();
</code>```

edit try this that i wrote only spend 5 min so it is not much but i tested it and it works make 2 file test1.php and test2.php
test1.php

```<code><?php
session_start();
if(isset($_POST['set'])){
    $log='1';
    $_session['log']=$log;
    include_once("test2.php");
    exit;
    }
if(isset($_POST['dontset'])){
    include_once("test2.php");
    }
?>
<html>
    <body>
        <form action="" method="post">
            <input type="submit" name="set" value="set">
            <input type="submit" name="dontset" value="dontset">
        </form>
    </body>
</html>
</code>```

test2.php

```<code><?php
session_start();
    if (!isset($_session['log'])){
        echo 'you are not authorised';
        header("location:test1.php");
    }
    if (isset($_session['log'])){
        echo 'you are authorised';
        }
?>
<html>
    <body>
        <form action="" method="post">
            <input type="submit" name="destroy" value="destroy">
        </form>
    </body>
</html>
<?php
    if(isset($_POST['destroy'])){
        session_destroy();
            include_once("test2.php");
        exit;
    }

?>
</code>```

it also shows you how to logout the user using sessions

Title: restrict access to the second form page

Body:
Helloo, I have a mutistep form functionality where
in "Step1" ( page 1 ) i have a form with three radioButton

And in step 2 (page2 ) I have another form.
So, My problem is that I want to restrict access to page2 via URL like if I type in Browser Addressbar : localhost/page1.php then it should load page1.php  but when I write localhost/page2.php then it should restrict user to have access for page2  and I would like to be redirected to localhost/page1.php

so i tried this :

page1 :

  <form class="type" action="page2.php" method="post">
    Type de compte :

   <input  type="radio" name="typeCompte" value="enseig"  required>
                 Enseignant

   <input type="radio" name="typeCompte" value="etud" required>
                  Etudiant

   <input type="radio"  name="typeCompte" value="admin" required>
                  Adminstrateur

   <input type="submit" class="make" name="submit" value="Valider">
   </form>

   <?php
    if(isset($_POST['submit']))
    {
       $_SESSION['log']=1;
    }
   ?>

page 2 :

 <?php
      session_start();
      if($_SESSION['log']!=1)
          header("location: page1.php");//redirecting to first page
 ?>

Body:
to check for session you can use isset command

<?php session_start();

//if ! means not isset check if the session is active
if(!isset($_SESSION['log']))
header("location:page1.php");
?>

in your page where you assign the session for log you can use it to assign any value for the user that you might need later. however do some reading about .htaccess and put your limited access file in a different dir
 on page 1

$t='1';
$_SESSION['log']=$t;

and very very important on the first line after <?php on page 1 you must have

session_start();

edit try this that i wrote only spend 5 min so it is not much but i tested it and it works make 2 file test1.php and test2.php
test1.php

<?php
session_start();
if(isset($_POST['set'])){
    $log='1';
    $_session['log']=$log;
    include_once("test2.php");
    exit;
    }
if(isset($_POST['dontset'])){
    include_once("test2.php");
    }
?>
<html>
    <body>
        <form action="" method="post">
            <input type="submit" name="set" value="set">
            <input type="submit" name="dontset" value="dontset">
        </form>
    </body>
</html>

test2.php

<?php
session_start();
    if (!isset($_session['log'])){
        echo 'you are not authorised';
        header("location:test1.php");
    }
    if (isset($_session['log'])){
        echo 'you are authorised';
        }
?>
<html>
    <body>
        <form action="" method="post">
            <input type="submit" name="destroy" value="destroy">
        </form>
    </body>
</html>
<?php
    if(isset($_POST['destroy'])){
        session_destroy();
            include_once("test2.php");
        exit;
    }

?>

it also shows you how to logout the user using sessions


问:
Iteration of Hash: JekyII
Hi I was trying to extract this ("Polk County", "short_name" => "Polk County")
in the 3rd row of this Hash but I can seem to get just the "Polk County"
this is my current code:

```<code>{% for county_hash in location.address_components %}
 {% for county in county_hash %}
  {{ county.long_name }}
 {% endfor %}
{% endfor %}

{
"0" => {
    "long_name" => "426", "short_name" => "426", "types" => ["street_number"]
}, "1" => {
    "long_name" => "Swanee Drive", "short_name" => "Swanee Dr", "types" => ["route"]
}, "2" => {
    "long_name" => "Livingston", "short_name" => "Livingston", "types" => ["locality", "political"]
}, "3" => {
    "long_name" => "Polk County", "short_name" => "Polk County", "types" => ["administrative_area_level_2", "political"]
}, "4" => {
    "long_name" => "Texas", "short_name" => "TX", "types" => ["administrative_area_level_1", "political"]
}, "5" => {
    "long_name" => "United States", "short_name" => "US", "types" => ["country", "political"]
}, "6" => {
    "long_name" => "77351", "short_name" => "77351", "types" => ["postal_code"]
}, "7" => {
    "long_name" => "8238", "short_name" => "8238", "types" => ["postal_code_suffix"]
}
</code>```

}

答:
While I'm not clear on what exactly you are trying to ask here, the following code

```<code>{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {{ county.long_name }}
  {% endfor %}
{% endfor %}
</code>```

will return a string of all long_names namely 426 Swanee Drive Livingston Polk County Texas United States 77351 8238 like you mentioned in the comments.

If you need to get just Polk County, you'll have to use the where filter:

```<code>{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {{ county.long_name | where: "shortname", "Polk County" }}
  {% endfor %}
{% endfor %}
</code>```

Title: Iteration of Hash: JekyII

Body:
Hi I was trying to extract this ("Polk County", "short_name" => "Polk County")
in the 3rd row of this Hash but I can seem to get just the "Polk County"
this is my current code:

{% for county_hash in location.address_components %}
 {% for county in county_hash %}
  {{ county.long_name }}
 {% endfor %}
{% endfor %}

{
"0" => {
    "long_name" => "426", "short_name" => "426", "types" => ["street_number"]
}, "1" => {
    "long_name" => "Swanee Drive", "short_name" => "Swanee Dr", "types" => ["route"]
}, "2" => {
    "long_name" => "Livingston", "short_name" => "Livingston", "types" => ["locality", "political"]
}, "3" => {
    "long_name" => "Polk County", "short_name" => "Polk County", "types" => ["administrative_area_level_2", "political"]
}, "4" => {
    "long_name" => "Texas", "short_name" => "TX", "types" => ["administrative_area_level_1", "political"]
}, "5" => {
    "long_name" => "United States", "short_name" => "US", "types" => ["country", "political"]
}, "6" => {
    "long_name" => "77351", "short_name" => "77351", "types" => ["postal_code"]
}, "7" => {
    "long_name" => "8238", "short_name" => "8238", "types" => ["postal_code_suffix"]
}

}

Body:
While I'm not clear on what exactly you are trying to ask here, the following code

{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {{ county.long_name }}
  {% endfor %}
{% endfor %}

will return a string of all long_names namely 426 Swanee Drive Livingston Polk County Texas United States 77351 8238 like you mentioned in the comments.

If you need to get just Polk County, you'll have to use the where filter:

{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {{ county.long_name | where: "shortname", "Polk County" }}
  {% endfor %}
{% endfor %}


问:
Regex + artificial intelligence
How would it be possible to write software that takes strings from a list and generates regular expressions based on a pattern in each line of the list.</p>

答:
As regular expressions are regular, it means they are used to match well defined patterns. If you need a kind of fuzzy matching, regular expressions are not needed or valid for that. If you need a "find similar text" algorithm, forget about regular expressions and use one of machine learning algorithms. Google "machine learning algorithms".

BTW, it's not too hard to make a program which would generate regular expressions matching a set of strings, but it would make sense if made only for fun or learning purposes, I can't imagine what else could it be useful for.

You could for example get an expression matching if something "looks like e-mail address", but you couldn't really tell if it's an e-mail address indeed, because to determine that you would need a strict set of rules applied, rules that could not be automatically determined from any sample of real-world e-mail addresses significantly smaller than the actual number of all existing e-mail accounts.

If I would do something like that for fun, I would first "extract" the rule of the length. No shorter than the shortest, no longer than the longest. Then character set limited to only existing in the set, or extended to full alphanumeric. No extending on special characters. It would probably work for some cases, fail miserably for others.

Title: Regex + artificial intelligence


问:
How to keep updating a webpage using NodeJS?
I am fairly new to NodeJS and I was wondering how I could have my node server keep updating the webpage.

So what I am doing is that I am fetching tweets from twitter, and for now I just want to display them all on a basic webpage. During its first run it looks like this:

Name: ap. Text: RT @APCentralRegion: Yevgeny Yevtushenko, Russian poet
  who focused on war atrocities, dies in Oklahoma
  Name: ap. Text: A week after
  hundreds attended anti-government protests in Russia, police arrest
  dozens at unauthorized rallies.
  ...

However, after the time interval of about a minute I get the following error message:

```<code>response.write("*********End of One Interval*********")
                  ^
TypeError: Cannot read property 'write' of undefined
</code>```

My code is below, keep in mind that when I had the tweet function inside my createServer it still showed the same behavior of it failing to properly update the page, however, the terminal window was always updated correctly using console.log

```<code>// Dependencies =========================
var
    twit = require('twit'),
    config = require('./config');

var http = require("http");
var url = require("url");

var Twitter = new twit(config);

// FAVORITE BOT====================
// Heavily modified from original tutorial.

var favoriteTweet = function(response, a, b){

        var params = {
        screen_name: a,
        count: b,
//      q: '#aprilfools, #aprilfoolsday',  // REQUIRED
//      result_type: 'recent', //recent tweets only.
      //lang: 'en'
    }

      //console.log("Params: " + params.q);
      // find the tweet
      Twitter.get('statuses/user_timeline', params, function(err,data){

        // find tweets
          //console.log(data);
        var tweet = data; //.statuses for actual tweets.
        //console.log(tweet);

        for(var result in tweet) {
            response.write("Name: " + a + ". Text: " + tweet[result].text + "\n");
            console.log("Resulting text: " + tweet[result].text);
            console.log("Created At: " + tweet[result].created_at);
        }

        //console.log(tweet);
          response.write("*********End of One Interval*********")
        console.log("*********End of One Interval*********")
      });
    }

http.createServer(function(request, response) {

    response.writeHead(200, {"Content-Type":"text/plain"});
        var params = url.parse(request.url, true).query;

        var a = params.name;
        var b = parseInt(params.count);

        // grab & 'favorite' as soon as program is running...
        favoriteTweet(response, a, b);

        // 'favorite' a tweet in every 1 minute
        setInterval(favoriteTweet, 60000);

}).listen(9090);
</code>```

答:
You have to pass arguments into the callback. Do the following:</p>

```<code> setInterval(function(){
      favoriteTweet(response,a,b)
 }, 60000);
</code>```

Body:
I am fairly new to NodeJS and I was wondering how I could have my node server keep updating the webpage.

So what I am doing is that I am fetching tweets from twitter, and for now I just want to display them all on a basic webpage. During its first run it looks like this:

Name: ap. Text: RT @APCentralRegion: Yevgeny Yevtushenko, Russian poet
  who focused on war atrocities, dies in Oklahoma
  Name: ap. Text: A week after
  hundreds attended anti-government protests in Russia, police arrest
  dozens at unauthorized rallies.
  ...

However, after the time interval of about a minute I get the following error message:

response.write("*********End of One Interval*********")
                  ^
TypeError: Cannot read property 'write' of undefined

My code is below, keep in mind that when I had the tweet function inside my createServer it still showed the same behavior of it failing to properly update the page, however, the terminal window was always updated correctly using console.log

// Dependencies =========================
var
    twit = require('twit'),
    config = require('./config');

var http = require("http");
var url = require("url");

var Twitter = new twit(config);

// FAVORITE BOT====================
// Heavily modified from original tutorial.

var favoriteTweet = function(response, a, b){

        var params = {
        screen_name: a,
        count: b,
//      q: '#aprilfools, #aprilfoolsday',  // REQUIRED
//      result_type: 'recent', //recent tweets only.
      //lang: 'en'
    }

      //console.log("Params: " + params.q);
      // find the tweet
      Twitter.get('statuses/user_timeline', params, function(err,data){

        // find tweets
          //console.log(data);
        var tweet = data; //.statuses for actual tweets.
        //console.log(tweet);

        for(var result in tweet) {
            response.write("Name: " + a + ". Text: " + tweet[result].text + "\n");
            console.log("Resulting text: " + tweet[result].text);
            console.log("Created At: " + tweet[result].created_at);
        }

        //console.log(tweet);
          response.write("*********End of One Interval*********")
        console.log("*********End of One Interval*********")
      });
    }

http.createServer(function(request, response) {

    response.writeHead(200, {"Content-Type":"text/plain"});
        var params = url.parse(request.url, true).query;

        var a = params.name;
        var b = parseInt(params.count);

        // grab & 'favorite' as soon as program is running...
        favoriteTweet(response, a, b);

        // 'favorite' a tweet in every 1 minute
        setInterval(favoriteTweet, 60000);

}).listen(9090);

Body:
You have to pass arguments into the callback. Do the following:

 setInterval(function(){
      favoriteTweet(response,a,b)
 }, 60000);


问:
Extract number from a GUID
Is there any possiblity to extract only the numbers from a GUID? I'm trying to achieve this because I don't want to display the GUID in a form, but the numbers within, which also are unique. </p>

答:
```<code>public string GetNumbersFromGuid(Guid Item)
{
    var result = string.Empty;

    var guidArray = Item.ToString().ToCharArray();

    int n;
    foreach (var item in guidArray)
    {
        if (int.TryParse(item.ToString(), out n) == true)
        {
            result += item.ToString();
        }
    }

    return result;
}
</code>```

Call it like:

```<code>var MyValue = GetNumbersFromGuid(Guid.NewGuid());
</code>```

Title: Extract number from a GUID

Body:
public string GetNumbersFromGuid(Guid Item)
{
    var result = string.Empty;

    var guidArray = Item.ToString().ToCharArray();

    int n;
    foreach (var item in guidArray)
    {
        if (int.TryParse(item.ToString(), out n) == true)
        {
            result += item.ToString();
        }
    }

    return result;
}

Call it like:

var MyValue = GetNumbersFromGuid(Guid.NewGuid());


问:
What am I doing wrong here ? html and css
Okay here is the desired result:

Here is the result I got:

The bottom row is in a straight line and not going in between the other containers like it need it be to be. I don't know how to go about getting the results I want like in the screenshot #1.

I hope someone can help me out. Thanks in advance.

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-size: 14px;
    background-color: #f2f2f2;
    font-family: 'Roboto', sans-serif;
}

h2 {
    font-size: 22px;
    font-weight: 300;
    padding-top: 7px;
}

.container {
    width: 948px;
    height: auto;
    margin: 0 auto;
    overflow: hidden;
    padding-top: 70px;
    padding-bottom: 50px;
}

.container ul {
    width: 100%;
    height: auto;
    list-style-type: none;
}

.container ul li {
    float: left;
    width: 300px;
    height: auto;
    padding: 10px;
    margin-right: 24px;
    border-radius: 6px;
    display: inline-block;
    background-color: #fff;
}

.container ul li:nth-child(3n) {
    margin: 0;
}

.container ul li span {
    font-size: 13px;
    padding-bottom: 7px;
    text-decoration: underline;
}

.container ul li p {
    color: #333;
    text-align: justify;
    padding-bottom: 15px;
}

.thumbnail-con {
    width: 100%;
    height: 174px;
    border-radius: 3px;
    background-color: #f2f2f2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>SimpleRead</title>
    <link rel="stylesheet" type="text/css"href="styles/main.css">
</head>

<body>
    <div class="container">
        <ul>
            <li>
                <div class="thumbnail-con"></div>
                <br>
                <span>Business</span>
                <h2>Caterpillar to close Illinois plant, lay off 800 workers</h2>
                <br>

            </li>
            <li>
                <div class="thumbnail-con"></div>
                <br>
                <span>Celebrity</span>
                <h2>Nicki Minaj signs with modeling agency</h2>
                <br>
                <p>Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.</p>
            </li>
            <li>
                <div class="thumbnail-con"></div>
                <br>
                <span>US</span>
                <h2>Racist ‘assassin’ indicted as terrorist in NYC murder of black man</h2>
                <br>
                <p>Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.</p>
            </li>
            <li>
                <div class="thumbnail-con"></div>
                <br>
                <span>US</span>
                <h2>Racist ‘assassin’ indicted as terrorist in NYC murder of black man</h2>
                <br>
                <p>Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.</p>
            </li>
            <li>
                <div class="thumbnail-con"></div>
                <br>
                <span>US</span>
                <h2>Racist ‘assassin’ indicted as terrorist in NYC murder of black man</h2>
                <br>
                <p>Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.</p>
            </li>
            <li>
                <div class="thumbnail-con"></div>
                <br>
                <span>US</span>
                <h2>Racist ‘assassin’ indicted as terrorist in NYC murder of black man</h2>
                <br>
                <p>Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.</p>
            </li>

        </ul>

    </div>
</body>

</html></code>```

答:
That layout is called the Masonry Grid. It can be achieved using CSS grid columns but it is quite a muddled task, i would recommend that you use a jQuery plugin like this one.

Hope this helps :)

Body:
Okay here is the desired result:

Here is the result I got:

The bottom row is in a straight line and not going in between the other containers like it need it be to be. I don't know how to go about getting the results I want like in the screenshot #1.

I hope someone can help me out. Thanks in advance.

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-size: 14px;
    background-color: #f2f2f2;
    font-family: 'Roboto', sans-serif;
}

h2 {
    font-size: 22px;
    font-weight: 300;
    padding-top: 7px;
}

.container {
    width: 948px;
    height: auto;
    margin: 0 auto;
    overflow: hidden;
    padding-top: 70px;
    padding-bottom: 50px;
}

.container ul {
    width: 100%;
    height: auto;
    list-style-type: none;
}

.container ul li {
    float: left;
    width: 300px;
    height: auto;
    padding: 10px;
    margin-right: 24px;
    border-radius: 6px;
    display: inline-block;
    background-color: #fff;
}

.container ul li:nth-child(3n) {
    margin: 0;
}

.container ul li span {
    font-size: 13px;
    padding-bottom: 7px;
    text-decoration: underline;
}

.container ul li p {
    color: #333;
    text-align: justify;
    padding-bottom: 15px;
}

.thumbnail-con {
    width: 100%;
    height: 174px;
    border-radius: 3px;
    background-color: #f2f2f2;
}

<!DOCTYPE html>

    <title>SimpleRead</title>
    <link rel="stylesheet" type="text/css"href="styles/main.css">

                Business

Caterpillar to close Illinois plant, lay off 800 workers

                Celebrity

Nicki Minaj signs with modeling agency

Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.

                US

Racist ‘assassin’ indicted as terrorist in NYC murder of black man

Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.

                US

Racist ‘assassin’ indicted as terrorist in NYC murder of black man

Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.

                US

Racist ‘assassin’ indicted as terrorist in NYC murder of black man

Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.

                US

Racist ‘assassin’ indicted as terrorist in NYC murder of black man

Prosecutors charged a white Baltimore racist Monday with murder as an act of terrorism for traveling to New York City and allegedly killing a 66-year-old black man with a sword.