问:
Spock test showing groovy.lang.MissingPropertyException
I have the following spock test. I am first going to the login page, and then I am clicking the login button without entering an email and password to verify the error message. I will add other steps later such as email but no password and email with incorrect password, but I first need to get this test to work.

```<code>package loginPageTests

import Pages.loginPage
import geb.Page
import geb.spock.GebReportingSpec

class invalidLoginSpec extends GebReportingSpec {

    def "Go to login page"() {
        when:
        Page loginPage = to loginPage
        waitFor { loginPage.loginButton.isDisplayed() }

        then:
        at loginPage
    }

    def "Try to log in without email or password"() {
        when:
        loginPage.loginButton.click()

        then:
        at loginPage
        assert loginPage.loginError.text() == "Please enter your email and password."
    }
}
</code>```

And the following page object

```<code>package Pages

import geb.Page

class loginPage extends Page {
    static url = 'login/'
    static at = { title == "Login to TB"}
    static content = {
        loginButton {$("#loginButton")}
        loginError(wait:true) {$("#loginError")}
    }
}
</code>```

The first method runs successfully, but I get this error when the second method tries to run

groovy.lang.MissingPropertyException: No such property: loginButton
  for class: Pages.loginPage

the property loginButton is in the loginPage page object, so I'm not sure why this error is occurring.

答:
The way you are interacting with the page is non-idiomatic but to answer the question asked...

You have defined loginPage as a local variable inside of the first test method and then tried to reference it inside of the second test method where it is out of scope.

Body:
I have the following spock test. I am first going to the login page, and then I am clicking the login button without entering an email and password to verify the error message. I will add other steps later such as email but no password and email with incorrect password, but I first need to get this test to work.

package loginPageTests

import Pages.loginPage
import geb.Page
import geb.spock.GebReportingSpec

class invalidLoginSpec extends GebReportingSpec {

    def "Go to login page"() {
        when:
        Page loginPage = to loginPage
        waitFor { loginPage.loginButton.isDisplayed() }

        then:
        at loginPage
    }

    def "Try to log in without email or password"() {
        when:
        loginPage.loginButton.click()

        then:
        at loginPage
        assert loginPage.loginError.text() == "Please enter your email and password."
    }
}

And the following page object

package Pages

import geb.Page

class loginPage extends Page {
    static url = 'login/'
    static at = { title == "Login to TB"}
    static content = {
        loginButton {$("#loginButton")}
        loginError(wait:true) {$("#loginError")}
    }
}

The first method runs successfully, but I get this error when the second method tries to run

groovy.lang.MissingPropertyException: No such property: loginButton
  for class: Pages.loginPage

the property loginButton is in the loginPage page object, so I'm not sure why this error is occurring.


来源: stackexchange

问:
PHP fopen does not working with directory variable
I have a php code that it creates a random name, then creates the directory, and then I need to create and write a text file inside the directory.
It creates the directory, but nothing when it need to create the text file.
This is what I have:

This create the random name

```<code>$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));
</code>```

This join all the characters:

```<code>$letras = $letra1 . $letra2 . $letra3 . $letra4;
</code>```

This creates de directory:

```<code>mkdir("a/$letras", 777);
</code>```

And here, where i think I have the problem, the fopen:

```<code>$archt = fopen("a/$letras/text.txt", "w") or die("");
$txt = "";
fclose($archt);
</code>```

I think it isn't a perms problem, I have given 777 to all directories...

I have tried a lot of stuf that I have been searched from stackoverflow but nothing is working for me and don't know what it will be?

答:
You need to give permissions to the sub-directories too.</p>

```<code><?php
    $letra1 = chr(rand(65,90));
    $letra2 = chr(rand(97,122));
    $letra3 = chr(rand(65,90));
    $letra4 = chr(rand(97,122));
    $letras = $letra1 . $letra2 . $letra3 . $letra4;

    mkdir("a/$letras", 0777, true); //third parameter is important if you want to add perms recursively

    $archt = fopen("a/".$letras."/text.txt", "w")or die(print_r(error_get_last(),true));

    $txt = "";

    fclose($archt);

    ?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a php code that it creates a random name, then creates the directory, and then I need to create and write a text file inside the directory.
It creates the directory, but nothing when it need to create the text file.
This is what I have:

This create the random name

$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));

This join all the characters:

$letras = $letra1 . $letra2 . $letra3 . $letra4;

This creates de directory:

mkdir("a/$letras", 777);

And here, where i think I have the problem, the fopen:

$archt = fopen("a/$letras/text.txt", "w") or die("");
$txt = "";
fclose($archt);

I think it isn't a perms problem, I have given 777 to all directories...

I have tried a lot of stuf that I have been searched from stackoverflow but nothing is working for me and don't know what it will be?

Body:
You need to give permissions to the sub-directories too.

<?php
    $letra1 = chr(rand(65,90));
    $letra2 = chr(rand(97,122));
    $letra3 = chr(rand(65,90));
    $letra4 = chr(rand(97,122));
    $letras = $letra1 . $letra2 . $letra3 . $letra4;

    mkdir("a/$letras", 0777, true); //third parameter is important if you want to add perms recursively

    $archt = fopen("a/".$letras."/text.txt", "w")or die(print_r(error_get_last(),true));

    $txt = "";

    fclose($archt);

    ?>


问:
What does the backslash operator do inside RSH conditionals?
I'm interested to know what this snippet of RSH code does, and whether Bash has something similar:</p>

```<code>if [ -z $ALPHA \
     -z $BRAVO \
     -z $CHARLIE \
     -z $DELTA ]; then

   var=$ZULU
fi
</code>```

答:
The \ is escaping the end of line.

It is a way to tell that the line is not yet complete and is being continued in the next line.

It just makes your code easier to read.

It is available in bash as well:

```<code>$ echo foo
foo
$ echo foo \
> bar
foo bar
$
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm interested to know what this snippet of RSH code does, and whether Bash has something similar:

if [ -z $ALPHA \
     -z $BRAVO \
     -z $CHARLIE \
     -z $DELTA ]; then

   var=$ZULU
fi

Body:
The \ is escaping the end of line.

It is a way to tell that the line is not yet complete and is being continued in the next line.

It just makes your code easier to read.

It is available in bash as well:

$ echo foo
foo
$ echo foo \
> bar
foo bar
$


问:
Rails ActiveRecord Callbacks: Update if Exists, Create if Doesn't Exist
After combing through the documentation I am having a difficult time understand what callback I should be using.

pseudo code:

if child_id and outage_id don't exist

create a relationship (INSERT statement)

if outage_id is changed

modify relationship (UPDATE statement)

These inserts and updates are handled via collection_check_boxes

There are 3 models. Relationship, Outage, and Child.

```<code>class Outage < ApplicationRecord
  has_many :relationships
  has_many :children, through: :relationships
end

class Child < ApplicationRecord
end

class Relationship < ApplicationRecord
  belongs_to :outage
  belongs_to :child

  validate :check_if_exists, if: :outage_id_changed?

  private

  def check_if_exists
    Relationship.where(child_id: self.child_id).update_all(outage_id: self.outage_id)
  end
end
</code>```

The issue I'm facing now is that an UPDATE always occurs right before the INSERT, no matter what. An UPDATE should only occur if the record exists and the outage_id is changed.

Any insight as to what I'm doing wrong here would be appreciated.

答:
You can try this,

```<code>class Relationship < ApplicationRecord
    before_update :check_if_exists, if: :outage_id_changed?

    private
    def check_if_exists
       # Your logic
    end
end
</code>```

Note: In your code check_if_exists will run on create also, since outage_id is changing from nil to <some_id> during create

However using before_update will make sure that its run only on update

Also note that you're using update_all which results in a direct db query and is not wrapped in transaction. Meaning, if at all update fails, changes made via update_all will not be rolled back

Body:
After combing through the documentation I am having a difficult time understand what callback I should be using.

pseudo code:

if child_id and outage_id don't exist

create a relationship (INSERT statement)

if outage_id is changed

modify relationship (UPDATE statement)

These inserts and updates are handled via collection_check_boxes

There are 3 models. Relationship, Outage, and Child.

class Outage < ApplicationRecord
  has_many :relationships
  has_many :children, through: :relationships
end

class Child < ApplicationRecord
end

class Relationship < ApplicationRecord
  belongs_to :outage
  belongs_to :child

  validate :check_if_exists, if: :outage_id_changed?

  private

  def check_if_exists
    Relationship.where(child_id: self.child_id).update_all(outage_id: self.outage_id)
  end
end

The issue I'm facing now is that an UPDATE always occurs right before the INSERT, no matter what. An UPDATE should only occur if the record exists and the outage_id is changed.

Any insight as to what I'm doing wrong here would be appreciated.

Body:
You can try this,

class Relationship < ApplicationRecord
    before_update :check_if_exists, if: :outage_id_changed?

    private
    def check_if_exists
       # Your logic
    end
end

Note: In your code check_if_exists will run on create also, since outage_id is changing from nil to <some_id> during create

However using before_update will make sure that its run only on update

Also note that you're using update_all which results in a direct db query and is not wrapped in transaction. Meaning, if at all update fails, changes made via update_all will not be rolled back


问:
Getting result as Array
We are learning how to use Stream Reader, and i got some problems with methods, actually when im trying to get return value it doesn't work.

```<code>static void FindeMinMaxVerkauf(Verkauf[] arr, out Verkauf min, out Verkauf max)
{

    double min2 = 10000;
    double max2 = 0;
    int min3 = 0;
    int max3 = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        if((arr[i].StückPreis * arr[i].Stückzahl) < min2)
        {
            min2 = arr[i].StückPreis * arr[i].Stückzahl;
            min3 = i;
        }
        if ((arr[i].StückPreis * arr[i].Stückzahl) > max2)
        {
            max2 = arr[i].StückPreis * arr[i].Stückzahl;
            max3 = i;
        }
    }
    min = arr[min3];
    max = arr[max3];
}
</code>```

This is how im trying to get return value

```<code>double min,max;
FindeMinMaxVerkauf(alle, out min, out max);
Console.WriteLine("Verkäufe mit kleinsten Preis " + min + "Verkäufe mit größten Preis" + max );
</code>```

But it says

CS1503    Argument "3": Konvertierung von "out double" in "out
  _61_T_Shirts.Verkauf" nicht möglich.

It means converting from double in Tshirts... not possible. I dont know how to fix it really.

This is my second methode:

```<code>static Verkauf FindeHöchsteStückzahl(Verkauf[] arr)
{
    int anz = 0;
    int pos = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Stückzahl > anz)
        {
            anz = arr[i].Stückzahl;
            pos = i;
        }
    }
    return arr[pos];
}
</code>```

And this is how I'm trying to get return value:

```<code>FindeHöchsteStückzahl(alle);
Console.WriteLine("Höchste Stückzahl: " + alle );
</code>```

But I'm getting Array as result:

```<code>Höchste Stückzahl: _61_T_Shirts.Verkauf[]
</code>```

I mean this:

```<code>static Verkauf[] FindeVerkäufe(Verkauf[] arr, string farbe)
{
    int j = 0;
    Verkauf[] finderverk = new Verkauf[10000];
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Farbe == farbe)
        {
            finderverk[j] = arr[i];
            j++;
        }
    }
    Array.Resize(ref finderverk, j);
    return finderverk;
}
</code>```

}
}

I need help ;D

答:
Try using Linq.

It's build in, and does make the code much more readable:

```<code>using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var ar = new Buy[]{
            new Buy(){Price = 1, Name = "shirt"},
            new Buy(){Price = 2, Name = "hat"},
            new Buy(){Price = 3, Name = "dog"}
        };

        Console.WriteLine(ar.OrderByDescending(b => b.Price).First().Name);
        Console.WriteLine(ar.OrderBy(b => b.Price).First().Name);
    }

    internal class Buy{
        public int Price;
        public string Name;
    }
}
</code>```

Prints:

```<code>dog
shirt
</code>```

This should lead you in the right direction.

Title: Getting result as Array

Body:
We are learning how to use Stream Reader, and i got some problems with methods, actually when im trying to get return value it doesn't work.

static void FindeMinMaxVerkauf(Verkauf[] arr, out Verkauf min, out Verkauf max)
{

    double min2 = 10000;
    double max2 = 0;
    int min3 = 0;
    int max3 = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        if((arr[i].StückPreis * arr[i].Stückzahl) < min2)
        {
            min2 = arr[i].StückPreis * arr[i].Stückzahl;
            min3 = i;
        }
        if ((arr[i].StückPreis * arr[i].Stückzahl) > max2)
        {
            max2 = arr[i].StückPreis * arr[i].Stückzahl;
            max3 = i;
        }
    }
    min = arr[min3];
    max = arr[max3];
}

This is how im trying to get return value

double min,max;
FindeMinMaxVerkauf(alle, out min, out max);
Console.WriteLine("Verkäufe mit kleinsten Preis " + min + "Verkäufe mit größten Preis" + max );

But it says

CS1503    Argument "3": Konvertierung von "out double" in "out
  _61_T_Shirts.Verkauf" nicht möglich.

It means converting from double in Tshirts... not possible. I dont know how to fix it really.

This is my second methode:

static Verkauf FindeHöchsteStückzahl(Verkauf[] arr)
{
    int anz = 0;
    int pos = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Stückzahl > anz)
        {
            anz = arr[i].Stückzahl;
            pos = i;
        }
    }
    return arr[pos];
}

And this is how I'm trying to get return value:

FindeHöchsteStückzahl(alle);
Console.WriteLine("Höchste Stückzahl: " + alle );

But I'm getting Array as result:

Höchste Stückzahl: _61_T_Shirts.Verkauf[]

I mean this:

static Verkauf[] FindeVerkäufe(Verkauf[] arr, string farbe)
{
    int j = 0;
    Verkauf[] finderverk = new Verkauf[10000];
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Farbe == farbe)
        {
            finderverk[j] = arr[i];
            j++;
        }
    }
    Array.Resize(ref finderverk, j);
    return finderverk;
}

}
}

I need help ;D

Body:
Try using Linq.

It's build in, and does make the code much more readable:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var ar = new Buy[]{
            new Buy(){Price = 1, Name = "shirt"},
            new Buy(){Price = 2, Name = "hat"},
            new Buy(){Price = 3, Name = "dog"}
        };

        Console.WriteLine(ar.OrderByDescending(b => b.Price).First().Name);
        Console.WriteLine(ar.OrderBy(b => b.Price).First().Name);
    }

    internal class Buy{
        public int Price;
        public string Name;
    }
}

Prints:

dog
shirt

This should lead you in the right direction.


问:
" Nothing more expected -> " when running "do it" in Squeak

I'm trying to run some command split on several lines from the Workspace in Squeak 5.1

When it's on one line, like below, it works fine:

```<code>Perroquet new nom: 'Polly' ; vocabulaire: 'Screatch! Go away'; vocabulaire: 'give me food'; parle.
</code>```

However, if I try to split it on several lines, with or without tabs, it doesn't run and adds "Nothing more expected ->" in the workspace

```<code>Perroquet new nom: 'Polly' ;
    vocabulaire: 'Screatch! Go away';
    vocabulaire: 'give me food'; parle.
</code>```

after "do it":

```<code>Perroquet new nom: 'Polly' ;
    vocabulaire: 'Screatch! Go away';
     Nothing more expected ->vocabulaire: 'give me food'; parle.
</code>```

In the doc that I'm using, the examples given seem to be able to split it without any trouble. Is that because of different version of Squeak? Am I missing something somewhere?

答: You have to select the whole expression so it is highlighted and then invoke the do-it command. Otherwise, only the text on the current line is attempted to be evaluated, which fails because there is no receiver before #vocabulaire:</p>

Body:
I'm trying to run some command split on several lines from the Workspace in Squeak 5.1

When it's on one line, like below, it works fine:

Perroquet new nom: 'Polly' ; vocabulaire: 'Screatch! Go away'; vocabulaire: 'give me food'; parle.

However, if I try to split it on several lines, with or without tabs, it doesn't run and adds "Nothing more expected ->" in the workspace

Perroquet new nom: 'Polly' ;
    vocabulaire: 'Screatch! Go away';
    vocabulaire: 'give me food'; parle.

after "do it":

Perroquet new nom: 'Polly' ;
    vocabulaire: 'Screatch! Go away';
     Nothing more expected ->vocabulaire: 'give me food'; parle.

In the doc that I'm using, the examples given seem to be able to split it without any trouble. Is that because of different version of Squeak? Am I missing something somewhere?


问:
401 (Unauthorized) ReactJS
I'm facing a problem here, I'm developing a Rest API and a Web App using ReactJS. I'm trying to make a fetch request to the Rest API, but always receive back a 401 code meaning Unauthorized access. I'm sending the fetch request in the following code:

```<code>  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      }).then(this.props.history.push('/get'));  //change page layout and URL
    }
  }
</code>```

As you can see, I'm inserting the Authorization header in the request following this structure: ('Authorization' : 'Basic ' + encoding). I got the encoding value in my request from Postman software.

Here is the code for my Rest API, where I configure the user and passwords allowed:

```<code>const express =     require('express');
const bodyParser =  require('body-parser');
const mongoose =    require('mongoose');
var basicAuth =     require('express-basic-auth')

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(basicAuth({
    users: {
        'admin': 'supersecret',
        'adam': 'password1234',
        'eve': 'asdfghjkl'
    }
}))

app.use(bodyParser.json());

app.use(function(err, req, res, next){
    console.log(err);
    //res.status(450).send({err: err.message})
});

app.use(require('./routes/api'));

app.listen(4000, function(){
    console.log('Now listening for request at port 4000');
});
</code>```

Using Google Chrome Developer Tools, I can see the request headers in this operation, as you can see here

If I remove the part of the code which I configure the Users and Passwords (in the Rest API), and the part that which configures the Authorization header (Web App), the code works properly. I can't make it work with the Authorization header.

What am I supposed to do with Authorization header in the fetch request, so I can have access to the Rest API?

答:
Looks like the problem has to do with the express-basic-auth module that you are using. See this part of the documentation:

The middleware will now check incoming requests to match the credentials admin:supersecret.

The middleware will check incoming requests for a basic auth (Authorization) header, parse it and check if the credentials are legit. If there are any credentials, an auth property will be added to the request, containing an object with user and password properties, filled with the credentials, no matter if they are legit or not.

The document doesn't mention anything about Basic + encoding for the Authorization header. You should try using admin:supersecret as the value of the Authorization header.

Update:

I think you are misusing the module. The express-basic-auth seems to be used just to make sure you are authenticated and allows you through to obtain information to the API. It has hardcoded user/password credentials in the server, which does not seem to allow for registration the way you are using. The package description says,

Simple plug & play HTTP basic auth middleware for Express.

So it is just HTTP basic authentication. For a registration/login system, I would recommend using passport.

Title: 401 (Unauthorized) ReactJS

Body:
I'm facing a problem here, I'm developing a Rest API and a Web App using ReactJS. I'm trying to make a fetch request to the Rest API, but always receive back a 401 code meaning Unauthorized access. I'm sending the fetch request in the following code:

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      }).then(this.props.history.push('/get'));  //change page layout and URL
    }
  }

As you can see, I'm inserting the Authorization header in the request following this structure: ('Authorization' : 'Basic ' + encoding). I got the encoding value in my request from Postman software.

Here is the code for my Rest API, where I configure the user and passwords allowed:

const express =     require('express');
const bodyParser =  require('body-parser');
const mongoose =    require('mongoose');
var basicAuth =     require('express-basic-auth')

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(basicAuth({
    users: {
        'admin': 'supersecret',
        'adam': 'password1234',
        'eve': 'asdfghjkl'
    }
}))

app.use(bodyParser.json());

app.use(function(err, req, res, next){
    console.log(err);
    //res.status(450).send({err: err.message})
});

app.use(require('./routes/api'));

app.listen(4000, function(){
    console.log('Now listening for request at port 4000');
});

Using Google Chrome Developer Tools, I can see the request headers in this operation, as you can see here

If I remove the part of the code which I configure the Users and Passwords (in the Rest API), and the part that which configures the Authorization header (Web App), the code works properly. I can't make it work with the Authorization header.

What am I supposed to do with Authorization header in the fetch request, so I can have access to the Rest API?


问:
Several loops in the same sub
I am trying to figure out how could I, within the same sub, run several loops:
I have a set of excel file each of these files have to undergo some changes in their column A and O, every cell with the value "136" have to be replaced by a "174" under certain condition:

For  now what I've done this:

```<code>Sub REPLACE1()
Dim y As Integer
Dim wB As Workbook
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

Set FolderObj = FileSystemObj.GetFolder("\")

For Each fileobj In FolderObj.Files
Set wB = Workbooks.Open(fileobj.Path)

With wB.Sheets("Schedule Daily Bank Structure R")
For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row
If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
.Cells(y, "A") = 174

End If
Next y
End With

wB.Save
wB.Close

Next fileobj

End Sub
</code>```

My problem is that when I try to do:

```<code>Sub REPLACE1()
Dim y As Integer
Dim wB As Workbook
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

Set FolderObj = FileSystemObj.GetFolder("\")

For Each fileobj In FolderObj.Files
Set wB = Workbooks.Open(fileobj.Path)

With wB.Sheets("Schedule Daily Bank Structure R")
For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row

If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
.Cells(y, "A") = 174

End If

If .Cells(y, "O") = 136 And .Cells(y, "N") = "320" Then
.Cells(y, "O") = 174

End If
Next y
End With

wB.Save
wB.Close

Next fileobj

End Sub
</code>```

Which means, include another "if" condition in the loop. None error message appears but no changes occured in my sheets.

I must miss something but I can figure out exactly what.

答:
You code is not formatted and you will miss a lot of simple problems. I had to format it and see if there is anything missing or not. Run this code and let me know if there is any error:</p>

```<code>Sub REPLACE1()
    Dim y As Integer
    Dim wB As Workbook
    Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

    Set FolderObj = FileSystemObj.GetFolder("\")

    For Each fileobj In FolderObj.Files
        Set wB = Workbooks.Open(fileobj.Path)

        With wB.Sheets("Schedule Daily Bank Structure R")
            For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row

                If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
                    .Cells(y, "A") = 174
                End If

                If .Cells(y, "O") = 136 And .Cells(y, "N") = "320" Then
                    .Cells(y, "O") = 174
                End If
            Next y
        End With

        wB.Save
        wB.Close

    Next fileobj
End Sub
</code>```

Title: Several loops in the same sub

Body:
I am trying to figure out how could I, within the same sub, run several loops:
I have a set of excel file each of these files have to undergo some changes in their column A and O, every cell with the value "136" have to be replaced by a "174" under certain condition:

For  now what I've done this:

Sub REPLACE1()
Dim y As Integer
Dim wB As Workbook
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

Set FolderObj = FileSystemObj.GetFolder("\")

For Each fileobj In FolderObj.Files
Set wB = Workbooks.Open(fileobj.Path)

With wB.Sheets("Schedule Daily Bank Structure R")
For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row
If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
.Cells(y, "A") = 174

End If
Next y
End With

wB.Save
wB.Close

Next fileobj

End Sub

My problem is that when I try to do:

Sub REPLACE1()
Dim y As Integer
Dim wB As Workbook
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

Set FolderObj = FileSystemObj.GetFolder("\")

For Each fileobj In FolderObj.Files
Set wB = Workbooks.Open(fileobj.Path)

With wB.Sheets("Schedule Daily Bank Structure R")
For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row

If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
.Cells(y, "A") = 174

End If

If .Cells(y, "O") = 136 And .Cells(y, "N") = "320" Then
.Cells(y, "O") = 174

End If
Next y
End With

wB.Save
wB.Close

Next fileobj

End Sub

Which means, include another "if" condition in the loop. None error message appears but no changes occured in my sheets.

I must miss something but I can figure out exactly what.

Body:
You code is not formatted and you will miss a lot of simple problems. I had to format it and see if there is anything missing or not. Run this code and let me know if there is any error:

Sub REPLACE1()
    Dim y As Integer
    Dim wB As Workbook
    Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

    Set FolderObj = FileSystemObj.GetFolder("\")

    For Each fileobj In FolderObj.Files
        Set wB = Workbooks.Open(fileobj.Path)

        With wB.Sheets("Schedule Daily Bank Structure R")
            For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row

                If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
                    .Cells(y, "A") = 174
                End If

                If .Cells(y, "O") = 136 And .Cells(y, "N") = "320" Then
                    .Cells(y, "O") = 174
                End If
            Next y
        End With

        wB.Save
        wB.Close

    Next fileobj
End Sub


问:
how to suppress info messages for hadoop fs command
When we run hadoop fs -get command we see all the info messages. How can I suppress these messages.</p>

```<code>17/12/05 17:59:02 INFO s3n.S3NativeFileSystem: Opening 's3://testbucketzs/Manish/test1/data/csv-serde-1.1.2-0.11.0-all - Copy (796) -
</code>```

答:
If you don't want to globally change the log4j.properties for all the Hadoop processes, you can do a one-off command for

```<code>export HADOOP_ROOT_LOGGER="WARN,DFRA"
</code>```

Then, following hdfs commands in that session will not output INFO messages.

Body:
When we run hadoop fs -get command we see all the info messages. How can I suppress these messages.

17/12/05 17:59:02 INFO s3n.S3NativeFileSystem: Opening 's3://testbucketzs/Manish/test1/data/csv-serde-1.1.2-0.11.0-all - Copy (796) -

Body:
If you don't want to globally change the log4j.properties for all the Hadoop processes, you can do a one-off command for

export HADOOP_ROOT_LOGGER="WARN,DFRA"

Then, following hdfs commands in that session will not output INFO messages.


问:
Join tables in Grails
I got two classes

```<code>class A {
    String name
    static hasMany[b:B]
    static mapping={
        b joinTable:[name:'A_B', column: 'b_id', key: 'a_id']
    }
}

class B {
    String name
}
</code>```

Now I should join the table class B and A_B table where A_B store both
the table id's. I wrote the query

```<code>select b.name from B b,A_B ab where b.id=ab.b_id
</code>```

but it throws an error that A_B is not mapped

答:
Looks like you are trying to create a many to many relationship</p>

```<code>class A {
    String name

    static hasMany = [b:B]

    static mapping={
        b joinTable:[name:'A_B']
    }
}

class B {
    String name

    static belongsTo = A
    static hasMany = [b:B]

    static mapping={
        b joinTable:[name:'A_B']
    }
}
</code>```

Title: Join tables in Grails

Body:
I got two classes

class A {
    String name
    static hasMany[b:B]
    static mapping={
        b joinTable:[name:'A_B', column: 'b_id', key: 'a_id']
    }
}

class B {
    String name
}

Now I should join the table class B and A_B table where A_B store both
the table id's. I wrote the query

select b.name from B b,A_B ab where b.id=ab.b_id

but it throws an error that A_B is not mapped

Body:
Looks like you are trying to create a many to many relationship

class A {
    String name

    static hasMany = [b:B]

    static mapping={
        b joinTable:[name:'A_B']
    }
}

class B {
    String name

    static belongsTo = A
    static hasMany = [b:B]

    static mapping={
        b joinTable:[name:'A_B']
    }
}


问:
machine.config and processmodel with IIS express
I'm wondering if modifying processModel in machine.config will have any effect on an IIS express integrated mode application?

I'm trying to modify the maxWorkerThreads to at least 100 because I was comparing normal IIS vs IIS express on windows 7 using WCAT to see if scott was correct when he said IIS express has no connection limits.

Although IIS express does show 30+ requests executing at the same time against the normal IIS limit of 10 the actual total requests per seconds are comparable between both and IIS express has much higher cpu usage and on average 70 requests queued vs 0 requests waiting for normal IIS! And the CPU is only about 70% on an quad core i7. surely there is room for optimization?

additional details

I have uploaded the WCAT results run on windows 7, same script, to
http://d1yb9lkqglrfzu.cloudfront.net/IISExpress-100VU-MachineConfig.zip

IIS Express has slighter higher requests per second, and total transactions served than normal IIS.

IIS Express is executing up to 50 requests at a time, while normal IIS on windows 7 is limited to 10 as designed.

IIS express is using 30% higher cpu, probably because of additional requests it handles at a time.

But on average Express requests take much longer to complete. see Request Execution Time performance counter and time analysis (first and last byte). Express is only able to beat IIS in total requests served because it can handle more requests at a time!

Theories

Could the fact that IIS express is printing each request to command line window even with trace set none be slowing it down.

I also noticed a lot of additional modules registered in IIS express applicationhost.config that are not in IIS applicationhost.config. Could then extra debugging/tracing modules be causing the problem.

I notice IIS express does not have FileCache and HTTPCache modules. Could that be why?

I'm hoping asp.net experts can clarify how these results are possible if IIS express is not limited.

答:
Machine.config settings apply to asp.net applications running within IISExpress. Just make sure you match the .Net version and bitness (iisexpress only runs in 32 bit mode so the

%windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config or

%windir%\Microsoft.NET\Framework\v4.0.30319\CONFIG\machine.config
are the correct to files based on the CLR version. Don't edit the one in Framework64 directory.

IIS Express doesn't throttle connections, though there may be some limitations coming from the OS itself.
Performance is not really top priority for iis express. IIS Express doesn't intentionally throttle execution, but doesn't go out of it's way to fully utilize CPU.
Your performance overhead observation is interesting. I will explore what may be causing it. Did you try to run single thread client application in a loop to see how IIS compares with IIS Express.


问:
Using unnest_tokens() to split a column by a specific character?
I'm working with a column of vectors of urls formatted as a string with each url separated by a comma:

column_with_urls

["url.a, url.b, url.c"]

["url.d, url.e, url.f"]

I would like to use the tidytext::unnest_tokens() R function to separate these out into one url per line (although I'm open to other preferably R based solutions). I've read the docs here but I can't tell if it's possible/advisable to enter a single character to split on.

My thought is something like unnest_tokens(url, column_with_urls, by = ','). Is there a way to specify that kind of argument and/or a better way to solve this problem?

My desired output is a dataframe with one url per row like this (and all other data for the original rows copied over to each row):

url

url.a

url.b

url.c

...

Thanks in advance.

答:
The unnest_tokens function has an option for you to split on a regex pattern.  Below is the example syntax to split on a comma using this option (you could also use it for more complex patterns).

Note that this will convert the class of your input data to a tibble

```<code>my_df = data.frame(id=1:2, urls=c("url.a, url.b, url.c",
                                  "url.d, url.e, url.f"))
tidytext::unnest_tokens(my_df, out, urls, token = 'regex', pattern=",")
# # A tibble: 6 × 2
#     id    out
#   <int>  <chr>
# 1     1  url.a
# 2     1  url.b
# 3     1  url.c
# 4     2  url.d
# 5     2  url.e
# 6     2  url.f
</code>```

Body:
The unnest_tokens function has an option for you to split on a regex pattern.  Below is the example syntax to split on a comma using this option (you could also use it for more complex patterns).

Note that this will convert the class of your input data to a tibble

my_df = data.frame(id=1:2, urls=c("url.a, url.b, url.c",
                                  "url.d, url.e, url.f"))
tidytext::unnest_tokens(my_df, out, urls, token = 'regex', pattern=",")
# # A tibble: 6 × 2
#     id    out
#   <int>  <chr>
# 1     1  url.a
# 2     1  url.b
# 3     1  url.c
# 4     2  url.d
# 5     2  url.e
# 6     2  url.f


问:
Multiple instances of playing a video on one page using jQuery
I have some code that shows a cover image over a video, upon clicking said image it auto plays the video. Currently this code works for one video on one page (because it uses ID's).

The code is leaning on Froogaloop to control and play Vimeo.

Using jQuery how can I convert the following code so that it will work with  more than 1 video on a page (currently it breaks):

```<code>// Control Vimeo videos
var iframe = document.getElementById('video');

// $f == Froogaloop
var player = $f(iframe);

var playButton = document.getElementById("play-me");

playButton.addEventListener("click", function() {
  player.api("play");
    $('.bg-image').addClass('hide-me');

    setTimeout(function(){
        $('.bg-image').css('z-index','-1');
    }, 1000);
});
</code>```

This is my HTML:

```<code><div class="video-wrapper">
    <div class="bg-image" id="play-me">
       <span class="play">
         <i class="i-play"></i>
       </span>
    </div>
    <iframe src="" id="video"></iframe>
</div>
</code>```

答:
Assuming there will be multiple play-me elements on the page, assign them each a class instead of an ID. Then just add a click handler with your existing code inside, making sure to use this to ensure the method calls are called on the element that's clicked.

Since you're setting the z-index in your timeout you may just want to put everything else there too.

```<code>$('.play-me').on('click', function(e) {
  var $this = $(this);

  setTimeout(function() {
    player.api('play');

    $this
      .css('z-index', '-1')
      .addClass('hide-me');
  }, 1000);
});
</code>```

Body:
I have some code that shows a cover image over a video, upon clicking said image it auto plays the video. Currently this code works for one video on one page (because it uses ID's).

The code is leaning on Froogaloop to control and play Vimeo.

Using jQuery how can I convert the following code so that it will work with  more than 1 video on a page (currently it breaks):

// Control Vimeo videos
var iframe = document.getElementById('video');

// $f == Froogaloop
var player = $f(iframe);

var playButton = document.getElementById("play-me");

playButton.addEventListener("click", function() {
  player.api("play");
    $('.bg-image').addClass('hide-me');

    setTimeout(function(){
        $('.bg-image').css('z-index','-1');
    }, 1000);
});

This is my HTML:

Body:
Assuming there will be multiple play-me elements on the page, assign them each a class instead of an ID. Then just add a click handler with your existing code inside, making sure to use this to ensure the method calls are called on the element that's clicked.

Since you're setting the z-index in your timeout you may just want to put everything else there too.

$('.play-me').on('click', function(e) {
  var $this = $(this);

  setTimeout(function() {
    player.api('play');

    $this
      .css('z-index', '-1')
      .addClass('hide-me');
  }, 1000);
});


问:
Make the banner image scale proportionately with the available space in the viewport
I have a banner 900px width and 150px height, if I make the screen smaller then 900px using google chrome, I want it to adjust automatically, like scaling proportionately.
This is the code I am using:

```<code><meta name="viewport" content="width=device-width, initial-scale=1"> .........some other code......

.banner {
  background: silver;
  padding: 20px 0;
  max-width: 100%;
  overflow: auto;
}
</code>```

What would be the suggestions to achieve what I am seeking?

答:
Consider the code demonstrated below. Initially the banner is set to width of 900px and height (you can tweak it around to your needs). When the screen size reaches 900px, you can change the width of the banner with a relative value in percentage (%) or vw (view-width) like shown below. Hope, it helps.
Example code below:

#banner{
width:900px;
}
@media only screen and (max-width: 900px) {
  #banner {
    width: 90%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="banner" src="https://d33wubrfki0l68.cloudfront.net/557d279498d303f3206fae0af97a62f3625ebf4e/c3c0d/images/header/leargas-banner-900px.png"/></code>```

Body:
I have a banner 900px width and 150px height, if I make the screen smaller then 900px using google chrome, I want it to adjust automatically, like scaling proportionately.
This is the code I am using:

<meta name="viewport" content="width=device-width, initial-scale=1"> .........some other code......

.banner {
  background: silver;
  padding: 20px 0;
  max-width: 100%;
  overflow: auto;
}

What would be the suggestions to achieve what I am seeking?

Body:
Consider the code demonstrated below. Initially the banner is set to width of 900px and height (you can tweak it around to your needs). When the screen size reaches 900px, you can change the width of the banner with a relative value in percentage (%) or vw (view-width) like shown below. Hope, it helps.
Example code below:

#banner{
width:900px;
}
@media only screen and (max-width: 900px) {
  #banner {
    width: 90%;
  }
}

<img id="banner" src="https://d33wubrfki0l68.cloudfront.net/557d279498d303f3206fae0af97a62f3625ebf4e/c3c0d/images/header/leargas-banner-900px.png"/>


问:
Are there any classification algorithms which target data with a one to many (1:n) relationship?
Has there been any research in the field of data-mining regarding classifying data which has a one to many relationship?

For example of a problem like this, say I am trying to predict which students are going to drop out of university based on their class grades and personal information. Obviously there is a one to many relationship between the students personal information and the grades they achieved in their classes.

Obvious approaches include:

Aggregate - The multiple records could be aggregated together in some way reducing the problem to a basic classification problem. In the case of the student classification, the average of their grades could be combined with their personal data. While this solution is simple, often key information is lost. For example what if most students who take organic chemistry and get below a C- end up dropping out even if their average is above a B+ rating.

Voting - Create multiple classifiers (often weak ones) and have them cast votes to determine the overall class of the data in question. This would be like if two classifiers were built, one for the student's course data and one for their personal data. Each course record would be passed to the course classifier and based on the grade and the course name, the classifier would predict whether the student would drop out using that course record alone. The personal data record would be classified using the personal data classifier. Then all the class record predictions along with the personal information record prediction would be voted together. This voting could be done in a number of different ways, but most likely would take into account how accurate the classifiers are and how certain the classifier was of the vote. Clearly this scheme allows for more complicated classification patterns than aggregation, yet there is a lot of extra complexity involved. Also if the voting is not performed well, accuracy can easily suffer.

So I am looking for other possible solutions to the classification of data with a one to many relationship.

答:
It's hard to say without knowing more, but from the Bayesian perspective, you may be interested in the case of missing features. I'll discuss in general terms. For more, see [Duda and Hart, 2nd ed., pp. 54-55].

For any classifier, the Bayes decision rule is to choose class i which maximizes the probability of class i occurring given that the data x was observed, i.e., max P(i|x). The vector x contains features, e.g., a student's grades, age, etc.

Not all students take the same classes, so the feature vector x may have empty elements, i.e., "missing features". In that case, you must marginalize over the missing features, i.e., just sum over the missing features, and then make a decision upon the good, remaining features.

Example. Suppose a student took biology, but not chemistry:

```<code>P(student drops out | A+ in biology)
= P(student drops out, A+ in biology)/P(A+ in biology)
= P(student drops out, A+ in biology, A in chemistry)
  ---------------------------------------------------
  P(A+ in biology, A in chemistry)
  +
  P(student drops out, A+ in biology, B in chemistry)
  ---------------------------------------------------
  P(A+ in biology, B in chemistry)
  + ... +
  P(student drops out, A+ in biology, F in chemistry)
  ---------------------------------------------------
  P(A+ in biology, F in chemistry)
</code>```

Body:
It's hard to say without knowing more, but from the Bayesian perspective, you may be interested in the case of missing features. I'll discuss in general terms. For more, see [Duda and Hart, 2nd ed., pp. 54-55].

For any classifier, the Bayes decision rule is to choose class i which maximizes the probability of class i occurring given that the data x was observed, i.e., max P(i|x). The vector x contains features, e.g., a student's grades, age, etc.

Not all students take the same classes, so the feature vector x may have empty elements, i.e., "missing features". In that case, you must marginalize over the missing features, i.e., just sum over the missing features, and then make a decision upon the good, remaining features.

Example. Suppose a student took biology, but not chemistry:

P(student drops out | A+ in biology)
= P(student drops out, A+ in biology)/P(A+ in biology)
= P(student drops out, A+ in biology, A in chemistry)
  ---------------------------------------------------
  P(A+ in biology, A in chemistry)
  +
  P(student drops out, A+ in biology, B in chemistry)
  ---------------------------------------------------
  P(A+ in biology, B in chemistry)
  + ... +
  P(student drops out, A+ in biology, F in chemistry)
  ---------------------------------------------------
  P(A+ in biology, F in chemistry)


问:
Servlet questions
I wrote a simple Servlet that connects to the DB, retrieves some info end writes a json response. I 'm using tomcat.

Just a couple of question about servlets:

1) As far as I understood the container, if receives simultaneous requests, puts them in a queue and in the end only one Servlet at time is executed, is that true? or the container parallelize the requests using different Servlets instances?

2) In order to connect to the DB,I create the connection in another Class that implements ServletContextListener in the contextInitialized and close it in the contextDestroyed. Is that the correct way? If I want to parallelize should I use different connections , correct?

答:
No, it's not. The requests are executed concurrently, using a single servlet instance. They're only queued if there is no thread available in the tomcat thread pool to handle the request.

No, it's not. Each transaction should get its own connection from a pool of connections (a DataSource, typically exposed in JNDI by Tomcat), do its job with this connection, commit or rollback, and then close the connection to give it back to the pool.

Title: Servlet questions


问:
java printing outside of a loop
I'm a high school student learning to program, and I can't get around this problem right now. I'm trying to print the averages outside of the loop, but I don't know how. </p>

```<code>for (int index = 0; index < temperature.length; index++) {
    double tempSum = 0;
    tempSum += temperature[index];
    double averageTemp = tempSum / temperature.length;
    double rainSum = 0;
    rainSum += precipitation[index];

}

//Output: display table of weather data including average and total
System.out.println();
System.out.println("           Weather Data");
System.out.println("      Location: " + city + ", " + state);
System.out.println("Month     Temperature (" + tempLabel + ")     Precipitation (" + precipLabel + ")");
System.out.println();
System.out.println("***************************************************");

for (int index = 0; index < precipitation.length; index++) {
    System.out.println(month[index] + "     " + temperature[index] + "     " + precipitation[index]);
}

System.out.println("Average Temperature: " + averageTemp + "    Total Rainfall: " + rainSum);
</code>```

答:
The comments provide the right idea. Variables in Java have block scope, which means that they are unavailable outside the block in which they are declared. JavaScript has "hoisting," which means that, no matter where the var keyword is used, the variable will be defined.

Move your variable declarations outside of the "for" blocks. Then they will be available when the loop is done. You can also do that for the "index" variable if you need to know the its last value. Typically, that is not necessary.

Title: java printing outside of a loop

Body:
I'm a high school student learning to program, and I can't get around this problem right now. I'm trying to print the averages outside of the loop, but I don't know how.

for (int index = 0; index < temperature.length; index++) {
    double tempSum = 0;
    tempSum += temperature[index];
    double averageTemp = tempSum / temperature.length;
    double rainSum = 0;
    rainSum += precipitation[index];

}

//Output: display table of weather data including average and total
System.out.println();
System.out.println("           Weather Data");
System.out.println("      Location: " + city + ", " + state);
System.out.println("Month     Temperature (" + tempLabel + ")     Precipitation (" + precipLabel + ")");
System.out.println();
System.out.println("***************************************************");

for (int index = 0; index < precipitation.length; index++) {
    System.out.println(month[index] + "     " + temperature[index] + "     " + precipitation[index]);
}

System.out.println("Average Temperature: " + averageTemp + "    Total Rainfall: " + rainSum);


问:
Can't get item with python beautifulsoup
I'm trying to learn how to webscrape with beautifulsoup + python, and I want to grab the name of the cinematographer from https://letterboxd.com/film/donnie-darko/ but I can't figure out how to isolate the text. The html for what I want is written as below, what I want to output is "Steven Poster":

```<code><h3><span>Cinematography</span></h3>
<div class="text-sluglist">
    <p>
        <a href="/cinematography/steven-poster/" class="text-slug">Steven Poster</a>
    </p>
</div>
</code>```

within my code I've done soup.find(text="Cinematography"), and a mixture of different thigns like trying to find item or get_text from within the a and p tags, but ...

答:
I would use a regex to parse the soup object for a link that contains "cinematography".</p>

```<code>import re
import requests
from bs4 import BeautifulSoup

r = requests.get('https://letterboxd.com/film/donnie-darko/')
soup = BeautifulSoup(r.text, 'lxml')
cinematographer = soup(href=re.compile(r'/cinematography/'))[0].text

print cinematographer
# outputs "Stephen Poster"
</code>```

Body:
I'm trying to learn how to webscrape with beautifulsoup + python, and I want to grab the name of the cinematographer from https://letterboxd.com/film/donnie-darko/ but I can't figure out how to isolate the text. The html for what I want is written as below, what I want to output is "Steven Poster":

Cinematography

        Steven Poster

within my code I've done soup.find(text="Cinematography"), and a mixture of different thigns like trying to find item or get_text from within the a and p tags, but ...

Body:
I would use a regex to parse the soup object for a link that contains "cinematography".

import re
import requests
from bs4 import BeautifulSoup

r = requests.get('https://letterboxd.com/film/donnie-darko/')
soup = BeautifulSoup(r.text, 'lxml')
cinematographer = soup(href=re.compile(r'/cinematography/'))[0].text

print cinematographer
# outputs "Stephen Poster"


问:
which webserver is suitable for this design?
We start to implement a project at university to check student attendances. Each student card will be recognized by the RFID module on an Embedded Linux board. The Embedded Linux board can communicate with the a remote webserver to check the identification of the student card. The webserver is expected to have the following features:

has a database so that we can add or remove entries for student cards.

can authenticate the client access, so that only authorized users (or the Embedded Linux board) have privileges to manipulate the database.

has a web interface for admin remote management.

the Embedded Linux board can retrieve data and put new data to the database (we intend to use cURL to implement this feature).

We have never done any projects on deploying webserver before, we don't know what kind of webserver is suitable for this design. Any suggestions are appreciated. Thanks in advance.

答:
Not sure if this is the structure you want but this is the structure generally used when an embedded linux device hosting an application needs to communicate to a server based DB:

On server use LAMP/WAMP and expose a set of webservices using php that provide an interface to talk to the DB. The webservice can send back data in XML or JSON or pian text as well depending on the project needs.

On the device side your application communicates with the server by calling appropriate webservices exposed and receives data back from it.

If you want remote access also, you need to develop a web application hosted on the server that also talks to the DB using the php based webservices. This way both your device and remote web application are using the same interface to talk to the DB. This can further be enhanced so that data changed from one is pushed to the other also eg data modified on device gets pushed realtime to the web application also.


问:
"The Id field is required" validation message on Create; Id not set to [Required]
This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2.

The POCO has the following properties:

```<code>public int Id {get;set;}

[Required]
public string Message {get; set}
</code>```

On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action.

The ModelState says that "The Id field is required", but I haven't set that to be so.
Is there something automatic going on here?

EDIT - Reason Revealed

The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul):

You're providing a value for
  ID, you just didn't know you were.
  It's in the route data of the default
  route ("{controller}/{action}/{id}"),
  and its default value is the empty
  string, which isn't valid for an int.
  Use the [Bind] attribute on your
  action parameter to exclude ID. My
  default route was: new { controller =
  "Customer", action = "Edit", id = " "
  } // Parameter defaults

EDIT - Update Model technique

I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that.

```<code>    [HttpPost]
    public ActionResult Add(Venue collection)
    {
        Venue venue = new Venue();
        if (TryUpdateModel(venue, null, null, new[] { "Id" }))
        {
            _service.Add(venue);
            return RedirectToAction("Index", "Manage");
        }
        return View(collection);
    }
</code>```

答:
You can disable this implicit validation by setting the AddImplicitRequiredAttributeForValueTypes option on the DataAnnotationsModelValidatorProvider by adding the following to your Application_Start:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
```

Further Reading:

Unrequired property keeps getting data-val-required attribute

ASP.NET MVC optional field being treated as required

Why MVC Model Binder set required for int, long values?

Body:
This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2.

The POCO has the following properties:

public int Id {get;set;}

[Required]
public string Message {get; set}

On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action.

The ModelState says that "The Id field is required", but I haven't set that to be so.
Is there something automatic going on here?

EDIT - Reason Revealed

The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul):

You're providing a value for
  ID, you just didn't know you were.
  It's in the route data of the default
  route ("{controller}/{action}/{id}"),
  and its default value is the empty
  string, which isn't valid for an int.
  Use the [Bind] attribute on your
  action parameter to exclude ID. My
  default route was: new { controller =
  "Customer", action = "Edit", id = " "
  } // Parameter defaults

EDIT - Update Model technique

I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that.

    [HttpPost]
    public ActionResult Add(Venue collection)
    {
        Venue venue = new Venue();
        if (TryUpdateModel(venue, null, null, new[] { "Id" }))
        {
            _service.Add(venue);
            return RedirectToAction("Index", "Manage");
        }
        return View(collection);
    }

Body:
You can disable this implicit validation by setting the AddImplicitRequiredAttributeForValueTypes option on the DataAnnotationsModelValidatorProvider by adding the following to your Application_Start:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Further Reading:

Unrequired property keeps getting data-val-required attribute

ASP.NET MVC optional field being treated as required

Why MVC Model Binder set required for int, long values?


问:
How to automatically close admob interstitial ad if users click the Android home button?
I was using the interstitial ad from Admob in my android app. The interstitialAd.show() is called at certain events of the app. Everything worked fine but one annoying use case with the ad.

If users click HOME while the ad is displaying or the ad activity (i.e. users click the ad) is active, the ad or the ad activity will be displayed after switching back to the app. I would prefer that the app is displayed (i.e. the main activity is at the top of the activity stack) since it looked confusing to the users to see the ad first.

I tried to trap all the activity callbacks (such as onStart(), onResume() ...), but apparently the app will never become foreground in this use case. Since the ad activity is started by calling interstitialAd.show(), the tricks I know on managing the activity stack does not help, either.

Does anyone know how to automatically close the ad and return the app main activity to the top?

Thanks.

答:
This may be too late but you cannot close the ad automatically. A hack around it is that in your onBackPressed() method, after the user taps on the back button to close the ad, you return the user to the application and using a Toast method, alert the user to click the back button again to exit the application. This approach also satisfies Google's suggestion that you allow the user to know which app is displaying the ads, thus you return to the app before closing it finally. In terms of the user experience, it may not be the best but it sure does do the trick. Below is a sample code.</p>

```<code>boolean doubleBackToExitPressedOnce = false;
public void onBackPressed() {
    if(doubleBackToExitPressedOnce) {
       super.onBackPressed();
       return;
    }

    if(backPressAd.isLoaded()) {
        backPressAd.show();
        backPressAd.setAdListener(new AdListener(){
           @Override
           public void onAdClosed() {
              doubleBackToExitPressedOnce = true;
              Toast.makeText(getApplicationContext(), "Click BACK again to exit", Toast.LENGTH_LONG).show();
              backPressAd.loadAd(new AdRequest.Builder().build());
           }
        });
    } else {
      finish();
    }
}
</code>```

Body:
This may be too late but you cannot close the ad automatically. A hack around it is that in your onBackPressed() method, after the user taps on the back button to close the ad, you return the user to the application and using a Toast method, alert the user to click the back button again to exit the application. This approach also satisfies Google's suggestion that you allow the user to know which app is displaying the ads, thus you return to the app before closing it finally. In terms of the user experience, it may not be the best but it sure does do the trick. Below is a sample code.

boolean doubleBackToExitPressedOnce = false;
public void onBackPressed() {
    if(doubleBackToExitPressedOnce) {
       super.onBackPressed();
       return;
    }

    if(backPressAd.isLoaded()) {
        backPressAd.show();
        backPressAd.setAdListener(new AdListener(){
           @Override
           public void onAdClosed() {
              doubleBackToExitPressedOnce = true;
              Toast.makeText(getApplicationContext(), "Click BACK again to exit", Toast.LENGTH_LONG).show();
              backPressAd.loadAd(new AdRequest.Builder().build());
           }
        });
    } else {
      finish();
    }
}


问:
How can I detect the presence of Intel Quick Sync from c++ code?
I want to detect whether Intel Quick Sync is present and enabled on the processor.  FYI, it may be disabled (powered down) if you have no video cable plugged into the motherboard, or can be disabled in the BIOS.
Thanks
Ron</p>

答:
There is no general solution for something like this, the code would have to be specific to the OS you are running.  It would likely boil down to a system call to determine the feature set of the processor you are running i.e. maybe something like cat /proc/cpuinfo if you were running Linux for example.

There are multiple ways to execute a system call in C++. Take a look at some of the previous answers here How to execute a command and get output of command within C++ using POSIX?


答:
In your code the variable averageTemp is only existing/ accessible within the for-loop.
To have it accessible outside of the loop, you need to the declare outside, in your case before the loop. Kind of

```<code>double averageTemperature;
for (....) {
</code>```

In the for-loop you could sum up the temperatures to tempSum and after the loop is finished divide tempSumby the number of items you iterated over in the loop. If you would like to do so, keep in mind that also tempSum has to be declared before entering the loop.

Title: java printing outside of a loop

Body:
In your code the variable averageTemp is only existing/ accessible within the for-loop.
To have it accessible outside of the loop, you need to the declare outside, in your case before the loop. Kind of

double averageTemperature;
for (....) {

In the for-loop you could sum up the temperatures to tempSum and after the loop is finished divide tempSumby the number of items you iterated over in the loop. If you would like to do so, keep in mind that also tempSum has to be declared before entering the loop.


问:
python flask return prior execution of reboot
for reasons I want to trigger the reboot of an raspberry pi using a REST api.

My REST api is coded in python flask like this:

```<code>from flask import Flask
from flask import jsonify
import subprocess

app = Flask(__name__)

@app.route('/api/reboot')
def reboot():
    subprocess.call("/sbin/reboot")
    return jsonify(triggered='reboot')

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0")
</code>```

the code is working perfectly fine. But due to its a reboot the return will not be send (because the system is rebooting obviously).

Is there a way to trigger the reboot some kind of async with a delay of a couple milliseconds, that allows to return some value (in my case just an custom 'ack') prior the actual reboot?

答:
Try threading.Timer:

For example:

```<code>from flask import Flask
from flask import jsonify
import subprocess
import threading

app = Flask(__name__)

def _reboot():
    subprocess.call("/sbin/reboot")

@app.route('/api/reboot')
def reboot():
    t = threading.Timer(1, _reboot)
    t.start()
    return jsonify(triggered='reboot')

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0")
</code>```

Body:
for reasons I want to trigger the reboot of an raspberry pi using a REST api.

My REST api is coded in python flask like this:

from flask import Flask
from flask import jsonify
import subprocess

app = Flask(__name__)

@app.route('/api/reboot')
def reboot():
    subprocess.call("/sbin/reboot")
    return jsonify(triggered='reboot')

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0")

the code is working perfectly fine. But due to its a reboot the return will not be send (because the system is rebooting obviously).

Is there a way to trigger the reboot some kind of async with a delay of a couple milliseconds, that allows to return some value (in my case just an custom 'ack') prior the actual reboot?

Body:
Try threading.Timer:

For example:

from flask import Flask
from flask import jsonify
import subprocess
import threading

app = Flask(__name__)

def _reboot():
    subprocess.call("/sbin/reboot")

@app.route('/api/reboot')
def reboot():
    t = threading.Timer(1, _reboot)
    t.start()
    return jsonify(triggered='reboot')

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0")


问:
How to calculate area of polygon from list of points with python?
I have a list/array of 2D points which form a non-convex non-self-intersecting shape.
I want to calculate the area enclosed by that polygon.

First I need to form a polygon with the points that I get provided as a 'curve-walk' (non self intersecting). If I can triangulate that polygon I can calculate the area ( I can tolerate a small relative error).

Using scipy's scipy.spatial.ConvexHull() results in  the wrong shape and area , obviously, but I have not found a available algorithm in the big math packages which does this.

Can anyone tell me how to do that ?

答:
use the shapely module available for both Python 2.7 and 3</p>

```<code>In [41]: from shapely.geometry import Polygon

In [48]: coords  = ((-1, 0), (-1, 1), (0, 0.5), (1, 1), (1, 0), (-1, 0))

In [49]: polygon = Polygon(coords)

In [50]: polygon.area
Out[50]: 1.5
</code>```

Body:
use the shapely module available for both Python 2.7 and 3

In [41]: from shapely.geometry import Polygon

In [48]: coords  = ((-1, 0), (-1, 1), (0, 0.5), (1, 1), (1, 0), (-1, 0))

In [49]: polygon = Polygon(coords)

In [50]: polygon.area
Out[50]: 1.5


问:
Can you document the APIs which are developed by someone else using swagger?
I am a newbie to swagger.io. And i have a bunch of APIs that have been developed by a team which is no longer working with me. So these APIs aren't properly documented by them. So, i was thinking to use swagger and document them properly.

But the Question is, Is possible to document these APIs with swagger?

If yes, How?
If no, is there any other tool/framework for me to do it?

答: Yes, you can write an OpenAPI (fka Swagger) definition (.yaml or .json) for an API manually in the Swagger Editor and then use Swagger UI to display the API docs. However, in this case the OpenAPI definition is not synchronized with the API implementation (that is, not linked to the source code), so if the implementation changes you will need to update the OpenAPI definition manually.</p>


问:
Taking dictionary/list, and mapping to dataframe with x number of matching columns
I have a table that contains 2 columns.

```<code>     Column 1 | Column 2
----------------------------
unique_number | '123 Main St. Suite 100 Chicago, IL'
</code>```

I've been exploring address parsing using https://parserator.datamade.us/api-docs and ideally would like to parse the address, and put the results into new columns.

```<code>import usaddress
addr='123 Main St. Suite 100 Chicago, IL'
</code>```

Two options for returning parsed results, and I plan on using whichever is easier to add to a dataframe:

usaddress.parse(addr) The parse method will split your address string into components, and
label each component. (returns list)

usaddress.tag(addr) The tag method will try to be a little smarter it will merge consecutive components, strip commas, & return an address type (returns ordered list)

There are 26 different tags available for an address using this parser.

However, Not all addresses will contain all of these tags.

I need to grab the full address for each row, parse it, map the parsed results to each matching column in that same row.

What the tag data looks like using from_records (index isn't exactly ideal)

What the parse data looks like using from_records

I can't quite figure out how to logic of row by row calculations and mapping results.

答:
First, create a column of json responses from the parsing service

```<code>df['json_response'] = df['address'].apply(usaddress.pars)
</code>```

Next, combine all the jsons into a single json string

```<code>json_combined = json.dumps(list(df['json_response']))
</code>```

Finally parse the combined json to a dataframe (after parsing the json string)

```<code>df_parsed = pd.io.json.json_normalize(json.loads(json_combined))
</code>```

Now you should have a structured dataframe with all required columns which you can df.join with your original dataframe to produce a single unified dataset.

Just a note, depending on the structure of the returned json, you may need to pass further arguments to the `pandas.io.json.json_normalize function. The example on the linked page is a good starting point.

Body:
I have a table that contains 2 columns.

     Column 1 | Column 2
----------------------------
unique_number | '123 Main St. Suite 100 Chicago, IL'

I've been exploring address parsing using https://parserator.datamade.us/api-docs and ideally would like to parse the address, and put the results into new columns.

import usaddress
addr='123 Main St. Suite 100 Chicago, IL'

Two options for returning parsed results, and I plan on using whichever is easier to add to a dataframe:

usaddress.parse(addr) The parse method will split your address string into components, and
label each component. (returns list)

usaddress.tag(addr) The tag method will try to be a little smarter it will merge consecutive components, strip commas, & return an address type (returns ordered list)

There are 26 different tags available for an address using this parser.

However, Not all addresses will contain all of these tags.

I need to grab the full address for each row, parse it, map the parsed results to each matching column in that same row.

What the tag data looks like using from_records (index isn't exactly ideal)

What the parse data looks like using from_records

I can't quite figure out how to logic of row by row calculations and mapping results.

Body:
First, create a column of json responses from the parsing service

df['json_response'] = df['address'].apply(usaddress.pars)

Next, combine all the jsons into a single json string

json_combined = json.dumps(list(df['json_response']))

Finally parse the combined json to a dataframe (after parsing the json string)

df_parsed = pd.io.json.json_normalize(json.loads(json_combined))

Now you should have a structured dataframe with all required columns which you can df.join with your original dataframe to produce a single unified dataset.

Just a note, depending on the structure of the returned json, you may need to pass further arguments to the `pandas.io.json.json_normalize function. The example on the linked page is a good starting point.


问:
Code that will shuffle songs that are selected
As the title shows, I'm trying to write a code that shuffles a list of songs chosen by the user. I succeeded with all the parts but the one that shuffles the songs, it seems that the code does nothing at all when it's supposed to shuffle the list of songs. Below is the code where Z is a cell array containing all the tracks' names chosen by the user, and V is also a cell array containing all the tracks available that can be chosen by the user. I just need some help with completing this code or even changing it all if needed. By the way myoffset is just a value chosen by the user also through input, my friend told me to use it but I don't get why so if it gets in your way just ignore/delete it. </p>

```<code>function shuffled=theSpotifyShuffle(Z, myOffset)
Z=strcat('Track',L,':',V(result)');
U1=unique(Z);
Numbsongs = zeros(size(U1));
for i = 1:length(U1)
Numbsongs(i) = sum(strcmp(chosen,U1(i)));
end
for j=1:length(T)
for i = 1:length(U1)
 if Numbsongs(i)==1
     myOrder(Numbsongs)=rand(1);
else Numbsongs(i)> 1;
 N=Numbsongs(i);
 for n=1:N
     myorder(i)=(n/(N+1)*(1+myOffset*randn(1)));
 end
 end
 end
 end
 end
</code>```

答:
Use randperm to generate the shuffled indices and use them to get shuffled Z.

```<code>shuffled = Z(randperm(numel(Z)));
</code>```

Body:
As the title shows, I'm trying to write a code that shuffles a list of songs chosen by the user. I succeeded with all the parts but the one that shuffles the songs, it seems that the code does nothing at all when it's supposed to shuffle the list of songs. Below is the code where Z is a cell array containing all the tracks' names chosen by the user, and V is also a cell array containing all the tracks available that can be chosen by the user. I just need some help with completing this code or even changing it all if needed. By the way myoffset is just a value chosen by the user also through input, my friend told me to use it but I don't get why so if it gets in your way just ignore/delete it.

function shuffled=theSpotifyShuffle(Z, myOffset)
Z=strcat('Track',L,':',V(result)');
U1=unique(Z);
Numbsongs = zeros(size(U1));
for i = 1:length(U1)
Numbsongs(i) = sum(strcmp(chosen,U1(i)));
end
for j=1:length(T)
for i = 1:length(U1)
 if Numbsongs(i)==1
     myOrder(Numbsongs)=rand(1);
else Numbsongs(i)> 1;
 N=Numbsongs(i);
 for n=1:N
     myorder(i)=(n/(N+1)*(1+myOffset*randn(1)));
 end
 end
 end
 end
 end

Body:
Use randperm to generate the shuffled indices and use them to get shuffled Z.

shuffled = Z(randperm(numel(Z)));


问:
Reversing words in shell
Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

EDIT: Let's assume word is a not interrupted sequence of letters from english alphabet.

( letter: ASCII range A-Z && a-z)

Example:

Input: "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them."

Output: "enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."

I have been able to write this script, but it sruggles with words with special chracters such as {,.} that are not supposed to be reversed.

```<code>#!/bin/bash

    word_length=0
    touch tmp

    for word in $(cat ./TEXT)
    do
            word_length=$(echo -n $word | wc -c )
            if [ $word_length -le 5 ]
            then
                    echo -n $word | rev >> tmp
                    echo -n " " >> tmp
            else
                    echo -n $word >> tmp
                    echo -n " " >> tmp
            fi
    done

    cat tmp > TEXT
    echo " " >> TEXT
    rm -rf tmp
</code>```

Output of this script:
"enO gnir ot elur meht ,lla eno gnir ot dnif ,meht enO gnir ot gnirb meht lla dna ni eht darkness dnib .meht"

You can see that {,.} are in the wrong place.

答:
With for word in $(cat ./TEXT),
it may look like you iterate over words of the input,
but Bash has a different definition of words than what you might expect.
In the above statement,
Bash performs word splitting,
but that just means splitting by the value of IFS.
By default this value is sequence of whitespace characters.
Which means that punctuation will be part of the words.

Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

For a robust solution,
consider this algorithm:

Initialize word to be the empty string

For each character c in the input

If c is a letter, append it to word

Otherwise:

If word is longer then 4 characters, print it

Or else if word is not empty, reverse it

Reset word to empty

Print c

After the loop, print word, to make sure the last word gets printed

Using pure Bash:

```<code>#!/usr/bin/env bash

s=$(cat ./TEXT)

print_reverse() {
    local w=$1
    local i
    reversed=
    for ((i = 0; i < ${#w}; i++)); do
        reversed=${w:i:1}$reversed
    done
    printf "$reversed"
}

print_word() {
    local w=$1
    if [ ${#w} -gt 4 ]; then
        printf "$w"
    elif [ "$w" ]; then
        print_reverse "$w"
    fi
}

word=
for ((i = 0; i < ${#s}; i++)); do
    c=${s:i:1}
    case "$c" in
        [a-zA-Z]) word=$word$c ;;
        *)
            print_word "$word"
            word=
            printf "$c"
            ;;
    esac
done

print_word "$word"
</code>```

Title: Reversing words in shell

Body:
Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

EDIT: Let's assume word is a not interrupted sequence of letters from english alphabet.

( letter: ASCII range A-Z && a-z)

Example:

Input: "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them."

Output: "enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."

I have been able to write this script, but it sruggles with words with special chracters such as {,.} that are not supposed to be reversed.

#!/bin/bash

    word_length=0
    touch tmp

    for word in $(cat ./TEXT)
    do
            word_length=$(echo -n $word | wc -c )
            if [ $word_length -le 5 ]
            then
                    echo -n $word | rev >> tmp
                    echo -n " " >> tmp
            else
                    echo -n $word >> tmp
                    echo -n " " >> tmp
            fi
    done

    cat tmp > TEXT
    echo " " >> TEXT
    rm -rf tmp

Output of this script:
"enO gnir ot elur meht ,lla eno gnir ot dnif ,meht enO gnir ot gnirb meht lla dna ni eht darkness dnib .meht"

You can see that {,.} are in the wrong place.

Body:
With for word in $(cat ./TEXT),
it may look like you iterate over words of the input,
but Bash has a different definition of words than what you might expect.
In the above statement,
Bash performs word splitting,
but that just means splitting by the value of IFS.
By default this value is sequence of whitespace characters.
Which means that punctuation will be part of the words.

Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

For a robust solution,
consider this algorithm:

Initialize word to be the empty string

For each character c in the input

If c is a letter, append it to word

Otherwise:

If word is longer then 4 characters, print it

Or else if word is not empty, reverse it

Reset word to empty

Print c

After the loop, print word, to make sure the last word gets printed

Using pure Bash:

#!/usr/bin/env bash

s=$(cat ./TEXT)

print_reverse() {
    local w=$1
    local i
    reversed=
    for ((i = 0; i < ${#w}; i++)); do
        reversed=${w:i:1}$reversed
    done
    printf "$reversed"
}

print_word() {
    local w=$1
    if [ ${#w} -gt 4 ]; then
        printf "$w"
    elif [ "$w" ]; then
        print_reverse "$w"
    fi
}

word=
for ((i = 0; i < ${#s}; i++)); do
    c=${s:i:1}
    case "$c" in
        [a-zA-Z]) word=$word$c ;;
        *)
            print_word "$word"
            word=
            printf "$c"
            ;;
    esac
done

print_word "$word"