问:
How do I code an event that calls a method
OK,

I have 5 methods

Move(), TurnRight(), TurnLeft(), Accelerate(), Decelerate()

I have 5 buttons on my windows form called:

Move, Turn Right, Turn Left, Accelerate, Decelerate

How do take values entered from texboxes and store them, so that when a user clicks one of those buttons it calls the method to perform calculations, and then display the information.

I just don't know how or what to code inside the event that I activated from the form.
Can anyone show me a sample of how they would do it?

Here is my move method

public void move()
        {
            double radians = direction * Math.PI / 180;

```<code>        //change the x location by the x vector of the speed
        X_Coordinate += (int)(speed * Math.Cos(radians));

        //change the y location by the y vectior of the speed
        Y_Coordinate -= (int)(speed * Math.Sin(radians));

    }
</code>```

I created a button on my form and named it btnMove

What should I code inside the event for my move button to call the move method and the display that for an outcome?

答:
I would store the initial values of the textboxes outside the method in the initiation of the class. Then in the button click event update the values that have changed. E.g.

int val1 = parseInt(textbox1.text);

int val2 = parseInt(textbox2.text);

private void Move()

{

```<code> val2 = parseInt(textbox2.text);
</code>```

}

Body:
OK,

I have 5 methods

Move(), TurnRight(), TurnLeft(), Accelerate(), Decelerate()

I have 5 buttons on my windows form called:

Move, Turn Right, Turn Left, Accelerate, Decelerate

How do take values entered from texboxes and store them, so that when a user clicks one of those buttons it calls the method to perform calculations, and then display the information.

I just don't know how or what to code inside the event that I activated from the form.
Can anyone show me a sample of how they would do it?

Here is my move method

public void move()
        {
            double radians = direction * Math.PI / 180;

        //change the x location by the x vector of the speed
        X_Coordinate += (int)(speed * Math.Cos(radians));

        //change the y location by the y vectior of the speed
        Y_Coordinate -= (int)(speed * Math.Sin(radians));

    }

I created a button on my form and named it btnMove

What should I code inside the event for my move button to call the move method and the display that for an outcome?

Body:
I would store the initial values of the textboxes outside the method in the initiation of the class. Then in the button click event update the values that have changed. E.g.

int val1 = parseInt(textbox1.text);

int val2 = parseInt(textbox2.text);

private void Move()

{

 val2 = parseInt(textbox2.text);

}


来源: stackexchange

问:
How to search two driver.find_element_by_partial_link_text
I am trying to create an automated bot to purchase items from supreme python/selenium.

When I am on the products page and I use a driver.find_element_by_partial_link_text('Flight Pant') to find the product I want to buy, however I also want to select the colour of the product so I use a driver.find_element_by_partial_link_text('Black') but by doing this I am returned with the first Black product on the page instead of Flight pants that are Black. Any idea how I would achieve this goal?

here is the site link where I am try to achieve this,

http://www.supremenewyork.com/shop/all/pants

Note - I am unable to use xpaths for this, as the products change on a weekly bases so I would be unable to get the xpath for the product before it goes live on the site.

Any advice or guidance would be greatly appreciated.

答:
After finding elements by the link text "Flight pants" , iterate over each found result and extract its css color attributes. Its a psuedo-code. You have to fine tune the specific color extraction web elements.

```<code>elements = driver.find_elements_by_partial_link_text("Flight Pants")

for element in elements :
  if(element.get_css_value('color').lower() == "black")
    element.click()
    break
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After finding elements by the link text "Flight pants" , iterate over each found result and extract its css color attributes. Its a psuedo-code. You have to fine tune the specific color extraction web elements.

elements = driver.find_elements_by_partial_link_text("Flight Pants")

for element in elements :
  if(element.get_css_value('color').lower() == "black")
    element.click()
    break


问:
Sample n random draw within group with different nrows
How can I draw n rows from a group where each group has a different number of rows?

```<code>df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)
</code>```

I've tried,

```<code>library(dplyr)
outdat <- df %>%
  group_by(color) %>%
  sample_n(nrow(.), replace = TRUE)
outdat
</code>```

but this returns a data.frame where nrow(.) are nrows from df and not the subset.

This SO post is close, but defines a specific number of row draws. I need it to be specific to group within dplyr.

Body:
How can I draw n rows from a group where each group has a different number of rows?

df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)

I've tried,

library(dplyr)
outdat <- df %>%
  group_by(color) %>%
  sample_n(nrow(.), replace = TRUE)
outdat

but this returns a data.frame where nrow(.) are nrows from df and not the subset.

This SO post is close, but defines a specific number of row draws. I need it to be specific to group within dplyr.

Body:
Another solution using slice and sample.int.
Reusing data from www:

outdat <- df %>%
group_by(color) %>%
slice(sample.int(n(),replace=T))
outdat

            X1          X2  color
1   1.71506499 -1.12310858   blue
2   0.07050839  2.16895597   blue
3   0.46091621 -0.40288484   blue
4   0.07050839  2.16895597   blue
5   0.07050839  2.16895597   blue
6   1.71506499 -1.12310858   blue
7  -1.26506123 -0.46665535   blue
8   1.55870831 -1.26539635   blue
9   0.12928774  1.20796200   blue
10  1.55870831 -1.26539635   blue
11  0.55391765 -0.28477301   pink
12 -0.29507148 -2.30916888   pink
13 -0.30596266  0.18130348   pink
14 -0.06191171 -1.22071771   pink
15  0.55391765 -0.28477301   pink
16  0.55391765 -0.28477301   pink
17  0.87813349 -0.70920076   pink
18  0.68864025  1.02557137   pink
19 -0.30596266  0.18130348   pink
20  0.68864025  1.02557137   pink
21  0.70135590  0.12385424    red
22  0.11068272  1.36860228    red
23 -1.96661716  0.58461375    red
24  0.40077145 -0.04287046    red
25  1.78691314  1.51647060    red
26 -0.55584113 -0.22577099    red
27  0.40077145 -0.04287046    red
28  1.78691314  1.51647060    red
29 -0.47279141  0.21594157    red
30 -0.47279141  0.21594157    red
31 -1.02600445 -0.33320738 yellow
32 -0.72889123 -1.01857538 yellow
33  1.25381492  2.05008469 yellow
34  0.83778704  0.44820978 yellow
35  1.25381492  2.05008469 yellow
36 -0.62503927 -1.07179123 yellow
37 -0.62503927 -1.07179123 yellow
38  0.83778704  0.44820978 yellow
39 -0.21797491 -0.50232345 yellow
40 -1.68669331  0.30352864 yellow


问:
How to remove the last comma in for loop
```<code>`<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>

<body>

<?php

for( $x=1 ; $x<=10 ; $x++){
echo "$x".",";
}
?>
</body>
</html>`
</code>```

1.output =1,2,3,4,5,6,7,8,9,10,

i have this output. how can i remove the last comma? your help is needed.

答:
```<code><?php
for( $x=1 ; $x<=10 ; $x++){
echo "$x";
if($x!=10)
echo ",";
}
?>
</code>```

Check for the last iteration and avoid ','

Body:
`<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>

<?php

for( $x=1 ; $x<=10 ; $x++){
echo "$x".",";
}
?>

`

1.output =1,2,3,4,5,6,7,8,9,10,

i have this output. how can i remove the last comma? your help is needed.

Body:
<?php
for( $x=1 ; $x<=10 ; $x++){
echo "$x";
if($x!=10)
echo ",";
}
?>

Check for the last iteration and avoid ','


问:
dashcode loading htm file problem
is there anything like webview in dashcode. I am trying this for so long now. I get a htm link while parsing my xml file and i need to load this htm link in next subview in stacklayout template, i am not able to figure out which component i should use to load the link in the new view.Any help would be appreciated...</p>

答:
I tried the same for a long time. To me it seems that it is not supported to link dashcode generated websites with other html content. The reason is for avoiding inhomogeneous styles.  Dashcode seems to be a tool to build a website from raw data that is stored in xml or json. For that it is a great tool.

The only way to get something like navigation between different views is using a stackLayout where you can have views as many as you want.

In iTunes University there are "Safari Development Essential Videos"...

ContentLicense: CC BY-SA 2.5

Title: dashcode loading htm file problem


问:
What characterizes a Lisp dialect?
What I am asking

What characteristics define a Lisp dialect as a dialect (and not some other language entirely)?

What I am not asking

Which dialect is the best? --or-- which dialect should I learn? --or-- Lisp vs. another language.

答:
My definition of lisps

A lisp family language is one that

has s-expression(-based) syntax.

has "prefix style" function application.

has so-called "lisp-style lists" constructed from cons cells.

Dialect? Language?

What makes a language a dialect of another language is really vague. C-style languages are obviously never refered to as C dialects, but for Lisp family languages, because they seem to have a common syntax (s-exp) and look the same to most people, they end up being called dialects.

I think the only "dialects" of a language are its own implementations. Scheme to Clojure to Common Lisp is like JavaScript to Perl to C, all very distinct from each other, and I think calling them Lisp dialects would only be confusing.

Even when I define it this way, it's still really opinionated. Chicken Scheme and Guile Scheme are both Scheme implementations, and they differ from each other enough to be Scheme dialects, but then I don't think Racket (#lang racket) should be called a Scheme dialect (or  even a Scheme implementation).

Title: What characterizes a Lisp dialect?

ContentLicense: CC BY-SA 4.0


问:
Repeating push notification in back4app
I am sending push notification from iOS and Android both by calling a cloud function, and in each device I am getting 5 times a single push notification. I am using parse database hosted on back4app.

Cloud code is given below:

```<code>Parse.Cloud.define("push", function (request, response) {
    var query = new Parse.Query(Parse.Installation);
    var userID = request.params.user;
    var message = request.params.message;
    var notificationType = request.params.notificationType;
    var user = new Parse.User();
    user.id = userID;
    query.equalTo('user', user);
    query.equalTo("allowPush", true);
    Parse.Push.send({
        where: query,
        data: {
                alert: message,
                sound: 'default',
                "type": notificationType
              }
        },  { useMasterKey: true });
});
</code>```

答:
Try to call reponse.success and response.error functions in the end of your cloud code function. Since your client code is not receiving the feedback if the call worked or not it is probably attempting to send again.</p>

```<code>Parse.Cloud.define("push", function (request, response) {
    var query = new Parse.Query(Parse.Installation);
    var userID = request.params.user;
    var message = request.params.message;
    var notificationType = request.params.notificationType;
    var user = new Parse.User();
    user.id = userID;
    query.equalTo('user', user);
    query.equalTo("allowPush", true);
    Parse.Push.send({
       where: query,
       data: {
            alert: message,
            sound: 'default',
            "type": notificationType
       }
    },
    {
       success: function () { response.success(); },
       error: function(err) { response.error(err); },
       useMasterKey: true
    });
});
</code>```

Title: Repeating push notification in back4app

Body:
I am sending push notification from iOS and Android both by calling a cloud function, and in each device I am getting 5 times a single push notification. I am using parse database hosted on back4app.

Cloud code is given below:

Parse.Cloud.define("push", function (request, response) {
    var query = new Parse.Query(Parse.Installation);
    var userID = request.params.user;
    var message = request.params.message;
    var notificationType = request.params.notificationType;
    var user = new Parse.User();
    user.id = userID;
    query.equalTo('user', user);
    query.equalTo("allowPush", true);
    Parse.Push.send({
        where: query,
        data: {
                alert: message,
                sound: 'default',
                "type": notificationType
              }
        },  { useMasterKey: true });
});

Body:
Try to call reponse.success and response.error functions in the end of your cloud code function. Since your client code is not receiving the feedback if the call worked or not it is probably attempting to send again.

Parse.Cloud.define("push", function (request, response) {
    var query = new Parse.Query(Parse.Installation);
    var userID = request.params.user;
    var message = request.params.message;
    var notificationType = request.params.notificationType;
    var user = new Parse.User();
    user.id = userID;
    query.equalTo('user', user);
    query.equalTo("allowPush", true);
    Parse.Push.send({
       where: query,
       data: {
            alert: message,
            sound: 'default',
            "type": notificationType
       }
    },
    {
       success: function () { response.success(); },
       error: function(err) { response.error(err); },
       useMasterKey: true
    });
});


问:
3 images centered in a row
I am trying to have three images centered in a row and then centered on the page. I've got them all in a row but I cannot get them centered. Any suggestions on getting my group to the middle? I tried 0 auto on the contain class and on the social class. so close!!

My HTML: first thing is div class=contain to wrap the whole thing, but for some reason if I try to include the class contain in HTML it disppears on Stack Overflow so excuse that.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contain">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div></code>```

答:
What I would recommend is to make use of flexbox container for the elements.

With flexbox, all you need is three different styles in order to centralise elements both horizontally and vertically:

display: flex;

align-items: self;

justify-content: center;

Note that you'll also need to set a height on the container, so that the elements can actually fill the vertical space.

This can be seen in the following, with a border added to showcase the area that the .container element occupies:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  border: 1px solid black;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div></code>```

Hope this helps! :)

Title: 3 images centered in a row

Body:
What I would recommend is to make use of flexbox container for the elements.

With flexbox, all you need is three different styles in order to centralise elements both horizontally and vertically:

display: flex;

align-items: self;

justify-content: center;

Note that you'll also need to set a height on the container, so that the elements can actually fill the vertical space.

This can be seen in the following, with a border added to showcase the area that the .container element occupies:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  border: 1px solid black;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}

<div class="container">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div>

Hope this helps! :)


问:
Set Opacity directly on Control which Storyboard Animation already set

I can setup UserControl Opacity property correctly, but not after bound to Storyboard.

UserControl MyControl;
MyControl.Opacity = 0.8;   /// This works before animation set

Storyboard sb = new Storyboard();
DoubleAnimation opacity = new DoubleAnimation();
opacity.From = 1;
opacity.To = 0;
opacity.Duration = TimeSpan.FromMilliseconds(400);
Storyboard.SetTarget(opacity, MyControl);
Storyboard.SetTargetProperty(opacity, new PropertyPath(UserControl.OpacityProperty));
sb.Children.Add(opacity);
sb.Begin();

sb.Completed += (object sender, EventArgs e) => {
  MyControl.Opacity = 0.5;   /// This doesn't work anymore
}
```

How to make it works after Storyboard complete?

答:
In some cases, it might appear that you can't change the value of a property after it has been animated.
You can try:

```<code>sb.Completed += (object sender, EventArgs e) => {
 sb.Remove(MyControl);
  MyControl.Opacity = 0.5;
}
</code>```

the reason is explained How to: Set a Property After Animating It with a Storyboard

Body:
I can setup UserControl Opacity property correctly, but not after bound to Storyboard.

UserControl MyControl;
MyControl.Opacity = 0.8;   /// This works before animation set

Storyboard sb = new Storyboard();
DoubleAnimation opacity = new DoubleAnimation();
opacity.From = 1;
opacity.To = 0;
opacity.Duration = TimeSpan.FromMilliseconds(400);
Storyboard.SetTarget(opacity, MyControl);
Storyboard.SetTargetProperty(opacity, new PropertyPath(UserControl.OpacityProperty));
sb.Children.Add(opacity);
sb.Begin();

sb.Completed += (object sender, EventArgs e) => {
  MyControl.Opacity = 0.5;   /// This doesn't work anymore
}

How to make it works after Storyboard complete?

Body:
In some cases, it might appear that you can't change the value of a property after it has been animated.
You can try:

sb.Completed += (object sender, EventArgs e) => {
 sb.Remove(MyControl);
  MyControl.Opacity = 0.5;
}

the reason is explained How to: Set a Property After Animating It with a Storyboard


问:
Ruby blocks behave unexpectedly when using "do"
I was trying to solve a coding puzzle: Take strings, and count the ones that don't include repeated words.

This code works:

```<code>def validate(passphrase)
  words = passphrase.split
  words == words.uniq
end

passphrases = File.readlines("../input/passphrases.txt")

p passphrases.count {|phrase| validate(phrase)}
#=> 337
</code>```

If I make one minor change with the count block, it counts all of the passphrases instead of just the ones that would return true when passed through the block:

```<code>p passphrases.count do |phrase|
  validate(phrase)
end
#=>512
</code>```

What's up with this?

答:
It is due to argument precedence with the do block.

Your first example is equivalent to:

p(passphrases.count {|phrase| validate(phrase)})

The second one with the do block is equivalent to:

```<code>p(passphrases.count) do |phrase|
  validate(phrase)
end
</code>```

Where the do is being applied to the p function.

If you want the second case to match the first, wrap the whole block in parenthesis:

```<code>p(passphrases.count do |phrase|
  validate(phrase)
end)
</code>```

Body:
I was trying to solve a coding puzzle: Take strings, and count the ones that don't include repeated words.

This code works:

def validate(passphrase)
  words = passphrase.split
  words == words.uniq
end

passphrases = File.readlines("../input/passphrases.txt")

p passphrases.count {|phrase| validate(phrase)}
#=> 337

If I make one minor change with the count block, it counts all of the passphrases instead of just the ones that would return true when passed through the block:

p passphrases.count do |phrase|
  validate(phrase)
end
#=>512

What's up with this?

Body:
It is due to argument precedence with the do block.

Your first example is equivalent to:

p(passphrases.count {|phrase| validate(phrase)})

The second one with the do block is equivalent to:

p(passphrases.count) do |phrase|
  validate(phrase)
end

Where the do is being applied to the p function.

If you want the second case to match the first, wrap the whole block in parenthesis:

p(passphrases.count do |phrase|
  validate(phrase)
end)


问:
Image and document upload/download in Elasticsearch
I'm looking to build an app around Elasticsearch with image and file upload/download. So a user uploads an image or document (PDF, Word, etc.), the image gets stored, and retrieved later by users and admin. It looks like Elastic can import/ingest data from files and images, but it is not clear to me if the image/file itself can be uploaded and retrieved. I just need to know if that is possible. If not I'll need to include another system into my app.</p>

答: ES is not a file system, it's just a search engine, you can store your file out of es.</p>


问:
Python ORM for massive data set
I have a massive data set of customer information (100s of millions of records, 50+ tables).

I am writing a python (twisted) app that I would like to interact with the dataset, performing table manipulation.  What I really need is an abstraction of 'table', so I can add/remove/alter columns/tables without having to resort to only creating SQL.

Is there an ORM that will not add significant overhead to my application, considering the size of the dataset?

答:
I thought that ORM solutions had to do with DQL (Data Query Language), not DDL (Data Definition Language).  You don't use ORM to add, alter, or remove columns at runtime.  You'd have to be able to add, alter, or remove object attributes and their types at the same time.

ORM is about dynamically generating SQL and developer's lift, not what you're alluding to.

Title: Python ORM for massive data set


问:
Install Chocolatey package if software is not installed, but skip install if newer version of software is already installed?
I'm using the following PowerShell script to install dotnetcore-windowshosting version 1.1.1 via an Octopus Deploy step.

ChocolateyPackageId is equal to "dotnetcore-windowshosting" and
$ChocolateyPackageVersion is equal to "1.1.1".

However, the target machine has a new version of DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed than the version being installed by the Chocolatey package. As a result, an error is raised alerting me that the target machine already has a newer version installed.

How can I install the package using cinst like in the script, however, ignore and don't raise an error if the package being installed (or a newer version) is already installed?

```<code>$chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "Machine") + "\bin"
if(-not (Test-Path $chocolateyBin)) {
    Write-Output "Environment variable 'ChocolateyInstall' was not found in the system variables. Attempting to find it in the user variables..."
    $chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "User") + "\bin"
}

$cinst = "$chocolateyBin\cinst.exe"
$choco = "$chocolateyBin\choco.exe"

if (-not (Test-Path $cinst) -or -not (Test-Path $choco)) {
    throw "Chocolatey was not found at $chocolateyBin."
}

if (-not $ChocolateyPackageId) {
    throw "Please specify the ID of an application package to install."
}

$chocoVersion = & $choco --version
Write-Output "Running Chocolatey version $chocoVersion"

$chocoArgs = @()
if([System.Version]::Parse($chocoVersion) -ge
   [System.Version]::Parse("0.9.8.33")) {
    Write-Output "Adding --confirm to arguments passed to Chocolatey"
    $chocoArgs += @("-y", "")
}

if (-not $ChocolateyPackageVersion) {
    Write-Output "Installing package $ChocolateyPackageId from the Chocolatey package repository..."
    & $cinst $ChocolateyPackageId $($chocoArgs)
}
else {
    Write-Output "Installing package $ChocolateyPackageId version $ChocolateyPackageVersion from the Chocolatey package repository..." & $cinst $ChocolateyPackageId -Version $ChocolateyPackageVersion $($chocoArgs)
}
</code>```

答:
Thanks for all the suggestions. Below seems to work for me</p>

```<code>$chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "Machine") + "\bin"
if(-not (Test-Path $chocolateyBin)) {
    Write-Output "Environment variable 'ChocolateyInstall' was not found in the system variables. Attempting to find it in the user variables..."
    $chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "User") + "\bin"
}

$cinst = "$chocolateyBin\cinst.exe"
$choco = "$chocolateyBin\choco.exe"

if (-not (Test-Path $cinst) -or -not (Test-Path $choco)) {
    throw "Chocolatey was not found at $chocolateyBin."
}

if (-not $ChocolateyPackageId) {
    throw "Please specify the ID of an application package to install."
}

$chocoVersion = & $choco --version
Write-Output "Running Chocolatey version $chocoVersion"

$chocoArgs = @()
if([System.Version]::Parse($chocoVersion) -ge [System.Version]::Parse("0.9.8.33")) {
    Write-Output "Adding --confirm to arguments passed to Chocolatey"
    $chocoArgs += @("-y", "")
}

if (-not $ChocolateyPackageVersion) {
    Write-Output "Installing package $ChocolateyPackageId from the Chocolatey package repository..."
    & $cinst $ChocolateyPackageId $($chocoArgs)
} else {
    Write-Output "Installing package $ChocolateyPackageId version $ChocolateyPackageVersion from the Chocolatey package repository..."
    & $cinst $ChocolateyPackageId -Version $ChocolateyPackageVersion $($chocoArgs) --force
}

$codes = $IgnoreExitCodes -split ','

if ($codes -Contains $lastExitCode)
{
    exit 0
}
</code>```

Body:
I'm using the following PowerShell script to install dotnetcore-windowshosting version 1.1.1 via an Octopus Deploy step.

ChocolateyPackageId is equal to "dotnetcore-windowshosting" and
$ChocolateyPackageVersion is equal to "1.1.1".

However, the target machine has a new version of DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed than the version being installed by the Chocolatey package. As a result, an error is raised alerting me that the target machine already has a newer version installed.

How can I install the package using cinst like in the script, however, ignore and don't raise an error if the package being installed (or a newer version) is already installed?

$chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "Machine") + "\bin"
if(-not (Test-Path $chocolateyBin)) {
    Write-Output "Environment variable 'ChocolateyInstall' was not found in the system variables. Attempting to find it in the user variables..."
    $chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "User") + "\bin"
}

$cinst = "$chocolateyBin\cinst.exe"
$choco = "$chocolateyBin\choco.exe"

if (-not (Test-Path $cinst) -or -not (Test-Path $choco)) {
    throw "Chocolatey was not found at $chocolateyBin."
}

if (-not $ChocolateyPackageId) {
    throw "Please specify the ID of an application package to install."
}

$chocoVersion = & $choco --version
Write-Output "Running Chocolatey version $chocoVersion"

$chocoArgs = @()
if([System.Version]::Parse($chocoVersion) -ge
   [System.Version]::Parse("0.9.8.33")) {
    Write-Output "Adding --confirm to arguments passed to Chocolatey"
    $chocoArgs += @("-y", "")
}

if (-not $ChocolateyPackageVersion) {
    Write-Output "Installing package $ChocolateyPackageId from the Chocolatey package repository..."
    & $cinst $ChocolateyPackageId $($chocoArgs)
}
else {
    Write-Output "Installing package $ChocolateyPackageId version $ChocolateyPackageVersion from the Chocolatey package repository..." & $cinst $ChocolateyPackageId -Version $ChocolateyPackageVersion $($chocoArgs)
}

Body:
Thanks for all the suggestions. Below seems to work for me

$chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "Machine") + "\bin"
if(-not (Test-Path $chocolateyBin)) {
    Write-Output "Environment variable 'ChocolateyInstall' was not found in the system variables. Attempting to find it in the user variables..."
    $chocolateyBin = [Environment]::GetEnvironmentVariable("ChocolateyInstall", "User") + "\bin"
}

$cinst = "$chocolateyBin\cinst.exe"
$choco = "$chocolateyBin\choco.exe"

if (-not (Test-Path $cinst) -or -not (Test-Path $choco)) {
    throw "Chocolatey was not found at $chocolateyBin."
}

if (-not $ChocolateyPackageId) {
    throw "Please specify the ID of an application package to install."
}

$chocoVersion = & $choco --version
Write-Output "Running Chocolatey version $chocoVersion"

$chocoArgs = @()
if([System.Version]::Parse($chocoVersion) -ge [System.Version]::Parse("0.9.8.33")) {
    Write-Output "Adding --confirm to arguments passed to Chocolatey"
    $chocoArgs += @("-y", "")
}

if (-not $ChocolateyPackageVersion) {
    Write-Output "Installing package $ChocolateyPackageId from the Chocolatey package repository..."
    & $cinst $ChocolateyPackageId $($chocoArgs)
} else {
    Write-Output "Installing package $ChocolateyPackageId version $ChocolateyPackageVersion from the Chocolatey package repository..."
    & $cinst $ChocolateyPackageId -Version $ChocolateyPackageVersion $($chocoArgs) --force
}

$codes = $IgnoreExitCodes -split ','

if ($codes -Contains $lastExitCode)
{
    exit 0
}


问:
Jsoup efficient way to remove html elements and children's
I want to remove html div and table tables tags and anything inside it(childs), what's the best way to do it ?

I tried traversing the document like this but it's not working, in Jsoup documentation it says that node.remove() removes the element from the DOM and his children's:

```<code>doc.traverse(new NodeVisitor() {
                @Override
                public void head(Node node, int i) {

                }

                @Override
                public void tail(Node node, int i) {
                    //Log.i(TAG,"node: "+node.nodeName());
                    if( node.nodeName().compareTo("table") == 0 ||
                            node.nodeName().compareTo("div") == 0 )
                       node.remove();

                }
            });
</code>```

答:
```<code>Document doc = Jsoup.parse(html);
doc.select("table *").remove();
</code>```

Body:
I want to remove html div and table tables tags and anything inside it(childs), what's the best way to do it ?

I tried traversing the document like this but it's not working, in Jsoup documentation it says that node.remove() removes the element from the DOM and his children's:

doc.traverse(new NodeVisitor() {
                @Override
                public void head(Node node, int i) {

                }

                @Override
                public void tail(Node node, int i) {
                    //Log.i(TAG,"node: "+node.nodeName());
                    if( node.nodeName().compareTo("table") == 0 ||
                            node.nodeName().compareTo("div") == 0 )
                       node.remove();

                }
            });


问:
Weblogic throws RuntimeException 'Exception reading license file' on https URLConnection
I'm trying to connect to an https url from a Java application connected to a weblogic server.

I've tried two approaches, one using URLConnection and one using HttpURLConnection, both give me the same error when I try to connect :

```<code>java.lang.RuntimeException: Exception occurred while reading the license file.
</code>```

I can connect to a normal http url just fine and my license.bea file is in the directory my IDE lists as bea home (being C:\bea1001 in this case) The file contains entries for SSL/Domestic and SSL/Export and it has read rights enabled. What's going wrong?

答:
This VM worked for me.
-DUseSunHttpHandler=true</p>

Body:
I'm trying to connect to an https url from a Java application connected to a weblogic server.

I've tried two approaches, one using URLConnection and one using HttpURLConnection, both give me the same error when I try to connect :

java.lang.RuntimeException: Exception occurred while reading the license file.

I can connect to a normal http url just fine and my license.bea file is in the directory my IDE lists as bea home (being C:\bea1001 in this case) The file contains entries for SSL/Domestic and SSL/Export and it has read rights enabled. What's going wrong?


问:
Code First Mapping and Repositories
I am learning the repository pattern and entity framework. I have a question regarding how to map my classes with EF 6 Code First (Existing Db). I know there a lot of questions about this (and I've readed maany of them) but still it's hard for me to understand something, which appears to be "logic" but it's getting me crazy (maybe I have readed too many different opinions...)

Problem (Example)

A table Processes which stores different processes like offer, receipt, order etc.. One of the columns of the table is AddDate which represents when this process was added to the DB.

Now I want to write a library to access this DB to use it in different apps, since it's the core Db in the company.

In the library I want to expose for example a ProcessRepository with a method GetByAddDateRange which returns the processes added after, before or in a given time range.

Question

So, now EF with CodeFirst to an existing DB first generates for me a class for every table with a property for every field. So I have a class Process (from now ProcessEntity) with a property AddDate.

Now in my "domain model", the classes that I want to use in my businnes logic etc, I want to have a class Process (from now ProcessDomain) but this should not have an AddDate property, since it's not important for the "object" or is part of its "properties".

So now how should I do then if I want to get ProcessDomains from my ProcessRepository using this AddDate as condition?

If I use directly ProcessEntity as "domain model" (class generated by EF) and if I understand it right, I have to have a property called AddDate since I will need it in my repo when doing sth like Return _dbContext.Set(Of Process).Where(Func(s)s.AddDate>addDate) or not?

I could (like I've read) have a class ProcessEntity and ProcessDomain and map manually between them in my repository. If I understand it right the repo should return the expected type for the layer above, in this case should return my domainModel class.

Do I understand it?

So for me the first option appears just in close to all scenarios useless, since you have to have specific properties in your classes.  so it doesn't matter how I try to look at the problem I always see the need to map manually when using an existing db.

Maybe I am missing sth or understanding sth wrong, so please let me know.

答:
Option 1:

Create DTOs that have what you actually want. Map between the entities and the DTOs when reading/writing. (The mapping is tedious and error prone. AutoMapper helps a lot.)

Option 2:

Use attributes such as DataContract/DataMember on your entities to control what fields are serialized and which are ignored.

Still error prone because entities are full of collections that aren't necessarily populated.

Option 3:

Use a different ORM. Tortuga Chain is designed specifically for working with DTOs and ViewModels without the need to map them to entities.

https://docevaad.github.io/Chain/Introduction.htm

Title: Code First Mapping and Repositories


问:
OSError: cannot identify image file 'dataSet/.DS_Store'
I am trying to run a facial recognition trainer that looks at a folder of jpg images of faces

```<code>import os                                               # importing the OS for path
import cv2                                              # importing the OpenCV library
import numpy as np                                      # importing Numpy library
from PIL import Image                                   # importing Image library

EigenFace = cv2.face.EigenFaceRecognizer_create(15)      # creating EIGEN FACE RECOGNISER
FisherFace = cv2.face.FisherFaceRecognizer_create(2)     # Create FISHER FACE RECOGNISER
LBPHFace = cv2.face.LBPHFaceRecognizer_create(1, 1, 7,7) # Create LBPH FACE RECOGNISER

path = 'dataSet'                                        # path to the photos
def getImageWithID (path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    FaceList = []
    IDs = []
    for imagePath in imagePaths:
        faceImage = Image.open(imagePath).convert('L')  # Open image and convert to gray
        faceImage = faceImage.resize((110,110))         # resize the image so the EIGEN recogniser can be trained
        faceNP = np.array(faceImage, 'uint8')           # convert the image to Numpy array
        ID = int(os.path.split(imagePath)[-1].split('.')[1])    # Retrieve the ID of the array
        FaceList.append(faceNP)                         # Append the Numpy Array to the list
        IDs.append(ID)                                  # Append the ID to the IDs list
        cv2.imshow('Training Set', faceNP)              # Show the images in the list
        cv2.waitKey(1)
    return np.array(IDs), FaceList                      # The IDs are converted in to a Numpy array
IDs, FaceList = getImageWithID(path)
</code>```

which in turn returns the error

```<code>Traceback (most recent call last):
  File "/Users/jef/PycharmProjects/testProject/Python/Trainer_All.py", line 28, in <module>
    IDs, FaceList = getImageWithID(path)
  File "/Users/jef/PycharmProjects/testProject/Python/Trainer_All.py", line 19, in getImageWithID
    faceImage = Image.open(imagePath).convert('L')  # Open image and convert to gray
  File "/Users/jef/venv1/lib/python3.6/site-packages/PIL/Image.py", line 2452, in open
    % (filename if filename else fp))
OSError: cannot identify image file 'dataSet/.DS_Store'
</code>```

The folder dataSet exists and i'm running the code on my mac, and the most recent versions of Pillow, numpy and cv2, I've googled the OSError but not much came up to help this particular problem. Any ideas?

答:
os.listdir() will give you every single file in the directory, including hidden files like .DS_Store. In macOS, .DS_Store is a hidden file (any file starting with a . is hidden from Finder) inserted in directories whenever you view them with Finder to speed up loading the file icons and saving your preferences for thumbnail sizes and such in that folder. You can read more about the file on Wikipedia.

You can see the file if you navigate to the directory and list the files in terminal with ls -a.

In any case, you just need to not try and read that as an image file. There are a bazillion ways to avoid this, here's a few:

```<code>for imagePath in imagePaths:
    if imagePath == directory + '.DS_Store':
        continue
    # rest of your program
</code>```

or

```<code>imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
if directory + '.DS_Store' in imagePaths:
    imagePaths.remove(directory + '.DS_Store')
</code>```

or just use glob to grab files only with the extensions you want:

```<code>import glob
imagePaths = [f for f in glob.glob(directory+'*.jpg')]  # or .png, .tif, etc
</code>```

Here the * is a wildcard meaning "any sequence of characters" so this will grab directory/1.jpg and directory/asdf.jpg and all other possibilities starting with directory/ and ending with .jpg.

Or just remove it from your directory in terminal with

```<code>rm .DS_Store
</code>```

but this is only a temporary solution as macOS will insert the file again next time you view the folder in Finder.

Body:
I am trying to run a facial recognition trainer that looks at a folder of jpg images of faces

import os                                               # importing the OS for path
import cv2                                              # importing the OpenCV library
import numpy as np                                      # importing Numpy library
from PIL import Image                                   # importing Image library

EigenFace = cv2.face.EigenFaceRecognizer_create(15)      # creating EIGEN FACE RECOGNISER
FisherFace = cv2.face.FisherFaceRecognizer_create(2)     # Create FISHER FACE RECOGNISER
LBPHFace = cv2.face.LBPHFaceRecognizer_create(1, 1, 7,7) # Create LBPH FACE RECOGNISER

path = 'dataSet'                                        # path to the photos
def getImageWithID (path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    FaceList = []
    IDs = []
    for imagePath in imagePaths:
        faceImage = Image.open(imagePath).convert('L')  # Open image and convert to gray
        faceImage = faceImage.resize((110,110))         # resize the image so the EIGEN recogniser can be trained
        faceNP = np.array(faceImage, 'uint8')           # convert the image to Numpy array
        ID = int(os.path.split(imagePath)[-1].split('.')[1])    # Retrieve the ID of the array
        FaceList.append(faceNP)                         # Append the Numpy Array to the list
        IDs.append(ID)                                  # Append the ID to the IDs list
        cv2.imshow('Training Set', faceNP)              # Show the images in the list
        cv2.waitKey(1)
    return np.array(IDs), FaceList                      # The IDs are converted in to a Numpy array
IDs, FaceList = getImageWithID(path)

which in turn returns the error

Traceback (most recent call last):
  File "/Users/jef/PycharmProjects/testProject/Python/Trainer_All.py", line 28, in <module>
    IDs, FaceList = getImageWithID(path)
  File "/Users/jef/PycharmProjects/testProject/Python/Trainer_All.py", line 19, in getImageWithID
    faceImage = Image.open(imagePath).convert('L')  # Open image and convert to gray
  File "/Users/jef/venv1/lib/python3.6/site-packages/PIL/Image.py", line 2452, in open
    % (filename if filename else fp))
OSError: cannot identify image file 'dataSet/.DS_Store'

The folder dataSet exists and i'm running the code on my mac, and the most recent versions of Pillow, numpy and cv2, I've googled the OSError but not much came up to help this particular problem. Any ideas?

Body:
os.listdir() will give you every single file in the directory, including hidden files like .DS_Store. In macOS, .DS_Store is a hidden file (any file starting with a . is hidden from Finder) inserted in directories whenever you view them with Finder to speed up loading the file icons and saving your preferences for thumbnail sizes and such in that folder. You can read more about the file on Wikipedia.

You can see the file if you navigate to the directory and list the files in terminal with ls -a.

In any case, you just need to not try and read that as an image file. There are a bazillion ways to avoid this, here's a few:

for imagePath in imagePaths:
    if imagePath == directory + '.DS_Store':
        continue
    # rest of your program

or

imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
if directory + '.DS_Store' in imagePaths:
    imagePaths.remove(directory + '.DS_Store')

or just use glob to grab files only with the extensions you want:

import glob
imagePaths = [f for f in glob.glob(directory+'*.jpg')]  # or .png, .tif, etc

Here the * is a wildcard meaning "any sequence of characters" so this will grab directory/1.jpg and directory/asdf.jpg and all other possibilities starting with directory/ and ending with .jpg.

Or just remove it from your directory in terminal with

rm .DS_Store

but this is only a temporary solution as macOS will insert the file again next time you view the folder in Finder.


问:
Actor accessing things out of scope
I'm using the Akka libraries.

What happens when multiple actors call a function on an object? Would this block other actors from accessing the object?

The reason I ask this is because I want to use JBCrypt with akka actors. And since we can encrypt multiple strings concurrently I have each actor calling JBcrypt.hash(...). Not sure how it works since I think, in scala, objects exist in one place, and I feel like multiple actors using the same object (library) might block the concurrency from actually happening.

答:
Multiple actors calling a function in an object that calls a library will not block unless the library being called uses concurrency control mechanisms such as sychronized, ThreadLocal or an object lock.

For example, calling print on the below Printer object will block:

```<code>class BlockingPrinter(){
  def print(s: String) = synchronized{s}
}

object Printer{
  val printer = new BlockingPrinter()

  def print(str: String) = printer.print(str)
}
</code>```

But calling it on the below Printer object will not

```<code>class NonBlockingPrinter(){
  def print(s: String) = s
}

object Printer{
  val printer = new NonBlockingPrinter()

  def print(str: String) = printer.print(str)
}
</code>```

In summary, the library that you're calling is the one that decides how concurrency is handled. Not the fact that you're calling an object.

Title: Actor accessing things out of scope

Body:
Multiple actors calling a function in an object that calls a library will not block unless the library being called uses concurrency control mechanisms such as sychronized, ThreadLocal or an object lock.

For example, calling print on the below Printer object will block:

class BlockingPrinter(){
  def print(s: String) = synchronized{s}
}

object Printer{
  val printer = new BlockingPrinter()

  def print(str: String) = printer.print(str)
}

But calling it on the below Printer object will not

class NonBlockingPrinter(){
  def print(s: String) = s
}

object Printer{
  val printer = new NonBlockingPrinter()

  def print(str: String) = printer.print(str)
}

In summary, the library that you're calling is the one that decides how concurrency is handled. Not the fact that you're calling an object.


问:
Interview javascript foreach
Q: Write a function called countLetters which accepts a string and returns the values as the number of times the letter appears in the string.
Hi, Is there a more efficient way to solve that question?

O(n) solution, howto make it O(log n)

function countLetters(str){
    var splitArr = str.toLowerCase().split("");
    var obj = {};
    var letters = "abcdefghijklmnopqrstuvwxez";

    splitArr.forEach((letter)=>{
        if(letters.includes(letter)){
            if(letter in obj){
                obj[letter]++;
            } else{
                obj[letter] = 1;

            }
        }
    });
    return obj;
}
console.log(countLetters('Ellie'))```

答:
This isn't O(log n) as that isn't achieveable given the problem at hand. I do however think this is a more succinct solution to the problem.

function countLetters(str){
  var letters = str.toLowerCase().replace(/[^a-z]/g, '').split('');

  return letters.reduce(function (counts, letter) {
    counts[letter] = (counts[letter] || 0) + 1;
    return counts;
  }, {});
}

console.log(countLetters('Hello World!'));```

Title: Interview javascript foreach


问:
Python for .NET: ImportError: No module named warnings
I am trying to embed python 2.6 in .NET 4.0.

Following the very minimal documentation in "Python for .NET", I wrote a fairly straightforward code as follows:

```<code> const string pythonModulePath = @"C:\Projects\PythonImport\PythonImport\test.py";
 Environment.SetEnvironmentVariable("PYTHONHOME", Path.GetDirectoryName(python
 ModulePath));

 PythonEngine.Initialize();

 var oldWorkingDirectory = Directory.GetCurrentDirectory();
 var currWorkingDirectory = Path.GetDirectoryName(pythonModulePath);

 Directory.SetCurrentDirectory(currWorkingDirectory);

 var pyPlugin = PythonEngine.ImportModule(Path.GetFileNameWithoutExtension(python
 ModulePath));
 if (pyPlugin == null)
 {
      throw new PythonException();
 }

 Directory.SetCurrentDirectory(oldWorkingDirectory);
</code>```

Even if test.py is empty I get an import error saying "No module named warnings".

```<code>'import site' failed; use -v for traceback

 Unhandled Exception: Python.Runtime.PythonException: ImportError : No module nam
 ed warnings
</code>```

The reason becomes apparent when you run test.py using "python -v" (verbose mode). Notice that python calls #cleanup[2] warnings.

Why is Python .NET not able to resolve warnings? The module is present in Lib directory.

Any ideas?

答:
I think by default the Python Engine does not set the paths you need automatically.

http://www.voidspace.org.uk/ironpython/custom_executable.shtml  has an example for embedding ironpython.  Looks like you are missing something like

```<code>PythonEngine engine = new PythonEngine();
engine.AddToPath(Path.GetDirectoryName(Application.ExecutablePath));
engine.AddToPath(MyPathToStdLib);
</code>```

Unless I know where and if Ironpython is installed, I prefer to find all of the standard modules I need, compile them to a IPyStdLibDLL and then do th following from my code

```<code>import clr
clr.addReference("IPyStdLib")
import site
</code>```

Body:
I am trying to embed python 2.6 in .NET 4.0.

Following the very minimal documentation in "Python for .NET", I wrote a fairly straightforward code as follows:

 const string pythonModulePath = @"C:\Projects\PythonImport\PythonImport\test.py";
 Environment.SetEnvironmentVariable("PYTHONHOME", Path.GetDirectoryName(python
 ModulePath));

 PythonEngine.Initialize();

 var oldWorkingDirectory = Directory.GetCurrentDirectory();
 var currWorkingDirectory = Path.GetDirectoryName(pythonModulePath);

 Directory.SetCurrentDirectory(currWorkingDirectory);

 var pyPlugin = PythonEngine.ImportModule(Path.GetFileNameWithoutExtension(python
 ModulePath));
 if (pyPlugin == null)
 {
      throw new PythonException();
 }

 Directory.SetCurrentDirectory(oldWorkingDirectory);

Even if test.py is empty I get an import error saying "No module named warnings".

'import site' failed; use -v for traceback

 Unhandled Exception: Python.Runtime.PythonException: ImportError : No module nam
 ed warnings

The reason becomes apparent when you run test.py using "python -v" (verbose mode). Notice that python calls #cleanup[2] warnings.

Why is Python .NET not able to resolve warnings? The module is present in Lib directory.

Any ideas?

Body:
I think by default the Python Engine does not set the paths you need automatically.

http://www.voidspace.org.uk/ironpython/custom_executable.shtml  has an example for embedding ironpython.  Looks like you are missing something like

PythonEngine engine = new PythonEngine();
engine.AddToPath(Path.GetDirectoryName(Application.ExecutablePath));
engine.AddToPath(MyPathToStdLib);

Unless I know where and if Ironpython is installed, I prefer to find all of the standard modules I need, compile them to a IPyStdLibDLL and then do th following from my code

import clr
clr.addReference("IPyStdLib")
import site


问:
Program in Java for testing internet connection
I'm trying to write a simple program which tells me in real time whether I have internet connection or not. This is what I'm doing:

```<code>import java.net.Socket;

public class InternetConnection {
    public static void main(String[] args) {
        String inetAddress = "www.google.com";
        int port = 80;

        while (true) {
            try {
                Socket socket = new Socket(inetAddress, port);
                System.out.println("Connected to the internet");
            } catch (Exception e) {
                System.out.println("Not connected to the internet");
            }
        }
    }
}
</code>```

That prints out the desired message if it reaches www.google.com. However, if I disconnect from the internet on purpose to check if it works, it does print "Not connected to the internet", then I reconnect and it shows "Connected to the internet", but when I disconnect again, it still shows the message "Connected to the internet". I don't know what I'm doing wrong...

P.S. I know this isn't the best way to check whether there's an internet connection or not.

答:
Put a delay time after you create the socket and print the connection message.

```<code>try {
    Socket socket = new Socket(inetAddress,port);
    System.out.println("Connected to the internet");
}catch(Exception e){
    System.out.println("Not connected to the internet");
}
TimeUnit.SECONDS.sleep(5);
</code>```

Your program should work as intended.

Body:
I'm trying to write a simple program which tells me in real time whether I have internet connection or not. This is what I'm doing:

import java.net.Socket;

public class InternetConnection {
    public static void main(String[] args) {
        String inetAddress = "www.google.com";
        int port = 80;

        while (true) {
            try {
                Socket socket = new Socket(inetAddress, port);
                System.out.println("Connected to the internet");
            } catch (Exception e) {
                System.out.println("Not connected to the internet");
            }
        }
    }
}

That prints out the desired message if it reaches www.google.com. However, if I disconnect from the internet on purpose to check if it works, it does print "Not connected to the internet", then I reconnect and it shows "Connected to the internet", but when I disconnect again, it still shows the message "Connected to the internet". I don't know what I'm doing wrong...

P.S. I know this isn't the best way to check whether there's an internet connection or not.

Body:
Put a delay time after you create the socket and print the connection message.

try {
    Socket socket = new Socket(inetAddress,port);
    System.out.println("Connected to the internet");
}catch(Exception e){
    System.out.println("Not connected to the internet");
}
TimeUnit.SECONDS.sleep(5);

Your program should work as intended.


问:
Persist Firebase login with Node.js backend
When I've looked up how to check if the user requesting a certain view is logged in, many people suggest using firebase.auth().currentUser, but when I read the docs, it says that firebase.auth().currentUser just shows you if any user is logged in which doesn't really help me when I'm getting a request to my Node server, and I want to see if the user is logged in.

So what is the idiomatic way to let a user login in Firebase, keep them logged in, and have a function to tell you if they're logged in?

答: Assuming that the user is authenticating to Firebase on the client side, the typical approach is for the client to pass an ID token to the server to identify the Firebase user for the session.  See this documentation for details on how to generate the ID token on the client and then verify it on the server.</p>


问:
Network connection from PC to Android Device
I used search for hours now but couldn't find an answer which fit to my question. I simply want to create a TCP network connection between a PC and an Android device. Sending data (let's say a simple String) from Android to PC actually works without any trouble with Socket and ServerSocket.
However, sending data from PC to Android doesn't work. There is nothing received. Here is the code:

Server at Android device:

```<code>    try {
        ServerSocket serverSocket = new ServerSocket( 1234 );

        //tell logcat the server is online
        Log.d("TCP", "C: Server Online...");

        while ( true ) {

            Socket client = serverSocket.accept();

            BufferedReader in = new BufferedReader( new InputStreamReader(    client.getInputStream() ) );
            String input = in.readLine();
            // Do what ever you want with input String

            client.close();
        }
    } catch ( Exception e ) {
        Log.d( "TCP", "C: " + e );
    }
</code>```

Client at PC:

```<code>    try {

        InetAddress serverAddr;

        try {
            serverAddr = InetAddress.getByName(IPAdresse);

            socket = new java.net.Socket(serverAddr,portAdresse);
            socket.setSoTimeout(1000);
        }catch (ConnectException e) { /*e.printStackTrace();*/ }

        PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
        out.println(nachricht);

        socket.close();

    }catch (SocketException e) {
</code>```

//          e.printStackTrace();
            try { socket.close(); } catch (Exception e1) { }

```<code>    }catch (IOException e) {
</code>```

//          e.printStackTrace();
}try { socket.close(); } catch (Exception e1) { }

```<code>    }catch (NullPointerException e) {
</code>```

//          e.printStackTrace();
            try { socket.close(); } catch (Exception e1) { /e1.printStackTrace();/ }

```<code>    }
</code>```

I have absolutely no idea why it doesn't work. I guess there is a problem in my Android code or some setting in the Android device. Maybe someone has already had the same trouble and a fitting soultion for me. Would help a lot.
Thanks

答:
I can think of a couple things that can be happening here:

Android is only binding the socket to 127.0.0.1

There is a missing permission on the phone

A firewall somewhere is preventing communications

You are not connecting to the correct IP address

For problems like this I put in a lot of print statements or step through the code while sniffing the data with Wireshark.

Body:
I used search for hours now but couldn't find an answer which fit to my question. I simply want to create a TCP network connection between a PC and an Android device. Sending data (let's say a simple String) from Android to PC actually works without any trouble with Socket and ServerSocket.
However, sending data from PC to Android doesn't work. There is nothing received. Here is the code:

Server at Android device:

    try {
        ServerSocket serverSocket = new ServerSocket( 1234 );

        //tell logcat the server is online
        Log.d("TCP", "C: Server Online...");

        while ( true ) {

            Socket client = serverSocket.accept();

            BufferedReader in = new BufferedReader( new InputStreamReader(    client.getInputStream() ) );
            String input = in.readLine();
            // Do what ever you want with input String

            client.close();
        }
    } catch ( Exception e ) {
        Log.d( "TCP", "C: " + e );
    }

Client at PC:

    try {

        InetAddress serverAddr;

        try {
            serverAddr = InetAddress.getByName(IPAdresse);

            socket = new java.net.Socket(serverAddr,portAdresse);
            socket.setSoTimeout(1000);
        }catch (ConnectException e) { /*e.printStackTrace();*/ }

        PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
        out.println(nachricht);

        socket.close();

    }catch (SocketException e) {

//          e.printStackTrace();
            try { socket.close(); } catch (Exception e1) { }

    }catch (IOException e) {

//          e.printStackTrace();
}try { socket.close(); } catch (Exception e1) { }

    }catch (NullPointerException e) {

//          e.printStackTrace();
            try { socket.close(); } catch (Exception e1) { /e1.printStackTrace();/ }

    }

I have absolutely no idea why it doesn't work. I guess there is a problem in my Android code or some setting in the Android device. Maybe someone has already had the same trouble and a fitting soultion for me. Would help a lot.
Thanks


问:
Smart ways to extract from a ImmutableMultiDict ( Dictionary in List )

Python3.6.1::Anaconda 4.4.0(64bit) + Flask 0.12.2

I post my data using jQuery like this

Front-end

```<code>$.ajax({
    url:'/immutableTest',
    data: {'key': kvs },
    type: 'POST'
});
</code>```

and typeof kvs is an object(array), there are many objects in it. So when console.log(kvs) gets

```<code>(3) [{…}, {…}, {…}]
  0:{"status": "good", "color": "#414141", "describe": "The machine is running"}
  1:{"status": "error", "color": "#ff0000", "describe": "Something error with it"}
  2:{"status": "powerOff", "color": "#000000", "describe": "Closing"}
</code>```

Back-end

My data looks like in back-end

```<code>@main.route('/immutableTest', methods=['POST'])
def immutableTest():
    for k, v in request.form.items():
    print(k, v)

key[0][status] powerOff
key[0][color] #414141
key[0][describe] The machine is running
key[1][status] error
key[1][color] #ffff00
key[1][describe] Something error with it
key[2][status] powerOff
key[2][color] #000000
key[2][describe] Closing
</code>```

So I write my program to extract the key-value which I need. I want to reprogram the following code.

```<code>@main.route('/immutableTest', methods=['POST'])
def immutableTest():
    kvs=[]
    kv={}
    i=0
    for kk, vv in request.form.items():
        kv[kk.split('[')[2].replace(']', '')] = vv
        if i == 2:
            kvs.append(kv)
            kv={}
            i = 0
        else:
            i = i + 1
    print(kvs)
    # Script to Database to update...
    return 'Update success.'
</code>```

This will result

```<code>[
  {"status": "good", "color": "#414141", "describe": "The machine is running"},
  {"status": "error", "color": "#ff0000", "describe": "Something error with it"},
  {"status": "powerOff", "color": "#000000", "describe": "Closing"}
]
</code>```

Is there a more manageable and standard way to get the same result?

I need the result so that I could update data in MongoDB easily.

答:
Well, you have to define what 'smart' means in your context. If you want more manageable and somewhat standard way to transfer structured data between a JS frontend and a Python backend, you can use JSON instead of packing your data as POST structure. For example, on the JS side:

```<code>$.ajax({
    url:'/immutableTest',
    data: JSON.stringify(kvs),
    contentType: "application/json",
    type: 'POST'
});
</code>```

then in your Flask app:

```<code>@main.route('/immutableTest', methods=['POST'])
def immutableTest():
    kvs = request.get_json()
    print(kvs)
</code>```

And it should automagically transport the structure.

Body:
Python3.6.1::Anaconda 4.4.0(64bit) + Flask 0.12.2

I post my data using jQuery like this

Front-end

$.ajax({
    url:'/immutableTest',
    data: {'key': kvs },
    type: 'POST'
});

and typeof kvs is an object(array), there are many objects in it. So when console.log(kvs) gets

(3) [{…}, {…}, {…}]
  0:{"status": "good", "color": "#414141", "describe": "The machine is running"}
  1:{"status": "error", "color": "#ff0000", "describe": "Something error with it"}
  2:{"status": "powerOff", "color": "#000000", "describe": "Closing"}

Back-end

My data looks like in back-end

@main.route('/immutableTest', methods=['POST'])
def immutableTest():
    for k, v in request.form.items():
    print(k, v)

key[0][status] powerOff
key[0][color] #414141
key[0][describe] The machine is running
key[1][status] error
key[1][color] #ffff00
key[1][describe] Something error with it
key[2][status] powerOff
key[2][color] #000000
key[2][describe] Closing

So I write my program to extract the key-value which I need. I want to reprogram the following code.

@main.route('/immutableTest', methods=['POST'])
def immutableTest():
    kvs=[]
    kv={}
    i=0
    for kk, vv in request.form.items():
        kv[kk.split('[')[2].replace(']', '')] = vv
        if i == 2:
            kvs.append(kv)
            kv={}
            i = 0
        else:
            i = i + 1
    print(kvs)
    # Script to Database to update...
    return 'Update success.'

This will result

[
  {"status": "good", "color": "#414141", "describe": "The machine is running"},
  {"status": "error", "color": "#ff0000", "describe": "Something error with it"},
  {"status": "powerOff", "color": "#000000", "describe": "Closing"}
]

Is there a more manageable and standard way to get the same result?

I need the result so that I could update data in MongoDB easily.

Body:
Well, you have to define what 'smart' means in your context. If you want more manageable and somewhat standard way to transfer structured data between a JS frontend and a Python backend, you can use JSON instead of packing your data as POST structure. For example, on the JS side:

$.ajax({
    url:'/immutableTest',
    data: JSON.stringify(kvs),
    contentType: "application/json",
    type: 'POST'
});

then in your Flask app:

@main.route('/immutableTest', methods=['POST'])
def immutableTest():
    kvs = request.get_json()
    print(kvs)

And it should automagically transport the structure.


问:
getting Permission denied(publickey) error upon git clone into VPS using ssh
I have copied the public key from my local machine into the authorized_keys file into my user's ssh directory on the VPS.
But when I do git clone I get and Permission denied(publickey) error

I get this log when I run

```<code>ssh -Tv git@github.com
OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to github.com [192.30.255.112] port 22.
debug1: Connection established.
debug1: identity file /home/sam/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_dsa-cert type -1

debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory

debug1: identity file /home/sam/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version libssh_0.7.0
debug1: no match: libssh_0.7.0
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ssh-rsa debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none

debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY

debug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /home/sam/.ssh/known_hosts:1 Warning: Permanently added the RSA host key for IP address '192.30.255.112' to the list of known hosts.
debug1: rekey after 134217728 blocks debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/sam/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug1: Trying private key: /home/sam/.ssh/id_dsa debug1: Trying private key: /home/sam/.ssh/id_ecdsa
debug1: Trying private key: /home/sam/.ssh/id_ed25519
debug1: No more authentication methods to try.
</code>```

I'm not sure what else I need to do. I also created authorized_keys2 with the publickey but still no luck.

答: You need to add the private key (e.g. ~/.ssh/id_rsa or id_dsa) to the VPS and then add the public key to your your Github profile settings to be able to authenticate and clone your repo via ssh.

Body:
I have copied the public key from my local machine into the authorized_keys file into my user's ssh directory on the VPS.
But when I do git clone I get and Permission denied(publickey) error

I get this log when I run

ssh -Tv git@github.com
OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to github.com [192.30.255.112] port 22.
debug1: Connection established.
debug1: identity file /home/sam/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_dsa-cert type -1

debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/sam/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory

debug1: identity file /home/sam/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version libssh_0.7.0
debug1: no match: libssh_0.7.0
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ssh-rsa debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none

debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY

debug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /home/sam/.ssh/known_hosts:1 Warning: Permanently added the RSA host key for IP address '192.30.255.112' to the list of known hosts.
debug1: rekey after 134217728 blocks debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/sam/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug1: Trying private key: /home/sam/.ssh/id_dsa debug1: Trying private key: /home/sam/.ssh/id_ecdsa
debug1: Trying private key: /home/sam/.ssh/id_ed25519
debug1: No more authentication methods to try.

I'm not sure what else I need to do. I also created authorized_keys2 with the publickey but still no luck.


问:
JavaScript temperature converter gives Invalid or unexpected token error
I was working on a JavaScript function tonight following a tutorial that would convert fahrenheit to celsius.

I tried this way:

```<code>function fahrToCels(fahrTemp) {
  return (fahrTemp − 32) * (5⁄9);
}
console.log(fahrToCels(140));
</code>```

and I got the following error:

```<code>Uncaught SyntaxError: Invalid or unexpected token
</code>```

I researched the correct way to write this online and found similar code to mine such as:

```<code>function toCelsius(f) {
           return (5/9) * (f-32);
      }
      document.getElementById("demo").innerHTML = toCelsius(77);
</code>```

I tried running this and I did not get an error. But, I couldn't figure out why my way was wrong, so when I gave up and looked up the answer they were looking for, I found this:

```<code>function fahrToCels(fahrTemp) {
  return (fahrTemp - 32) / 1.8;
}

console.log(fahrToCels(140));
</code>```

This does not give an error although it gives a different answer.
So, what gives here? I have something similar above, except without the 1.8. I am unclear on what the syntax error is telling me. Pleas help.

答:
You have invalid characters: − and 5⁄9.

Change to:

- and 5/9.

Something like this:

function fahrToCels(fahrTemp) {
  return (fahrTemp - 32) * (5/9);
}
console.log(fahrToCels(140));```

Body:
I was working on a JavaScript function tonight following a tutorial that would convert fahrenheit to celsius.

I tried this way:

function fahrToCels(fahrTemp) {
  return (fahrTemp − 32) * (5⁄9);
}
console.log(fahrToCels(140));

and I got the following error:

Uncaught SyntaxError: Invalid or unexpected token

I researched the correct way to write this online and found similar code to mine such as:

function toCelsius(f) {
           return (5/9) * (f-32);
      }
      document.getElementById("demo").innerHTML = toCelsius(77);

I tried running this and I did not get an error. But, I couldn't figure out why my way was wrong, so when I gave up and looked up the answer they were looking for, I found this:

function fahrToCels(fahrTemp) {
  return (fahrTemp - 32) / 1.8;
}

console.log(fahrToCels(140));

This does not give an error although it gives a different answer.
So, what gives here? I have something similar above, except without the 1.8. I am unclear on what the syntax error is telling me. Pleas help.


问:
Ionic 3 - how use cordova plugin Network interface with ionic?
My problem:
I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

```<code> "cordova plugin add cordova-plugin-networkinterface"
</code>```

2. Declare the variable in global scope to access the object

```<code>declare var NetworkInterface: any;
export class TestClass{}
</code>```

3. Call the object using the global variable inside a component

```<code>NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});
</code>```

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise):  ReferenceError: NetworkInterface
  is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

答:
Solved the issue by accessing the window object directly and then the networkinterface object.

Code Solution:

```<code> (<any>window).networkinterface.getWiFiIPAddress((ip) => {
     console.log("network ip address = " + ip);
 });
</code>```

This means I no longer have to use a global variable for reference. Hopefully this will help someone else.

Update thanks to Sampath for another solution; It appears I should of used:

```<code>ionic cordova plugin add cordova-plugin-networkinterface --save
</code>```

Instead of:

```<code>cordova plugin add cordova-plugin-networkinterface
</code>```

Body:
My problem:
I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

 "cordova plugin add cordova-plugin-networkinterface"

2. Declare the variable in global scope to access the object

declare var NetworkInterface: any;
export class TestClass{}

3. Call the object using the global variable inside a component

NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise):  ReferenceError: NetworkInterface
  is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

Body:
Solved the issue by accessing the window object directly and then the networkinterface object.

Code Solution:

 (<any>window).networkinterface.getWiFiIPAddress((ip) => {
     console.log("network ip address = " + ip);
 });

This means I no longer have to use a global variable for reference. Hopefully this will help someone else.

Update thanks to Sampath for another solution; It appears I should of used:

ionic cordova plugin add cordova-plugin-networkinterface --save

Instead of:

cordova plugin add cordova-plugin-networkinterface


问:
BigQuery: Cannot read field 'stamp' of type TIMESTAMP_MICROS as DATETIME
I'm playing with BigQuery's Standard SQL Wildcard Table functionality.

I have a table with the following schema:

```<code>_PARTITIONTIME  TIMESTAMP   NULLABLE
stamp           TIMESTAMP   NULLABLE
value           FLOAT       NULLABLE
source          STRING      NULLABLE
...
</code>```

Because the tables in my dataset have mixed schemas and their names are not commonly prefixed, I intend on making a wide Wildcard match - then, narrowing _TABLE_SUFFIX in the WHERE:

SELECT
*,
_TABLE_SUFFIX AS table_name
FROM `my-project.my-dataset.*`
WHERE REGEXP_CONTAINS(_TABLE_SUFFIX, r"cars")
```

<p>This is as-basic as I can make it. <code>cars</code> only matches a single table.
I intend on adding additional tables to the REGEX above. e.g: <code>cars|trucks|...</code></p>

<p>When I execute the above query, I get the following error:</p>

<p><code>Cannot read field 'stamp' of type TIMESTAMP_MICROS as DATETIME</code></p>

<p>Furthermore, when I attempt to remove the <code>stamp</code> from my <code>SELECT</code> and use the <code>source</code> column in it's place:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
source,
_TABLE_SUFFIX AS table_name
FROM `my-project.my-dataset.*`
WHERE REGEXP_CONTAINS(_TABLE_SUFFIX, r"cars")
</code>```

BigQuery now tells me: Unrecognized name: source at [2:1]

What's happening here in both cases? Why does BigQuery want to cast my stamp column, and why is it unable to find source ?

答:
What's happening here in both cases? Why does BigQuery want to cast my stamp column, and why is it unable to find source ?

In order to execute a standard SQL query that uses a wildcard table, BigQuery automatically infers the schema for that table. BigQuery uses the schema for the most recently created table that matches the wildcard as the schema for the wildcard table. If the schema is inconsistent across tables matched by the wildcard table, BigQuery returns an error.

This explains both case you see!

In first case - the most recent table has _PARTITIONTIME as DATETIME data type

In second case - same most recent table just simply does not have source field in it

Body:
I'm playing with BigQuery's Standard SQL Wildcard Table functionality.

I have a table with the following schema:

_PARTITIONTIME  TIMESTAMP   NULLABLE
stamp           TIMESTAMP   NULLABLE
value           FLOAT       NULLABLE
source          STRING      NULLABLE
...

Because the tables in my dataset have mixed schemas and their names are not commonly prefixed, I intend on making a wide Wildcard match - then, narrowing _TABLE_SUFFIX in the WHERE:

SELECT
*,
_TABLE_SUFFIX AS table_name
FROM `my-project.my-dataset.*`
WHERE REGEXP_CONTAINS(_TABLE_SUFFIX, r"cars")

This is as-basic as I can make it. cars only matches a single table.
I intend on adding additional tables to the REGEX above. e.g: cars|trucks|...

When I execute the above query, I get the following error:

Cannot read field 'stamp' of type TIMESTAMP_MICROS as DATETIME

Furthermore, when I attempt to remove the stamp from my SELECT and use the source column in it's place:

SELECT
source,
_TABLE_SUFFIX AS table_name
FROM `my-project.my-dataset.*`
WHERE REGEXP_CONTAINS(_TABLE_SUFFIX, r"cars")

BigQuery now tells me: Unrecognized name: source at [2:1]

What's happening here in both cases? Why does BigQuery want to cast my stamp column, and why is it unable to find source ?


问:
Single versus double quotes in json loads in Python
I notice that single quotes cause simplejson's loads function to fail:

```<code>>>> import simplejson as json
>>> json.loads("\"foo\"")
'foo'
>>> json.loads("\'foo\'")
Traceback (most recent call last):
...
ValueError: No JSON object could be decoded
</code>```

I'm parsing things like: foo = ["a", "b", "c"] from a textfile into lists in Python and would like to also accept foo = ['a', 'b', 'c']. simplejson is convenient for making foo automatically into a list.

How can I get loads to accept single quotes, or automatically substitute double for single quotes without wrecking the input?  thanks.

答:
I started at this StackOverflow question when looking to solve this myself.

The solution to use ast.literal_eval() did not work for all my cases, as the text also occasionally had boolean constants true/false which are not recognised as Python tokens (which are capitalised.)

To solve it for myself, I wrok a custom JSONDecoder which plugs into the standard json Python package.

pip install git+https://github.com/jpz/tolerantjsondecoder.git

Maybe this may be of use to the next person.

Also, to note, after I completed this, I later found the demjson library which appears to be a more complete solution, however I've not evaluated it.

Body:
I notice that single quotes cause simplejson's loads function to fail:

>>> import simplejson as json
>>> json.loads("\"foo\"")
'foo'
>>> json.loads("\'foo\'")
Traceback (most recent call last):
...
ValueError: No JSON object could be decoded

I'm parsing things like: foo = ["a", "b", "c"] from a textfile into lists in Python and would like to also accept foo = ['a', 'b', 'c']. simplejson is convenient for making foo automatically into a list.

How can I get loads to accept single quotes, or automatically substitute double for single quotes without wrecking the input?  thanks.


问:
How to remove the last comma in for loop
```<code>`<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>

<body>

<?php

for( $x=1 ; $x<=10 ; $x++){
echo "$x".",";
}
?>
</body>
</html>`
</code>```

1.output =1,2,3,4,5,6,7,8,9,10,

i have this output. how can i remove the last comma? your help is needed.

答:
You can remove the last comma using join.</p>

```<code>echo join(',', range(1,10));
</code>```

Body:
`<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>

<?php

for( $x=1 ; $x<=10 ; $x++){
echo "$x".",";
}
?>

`

1.output =1,2,3,4,5,6,7,8,9,10,

i have this output. how can i remove the last comma? your help is needed.

Body:
You can remove the last comma using join.

echo join(',', range(1,10));


问:
How to set input files with a Makefile? (C)
If I have source code files main.c, library.c, library.h, etc. how would I go about setting the input text files to act as console commands like main input1.txt input2.txt? Can this be done at all or must it be done post-compilation?

答:
```<code>program: main.c library.c
     gcc -o program $<

.PHONY: run
run: program input1.txt input2.txt.
     ./program input1.txt input2.txt
</code>```

Basically, you treat them like dependencies for running the program. In the above example, make run will run the program and compile it if needed.

Body:
program: main.c library.c
     gcc -o program $<

.PHONY: run
run: program input1.txt input2.txt.
     ./program input1.txt input2.txt

Basically, you treat them like dependencies for running the program. In the above example, make run will run the program and compile it if needed.


问:
Excel Parameter from Drop down
I have a datasource that poplulates my sheet from sql server.  There is a parameter to refresh the data.  Can I have the choices come from a drop down menu on another sheet?  I know no VBA BTW.</p>

答:
I know this is a old but the answer is No.

To add dynmic parameters, you need to use VBA.

Its not hard. Since this queistion is 4 months old you have probably already figured that out.

Title: Excel Parameter from Drop down


问:
Can't set cookies in Plug in test
I have a plug who's responsibility is to fetch a cookie from the request which is a token and verify it.

I am currently having issue setting up my tests to pass a cookie inside the conn.

```<code>  setup do
    token = "some string"
    conn =
      conn(:get, "/")
      |> put_req_cookie("session_token", token)

    %{conn: MyPlug.call(conn, [])}
  end

  test "user passes through when token is valid", %{conn: conn} do
    require IEx; IEx.pry

    assert conn.status == 200
  end
</code>```

In my debugger if I check conn.cookies
I get %Plug.Conn.Unfetched{aspect: :cookies}.

Is there something I am missing?

答:
put_req_cookie only adds a cookie header to the conn struct. You need to call Plug.Conn.fetch_cookies after that to parse the cookie headers and load them into the cookies map. The following code should work:

```<code>conn =
  conn(:get, "/")
  |> put_req_cookie("session_token", token)
  |> fetch_cookies()
</code>```

Title: Can't set cookies in Plug in test

Body:
I have a plug who's responsibility is to fetch a cookie from the request which is a token and verify it.

I am currently having issue setting up my tests to pass a cookie inside the conn.

  setup do
    token = "some string"
    conn =
      conn(:get, "/")
      |> put_req_cookie("session_token", token)

    %{conn: MyPlug.call(conn, [])}
  end

  test "user passes through when token is valid", %{conn: conn} do
    require IEx; IEx.pry

    assert conn.status == 200
  end

In my debugger if I check conn.cookies
I get %Plug.Conn.Unfetched{aspect: :cookies}.

Is there something I am missing?

Body:
put_req_cookie only adds a cookie header to the conn struct. You need to call Plug.Conn.fetch_cookies after that to parse the cookie headers and load them into the cookies map. The following code should work:

conn =
  conn(:get, "/")
  |> put_req_cookie("session_token", token)
  |> fetch_cookies()


问:
composer dump-autoload not recognized command

whenever I use composer dump-autoload  with laravel   I get this error

Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
    @php artisan package:discover 'C:\Program' is not recognized as an internal or external command, operable program or batch file. Script
    @php artisan package:discover handling the post-autoload-dump event
    returned with error code 1

I think it has something to do with "environment variables"

so my paths

```<code>C:\ProgramData\Oracle\Java\javapath;
C:\Program Files\iis express\PHP\v7.0;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\Program Files (x86)\QuickTime\QTSystem\;
C:\xampp\php;
C:\ProgramData\ComposerSetup\bin;
C:\Android;C:\Windows\System32;
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;
C:\ProgramFiles\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\Program Files\Git\cmd;
C:\Program Files (x86)\Skype\Phone\;
C:\Program Files (x86)\Brackets\command;
C:\Program Files\nodejs\;
C:\ProgramFiles\Microsoft SQL Server\130\Tools\Binn\;
C:\Program Files\dotnet\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\xampp\php;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\phpspec run;
C:\Users\ahmadz\AppData\Roaming\npm;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\kahlan
</code>```

答:
You're composer might be outdated. Try running this script in your terminal

```<code>composer global update
</code>```

Then run composer update in your project folder.

Body:
whenever I use composer dump-autoload  with laravel   I get this error

Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
    @php artisan package:discover 'C:\Program' is not recognized as an internal or external command, operable program or batch file. Script
    @php artisan package:discover handling the post-autoload-dump event
    returned with error code 1

I think it has something to do with "environment variables"

so my paths

C:\ProgramData\Oracle\Java\javapath;
C:\Program Files\iis express\PHP\v7.0;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\Program Files (x86)\QuickTime\QTSystem\;
C:\xampp\php;
C:\ProgramData\ComposerSetup\bin;
C:\Android;C:\Windows\System32;
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;
C:\ProgramFiles\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;
C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;
C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;
C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\Program Files\Git\cmd;
C:\Program Files (x86)\Skype\Phone\;
C:\Program Files (x86)\Brackets\command;
C:\Program Files\nodejs\;
C:\ProgramFiles\Microsoft SQL Server\130\Tools\Binn\;
C:\Program Files\dotnet\;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin;
C:\Users\ahmadz\AppData\Local\Microsoft\WindowsApps;
C:\xampp\php;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\phpspec run;
C:\Users\ahmadz\AppData\Roaming\npm;
C:\Users\ahmadz\AppData\Roaming\Composer\vendor\bin\kahlan

Body:
You're composer might be outdated. Try running this script in your terminal

composer global update

Then run composer update in your project folder.


问:
Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

```<code>find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323
</code>```

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

答:
I found a workaround it:
Download Xocde 9.1 from https://developer.apple.com/download/more/

Make a fresh archive then upload it. It worked for me.

P.S. I did not send for review but I sent it to internal testers including myself.

Body:
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."


问:
Using withStyles of material-ui v1 in a nested manner
So I have this component that I am trying to write in react manner. Where each of the major containers are separated as React class component.
Now I know how to use withStyles with one component :
export default withStyles(styles)(MyComponent);

But when you have more than two components, how do you use withStyles.
Here's the code :

```<code>    class AtmanPage extends Component {
  render() {
    return (
      <AtmanAppBar />
    );
  }
}

class AtmanAppBar extends Component {
  render() {
    return (
      <div className= {this.props.classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton className= {this.props.classes.menubutton} color="contrast" aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <Typography type="title" color="inherit" className={this.props.classes.flex}>
            Title
          </Typography>
          <Button color="contrast">Login</Button>
        </Toolbar>
      </AppBar>
          </div>
    );
  }
}

const styles = theme => ({
  root: {
    marginTop: theme.spacing.unit * 3,
    width: '100%',
  },
  flex: {
    flex: 1,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
});

export default withStyles(styles) AtmanPage ?;
</code>```

Now the question mark is about what else should be done to pass the styles as a prop to AtmanAppBar through AtmanPage.

答:
Your issue is not related to withStyles but in the way you organize your components and exports.

Solution 1:

You can put each component in a separate file and use

```<code>export default withStyles(styles)(MyComponent);
</code>```

in each file as you have mentioned in your post.

Solution 2:

You can do a simple export for both of your classes if you wish to keep them in the same file:

```<code>export const StyledAtmanAppBar = withStyles(styles)(AtmanAppBar);
export const StylesAtmanPage = withStyles(styles)(AtmanPage);
</code>```

Then you need to import them like so in another file:

```<code>import {StyledAtmanAppBar, StylesAtmanPage} from './path/to/your/file';
</code>```

Body:
So I have this component that I am trying to write in react manner. Where each of the major containers are separated as React class component.
Now I know how to use withStyles with one component :
export default withStyles(styles)(MyComponent);

But when you have more than two components, how do you use withStyles.
Here's the code :

    class AtmanPage extends Component {
  render() {
    return (
      <AtmanAppBar />
    );
  }
}

class AtmanAppBar extends Component {
  render() {
    return (

      <AppBar position="static">
        <Toolbar>
          <IconButton className= {this.props.classes.menubutton} color="contrast" aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <Typography type="title" color="inherit" className={this.props.classes.flex}>
            Title
          </Typography>
          <Button color="contrast">Login</Button>
        </Toolbar>
      </AppBar>

    );
  }
}

const styles = theme => ({
  root: {
    marginTop: theme.spacing.unit * 3,
    width: '100%',
  },
  flex: {
    flex: 1,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
});

export default withStyles(styles) AtmanPage ?;

Now the question mark is about what else should be done to pass the styles as a prop to AtmanAppBar through AtmanPage.

Body:
Your issue is not related to withStyles but in the way you organize your components and exports.

Solution 1:

You can put each component in a separate file and use

export default withStyles(styles)(MyComponent);

in each file as you have mentioned in your post.

Solution 2:

You can do a simple export for both of your classes if you wish to keep them in the same file:

export const StyledAtmanAppBar = withStyles(styles)(AtmanAppBar);
export const StylesAtmanPage = withStyles(styles)(AtmanPage);

Then you need to import them like so in another file:

import {StyledAtmanAppBar, StylesAtmanPage} from './path/to/your/file';