问:
Angular 2 - Email validation
How can I check if email exists in database using custom validator? I have tried to found built in validator but there is none for that purpose.
I can't put code to question because I'm new to angular 2 and I don't know how to use custom validators.

In component I get all users from database and I need to check if email entered in input form already existis.

```<code>ngOnInit() {
this.registrationService.getUsers().subscribe(data => this.allUsers = data, error => this.errorMsg = error);
</code>```

}

in service:

```<code>AddUser(regValues: any, allUsers: any) {
    if (regValues.email !== "" || regValues.password !== "" || regValues.nickname !== "" || regValues.confirmpassword !== "") {

        if (regValues.password != regValues.confirmpassword) {
            window.alert("Password and confirm password don't match. Please input same password in these two fields.");
        }
        else if (regValues.password.length < 7) {
            window.alert("Password must have minimum 7 characters. Please input password that has apropriate length.");
        }
        else if (regValues.username.length < 3) {
            window.alert("Nickname must have minimum 3 characters. Please input nickname that has apropriate length.");
        }
        else {

            if (allUsers.indexOf(regValues.email) !== -1) {
                window.alert("This email is already taken. Please choose another one.");
            }

            var regUser = {
                Email: regValues.email,
                PasswordHash: undefined,
                UserName: regValues.username
            }

            regUser.PasswordHash = Md5.hashStr(regValues.password);

            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            return this.http.post('/footballapi/user/add', regUser, options)
                .map((response: Response) => response.json())
                .catch(this.registrationService.errorHandler);
        }
    }
}
</code>```

In component:

Register(regValues: any) {
        let allUsers = this.registrationService.getUsers();
        this.registrationService.AddUser(regValues, allUsers).subscribe(data => this.allUsers = data, error => this.errorMsg = error);
    }

HTML form:

Create a new account.

{{errorMsg}}

<form #registrationForm="ngForm" (ngSubmit)="Register(registrationForm.value)">

        Email:

            <input type="text" name="email" ngModel required placeholder="Write your email address here..." />

        Nickname:

            <input type="text" name="nickname" ngModel required placeholder="Write your nickname here..." />

        Password:

            <input type="password" name="password" ngModel required placeholder="Write your password here..." />

        Confirm password:

            <input type="password" name="confirmpassword" ngModel required placeholder="Write your password again..." />

            <button type="submit" [disabled]="!registrationForm.form.valid">Confirm registration</button>

</form>```

答:
You can achieve this by using Async Validator

You have to write a Validator function, make a call to database and return a variable to say weather the email exists or not.

```<code>import {Control} from "@angular/common"
export class EmailValidators{
static checkEmail(control: Control){
  // make a db call{
// if exists
return {checkEmail : true}

}else return null;

}
}
</code>```

Then this returned boolean flag will be passed as the aync validator parameter
if you use model driven forms and using formbuilder, include this in your component

```<code>export calss AppComponent{
constructor(fb : FormBuilder){
this.form = fb.group({
 email:['',Validators.EmailValidators.checkEmail]
})
}
}
</code>```

Here is EmailValidators is the class that u import and checkEmail is the static method used to define your custom validation, which returns the boolean.

Title: Angular 2 - Email validation

Body:
How can I check if email exists in database using custom validator? I have tried to found built in validator but there is none for that purpose.
I can't put code to question because I'm new to angular 2 and I don't know how to use custom validators.

In component I get all users from database and I need to check if email entered in input form already existis.

ngOnInit() {
this.registrationService.getUsers().subscribe(data => this.allUsers = data, error => this.errorMsg = error);

}

in service:

AddUser(regValues: any, allUsers: any) {
    if (regValues.email !== "" || regValues.password !== "" || regValues.nickname !== "" || regValues.confirmpassword !== "") {

        if (regValues.password != regValues.confirmpassword) {
            window.alert("Password and confirm password don't match. Please input same password in these two fields.");
        }
        else if (regValues.password.length < 7) {
            window.alert("Password must have minimum 7 characters. Please input password that has apropriate length.");
        }
        else if (regValues.username.length < 3) {
            window.alert("Nickname must have minimum 3 characters. Please input nickname that has apropriate length.");
        }
        else {

            if (allUsers.indexOf(regValues.email) !== -1) {
                window.alert("This email is already taken. Please choose another one.");
            }

            var regUser = {
                Email: regValues.email,
                PasswordHash: undefined,
                UserName: regValues.username
            }

            regUser.PasswordHash = Md5.hashStr(regValues.password);

            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            return this.http.post('/footballapi/user/add', regUser, options)
                .map((response: Response) => response.json())
                .catch(this.registrationService.errorHandler);
        }
    }
}

In component:

Register(regValues: any) {
        let allUsers = this.registrationService.getUsers();
        this.registrationService.AddUser(regValues, allUsers).subscribe(data => this.allUsers = data, error => this.errorMsg = error);
    }

HTML form:

Create a new account.

{{errorMsg}}

<form #registrationForm="ngForm" (ngSubmit)="Register(registrationForm.value)">

        Email:

            <input type="text" name="email" ngModel required placeholder="Write your email address here..." />

        Nickname:

            <input type="text" name="nickname" ngModel required placeholder="Write your nickname here..." />

        Password:

            <input type="password" name="password" ngModel required placeholder="Write your password here..." />

        Confirm password:

            <input type="password" name="confirmpassword" ngModel required placeholder="Write your password again..." />

            <button type="submit" [disabled]="!registrationForm.form.valid">Confirm registration</button>

</form>

Body:
You can achieve this by using Async Validator

You have to write a Validator function, make a call to database and return a variable to say weather the email exists or not.

import {Control} from "@angular/common"
export class EmailValidators{
static checkEmail(control: Control){
  // make a db call{
// if exists
return {checkEmail : true}

}else return null;

}
}

Then this returned boolean flag will be passed as the aync validator parameter
if you use model driven forms and using formbuilder, include this in your component

export calss AppComponent{
constructor(fb : FormBuilder){
this.form = fb.group({
 email:['',Validators.EmailValidators.checkEmail]
})
}
}

Here is EmailValidators is the class that u import and checkEmail is the static method used to define your custom validation, which returns the boolean.


来源: stackexchange

问:
No more connection with c3p0
I have connection issues since i decided to use c3p0 pooling.

persistence.xml

```<code>            <property name="hibernate.connection.url" value="jdbc:mysql://***.***.***.***:****/*****"/>
            <property name="hibernate.connection.username" value="****"/>
            <property name="hibernate.connection.password" value="****"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.show_sql" value="true" />
<!--            <property name="hibernate.connection.provider_class" value="org.hibernate.c3p0.internal.C3P0ConnectionProvider" /> -->
<!--            <property name="hibernate.c3p0.min_size" value="1"/> -->
<!--            <property name="hibernate.c3p0.max_size" value="50"/> -->
<!--            <property name="hibernate.c3p0.timeout" value="10000"/> -->
<!--            <property name="hibernate.c3p0.max_statements" value="100"/> -->
<!--            <property name="hibernate.c3p0.idle_test_period" value="300"/> -->
</code>```

With this config everything works fine. When i uncomment the c3p0 properties i cant even connect to my application.

```<code>try {
    user = UserDAO.connect(login,Tools.encode(password));
}
 catch (SQLException e) {
    e.printStackTrace();
    logger.error(utils.Constants.GENERAL_ERROR);
    message=utils.Constants.LOGIN_KO;
}
finally{
//some code
}
</code>```

I tried to run this code in debug. I have a break point on each block. The program directly go from the try to the finally.
Here are the logs:

```<code>2015-08-26 15:27:50 INFO  LogHelper:46 - HHH000204: Processing PersistenceUnitInfo [
name: ****
...]
2015-08-26 15:27:53 INFO  Version:54 - HHH000412: Hibernate Core {4.3.6.Final}
2015-08-26 15:27:53 INFO  Environment:239 - HHH000206: hibernate.properties not found
2015-08-26 15:27:53 INFO  Environment:346 - HHH000021: Bytecode provider name : javassist
2015-08-26 15:27:56 INFO  Version:66 - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-08-26 15:27:56 INFO  ConnectionProviderInitiator:190 - HHH000130: Instantiating explicit connection provider: org.hibernate.c3p0.internal.C3P0ConnectionProvider
2015-08-26 15:27:56 INFO  C3P0ConnectionProvider:117 - HHH010002: C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://***.***.***.***:****/*****
2015-08-26 15:27:56 INFO  C3P0ConnectionProvider:118 - HHH000046: Connection properties: {user=****, password=****}
2015-08-26 15:27:56 INFO  C3P0ConnectionProvider:121 - HHH000006: Autocommit mode: false
</code>```

I see there is this line in the logs

```<code>Environment:239 - HHH000206: hibernate.properties not found
</code>```

But i dont understand where it comes from and if it is the reason of the issue.
I already looked at
how to fix the error: "INFO: HHH000206: hibernate.properties not found"?
and similar posts

@Maciej Dobrowolski
I dont use Maven so i dont have pom.xml (i wont explain why here it is not related)
Here are the jars i have in the classpath:

```<code> /WebContent/WEB-INF/lib/hibernate-c3p0-5.0.0.Final.jar
 /WebContent/WEB-INF/lib/hibernate-commons-annotations-4.0.5.Final.jar
 /WebContent/WEB-INF/lib/hibernate-core-4.3.6.Final.jar
 /WebContent/WEB-INF/lib/hibernate-entitymanager-4.3.6.Final.jar
 /WebContent/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar
 /WebContent/WEB-INF/lib/c3p0-0.9.5.1.jar
</code>```

答:
It could be silly but i think you need to add:

```<code><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</code>```

to your configuration, i hope this works for you,

ContentLicense: CC BY-SA 3.0

Title: No more connection with c3p0

Body:
I have connection issues since i decided to use c3p0 pooling.

persistence.xml

            <property name="hibernate.connection.url" value="jdbc:mysql://***.***.***.***:****/*****"/>
            <property name="hibernate.connection.username" value="****"/>
            <property name="hibernate.connection.password" value="****"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.show_sql" value="true" />

With this config everything works fine. When i uncomment the c3p0 properties i cant even connect to my application.

try {
    user = UserDAO.connect(login,Tools.encode(password));
}
 catch (SQLException e) {
    e.printStackTrace();
    logger.error(utils.Constants.GENERAL_ERROR);
    message=utils.Constants.LOGIN_KO;
}
finally{
//some code
}

I tried to run this code in debug. I have a break point on each block. The program directly go from the try to the finally.
Here are the logs:

2015-08-26 15:27:50 INFO  LogHelper:46 - HHH000204: Processing PersistenceUnitInfo [
name: ****
...]
2015-08-26 15:27:53 INFO  Version:54 - HHH000412: Hibernate Core {4.3.6.Final}
2015-08-26 15:27:53 INFO  Environment:239 - HHH000206: hibernate.properties not found
2015-08-26 15:27:53 INFO  Environment:346 - HHH000021: Bytecode provider name : javassist
2015-08-26 15:27:56 INFO  Version:66 - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-08-26 15:27:56 INFO  ConnectionProviderInitiator:190 - HHH000130: Instantiating explicit connection provider: org.hibernate.c3p0.internal.C3P0ConnectionProvider
2015-08-26 15:27:56 INFO  C3P0ConnectionProvider:117 - HHH010002: C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://***.***.***.***:****/*****
2015-08-26 15:27:56 INFO  C3P0ConnectionProvider:118 - HHH000046: Connection properties: {user=****, password=****}
2015-08-26 15:27:56 INFO  C3P0ConnectionProvider:121 - HHH000006: Autocommit mode: false

I see there is this line in the logs

Environment:239 - HHH000206: hibernate.properties not found

But i dont understand where it comes from and if it is the reason of the issue.
I already looked at
how to fix the error: "INFO: HHH000206: hibernate.properties not found"?
and similar posts

@Maciej Dobrowolski
I dont use Maven so i dont have pom.xml (i wont explain why here it is not related)
Here are the jars i have in the classpath:

 /WebContent/WEB-INF/lib/hibernate-c3p0-5.0.0.Final.jar
 /WebContent/WEB-INF/lib/hibernate-commons-annotations-4.0.5.Final.jar
 /WebContent/WEB-INF/lib/hibernate-core-4.3.6.Final.jar
 /WebContent/WEB-INF/lib/hibernate-entitymanager-4.3.6.Final.jar
 /WebContent/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar
 /WebContent/WEB-INF/lib/c3p0-0.9.5.1.jar

Body:
It could be silly but i think you need to add:

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

to your configuration, i hope this works for you,


问:
What's the jquery syntax for click function of submit button
my form has a submit button that's been defined this way:

```<code><input type="submit" name="submit-reg" value="Register" class="submit button">
</code>```

What is the syntax to call the button's jquery click() function?
I've tried:

```<code>$('#submit-reg').click(function()...
</code>```

But it's not working.

答:
```<code>$(document).ready(function(){
    $(":submit").css("background-color", "red");
});
</code>```

Body:
my form has a submit button that's been defined this way:

<input type="submit" name="submit-reg" value="Register" class="submit button">

What is the syntax to call the button's jquery click() function?
I've tried:

$('#submit-reg').click(function()...

But it's not working.


问:
SQLite database update query with multiple where conditions in Android
I want to update my database table with multiple where conditions. I already did with single where condition

```<code>db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
                new String[] { String.valueOf(items.getAuthor()) });
</code>```

Now i want 2 where condition.

P.S :- No raw query

答:
Try this simple query
db.update(TABLE_FF_CHECKLIST_DATA,contentValues, "FFCHECKLISTID = ? and TASK_ID_CHK = ?" , new String[] {"EHS" , "CTO914"});

where "EHS" is value in column FFCHECKLISTID and CTO914 is value in TASK_ID_CHK.

Body:
I want to update my database table with multiple where conditions. I already did with single where condition

db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
                new String[] { String.valueOf(items.getAuthor()) });

Now i want 2 where condition.

P.S :- No raw query


问:
How to split a string by "," except between certain characters in python?
How to split a string by "," except between certain characters in python?
My data is like:

```<code>('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')
</code>```

I need to split them by "," except for 'Aa,Ab'.

The result should be:

```<code>("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")
</code>```

Do you know how to do that?

Body:
How to split a string by "," except between certain characters in python?
My data is like:

('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')

I need to split them by "," except for 'Aa,Ab'.

The result should be:

("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")

Do you know how to do that?

Body:
It appears that you are looking for ''.join():

the_string = ('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5', 19, 135, 'NULL','NULL','NULL','NULL','000113.19+135830.3')

the_string = map(str, the_string)

new_string = (' '.join(i for i in the_string))


问:
Polymer 2.0 app crashes Internet Explorer 11
I have a polymer 2.0 app that is transpiled to ES5.  It works well in Edge, Firefox, and Chrome; however, when I open it in Internet Explorer 11 on Windows 7, 8.1, or 10, the program crashes.  Sometimes it will render without most of the styles, other times it will crash before the page is even rendered.  Once, it said that a script was running long and asked if I wanted to stop the script.  Doing this also crashed IE.

Since the developer tools won't open, I'm not able to debug this.  What suggestions would you have for resolving this issue?

答: In the project's bower.json file, webcomponentsjs was only saved as a dev dependency. Changing this to a primary dependency, rerunning bower install, and then rebuilding the app has solved this issue.</p>


问:
Rundeck - Unsupported major.minor version
I'm getting this error when launching the install launcher.
$JAVA_HOME/bin/java -jar rundeck-launcher-2.8.2.jar

Exception in thread "main" java.lang.UnsupportedClassVersionError: com/dtolabs/rundeck/ExpandRunServer : Unsupported major.minor version 52.0

$JAVA_HOME/bin/java -version
java version "1.7.0_131"
Java(TM) SE Runtime Environment (build 1.7.0_131-b31)
Java HotSpot(TM) 64-Bit Server VM (build 24.131-b31, mixed mode)

The requirements for rundeck say that this should be a supported version.

from the manual

" $JAVA_HOME/bin/java -version
java version "1.7.0_131"
Java(TM) SE Runtime Environment (build 1.7.0_131-b31)
Java HotSpot(TM) 64-Bit Server VM (build 24.131-b31, mixed mode)"

What did I do wrong?
Thanks

答:
Rundeck 2.8.0+ requires Java 8 to run:

Upgrading to Rundeck 2.8 from earlier versions

Java 8 is required

Rundeck server now requires Java 8.

http://rundeck.org/docs/upgrading/index.html#java-8-is-required

I'm assuming the manual is outdated.


问:
While using a SELECT SUM() GROUP BY, how can I still get the individual values?
```<code>values = 2,3,4
</code>```

When doing a JOIN (SELECT *, SUM(values) AS MaxValues FROM table GROUP BY id), $a = $data['MaxValues'] will equal 9 as it should. However, how can I still pull the individual values(2,3,4)? trying a foreach on $b = $data['values'] only gives me one of the values. I'm assuming because of the required GROUP BY. I'm still new  to all of this. Thank you

答:
You can select both values and SUM with JOIN. Also, you don't need GROUP BY if you want to get all the values, e.g.:

```<code>SELECT value, a.sum
FROM table, (SELECT SUM(value) AS `sum` FROM table ) a;
</code>```

Body:
values = 2,3,4

When doing a JOIN (SELECT *, SUM(values) AS MaxValues FROM table GROUP BY id), $a = $data['MaxValues'] will equal 9 as it should. However, how can I still pull the individual values(2,3,4)? trying a foreach on $b = $data['values'] only gives me one of the values. I'm assuming because of the required GROUP BY. I'm still new  to all of this. Thank you

Body:
You can select both values and SUM with JOIN. Also, you don't need GROUP BY if you want to get all the values, e.g.:

SELECT value, a.sum
FROM table, (SELECT SUM(value) AS `sum` FROM table ) a;


答:
You are looking for group_concat(), I think:

```<code>JOIN (SELECT id, SUM(values) AS MaxValues, group_concat(values) as values
      FROM table
      GROUP BY id)
</code>```

Note:  You should not be using SELECT * with GROUP BY.  Only include the columns in the GROUP BY clause.

Title: While using a SELECT SUM() GROUP BY, how can I still get the individual values?

Body:
You are looking for group_concat(), I think:

JOIN (SELECT id, SUM(values) AS MaxValues, group_concat(values) as values
      FROM table
      GROUP BY id)

Note:  You should not be using SELECT * with GROUP BY.  Only include the columns in the GROUP BY clause.


问:
Displaying progress of file download in a ProgressBar with SSH.NET
I want to show the progress of a downloading process on my ProgressBar. I tried to do somethings like this code for upload, but I failed. Here is an example of my failed attempts

```<code>private void button5_Click(object sender, EventArgs e)
{
    Task.Run(() => Download());
}

private void Download()
{
    try
    {
        int Port = (int)numericUpDown1.Value;
        string Host = comboBox1.Text;
        string Username = textBox3.Text;
        string Password = textBox4.Text;
        string SourcePath = textBox5.Text;
        string RemotePath = textBox6.Text;
        string FileName = textBox7.Text;

        using (var file = File.OpenWrite(SourcePath + FileName))
        using (var Stream = new FileStream(SourcePath + FileName, FileMode.Open))
        using (var Client = new SftpClient(Host, Port, Username, Password))
        {
            Client.Connect();
            progressBar1.Invoke((MethodInvoker)
            delegate
            {
                progressBar1.Maximum = (int)Stream.Length;
            });
            Client.DownloadFile(RemotePath + FileName, /*file*/ Stream, DownloadProgresBar);
            Client.Disconnect();
        }
    }
    catch (Exception Ex)
    {
        System.Windows.Forms.MessageBox.Show(Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
private void DownloadProgresBar(ulong Downloaded)
{
    progressBar1.Invoke((MethodInvoker)
        delegate
        {
            progressBar1.Value = (int)Downloaded;
        });
}
</code>```

Thank you in advance

答:
As you correctly did, similarly to the code for displaying progress of file upload, you have to provide a callback to the downloadCallback argument of SftpClient.DownloadFile.

```<code>public void DownloadFile(
    string path, Stream output, Action<ulong> downloadCallback = null)
</code>```

Also you correctly download on a background thread. Alternatively, you could use an asynchronous upload (SftpClient.BeginDownloadFile).

What is wrong and needs change:

You have to open/create the local file for writing (FileMode.Create).

You have to retrieve a size of the remote file, not the local one (not existing yet). Use SftpClient.GetAttributes.

Example using a background thread (task):

```<code>private void button1_Click(object sender, EventArgs e)
{
    // Run Download on background thread
    Task.Run(() => Download());
}

private void Download()
{
    try
    {
        int Port = 22;
        string Host = "example.com";
        string Username = "username";
        string Password = "password";
        string RemotePath = "/remote/path/";
        string SourcePath = @"C:\local\path\";
        string FileName = "download.txt";

        string SourceFilePath = SourcePath + FileName;
        using (var stream = new FileStream(SourceFilePath, FileMode.Create))
        using (var client = new SftpClient(Host, Port, Username, Password))
        {
            client.Connect();
            string RemoteFilePath = RemotePath + FileName;
            SftpFileAttributes attrs = client.GetAttributes(RemoteFilePath);
            // Set progress bar maximum on foreground thread
            int max = (int)attrs.Size;
            progressBar1.Invoke(
                (MethodInvoker)delegate { progressBar1.Maximum = max; });
            // Download with progress callback
            client.DownloadFile(RemoteFilePath, stream, DownloadProgresBar);
            MessageBox.Show("Download complete");
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

private void DownloadProgresBar(ulong uploaded)
{
    // Update progress bar on foreground thread
    progressBar1.Invoke(
        (MethodInvoker)delegate { progressBar1.Value = (int)uploaded; });
}
</code>```

For upload see:

Displaying progress of file upload in a ProgressBar with SSH.NET

Body:
I want to show the progress of a downloading process on my ProgressBar. I tried to do somethings like this code for upload, but I failed. Here is an example of my failed attempts

private void button5_Click(object sender, EventArgs e)
{
    Task.Run(() => Download());
}

private void Download()
{
    try
    {
        int Port = (int)numericUpDown1.Value;
        string Host = comboBox1.Text;
        string Username = textBox3.Text;
        string Password = textBox4.Text;
        string SourcePath = textBox5.Text;
        string RemotePath = textBox6.Text;
        string FileName = textBox7.Text;

        using (var file = File.OpenWrite(SourcePath + FileName))
        using (var Stream = new FileStream(SourcePath + FileName, FileMode.Open))
        using (var Client = new SftpClient(Host, Port, Username, Password))
        {
            Client.Connect();
            progressBar1.Invoke((MethodInvoker)
            delegate
            {
                progressBar1.Maximum = (int)Stream.Length;
            });
            Client.DownloadFile(RemotePath + FileName, /*file*/ Stream, DownloadProgresBar);
            Client.Disconnect();
        }
    }
    catch (Exception Ex)
    {
        System.Windows.Forms.MessageBox.Show(Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
private void DownloadProgresBar(ulong Downloaded)
{
    progressBar1.Invoke((MethodInvoker)
        delegate
        {
            progressBar1.Value = (int)Downloaded;
        });
}

Thank you in advance

Body:
As you correctly did, similarly to the code for displaying progress of file upload, you have to provide a callback to the downloadCallback argument of SftpClient.DownloadFile.

public void DownloadFile(
    string path, Stream output, Action<ulong> downloadCallback = null)

Also you correctly download on a background thread. Alternatively, you could use an asynchronous upload (SftpClient.BeginDownloadFile).

What is wrong and needs change:

You have to open/create the local file for writing (FileMode.Create).

You have to retrieve a size of the remote file, not the local one (not existing yet). Use SftpClient.GetAttributes.

Example using a background thread (task):

private void button1_Click(object sender, EventArgs e)
{
    // Run Download on background thread
    Task.Run(() => Download());
}

private void Download()
{
    try
    {
        int Port = 22;
        string Host = "example.com";
        string Username = "username";
        string Password = "password";
        string RemotePath = "/remote/path/";
        string SourcePath = @"C:\local\path\";
        string FileName = "download.txt";

        string SourceFilePath = SourcePath + FileName;
        using (var stream = new FileStream(SourceFilePath, FileMode.Create))
        using (var client = new SftpClient(Host, Port, Username, Password))
        {
            client.Connect();
            string RemoteFilePath = RemotePath + FileName;
            SftpFileAttributes attrs = client.GetAttributes(RemoteFilePath);
            // Set progress bar maximum on foreground thread
            int max = (int)attrs.Size;
            progressBar1.Invoke(
                (MethodInvoker)delegate { progressBar1.Maximum = max; });
            // Download with progress callback
            client.DownloadFile(RemoteFilePath, stream, DownloadProgresBar);
            MessageBox.Show("Download complete");
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

private void DownloadProgresBar(ulong uploaded)
{
    // Update progress bar on foreground thread
    progressBar1.Invoke(
        (MethodInvoker)delegate { progressBar1.Value = (int)uploaded; });
}

For upload see:

Displaying progress of file upload in a ProgressBar with SSH.NET

ContentLicense: CC BY-SA 4.0


问:
How to perform a cumulative sum but maintain zero values in MATLAB?
I need to do a cumulative sum in MATLAB, for a matrix of zeros and ones for each row, but I need to stop it when there are no more ones. Example, if I start with:

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

I want the result:

```<code>B = [0 0 0 0 0 1 2 3 4 5 0 0 0;
     0 0 0 1 2 3 4 5 6 7 0 0 0;
     0 0 0 0 0 0 0 1 2 0 0 0 0];
</code>```

If I use cumsum, it will continue adding the values and give another result:

```<code>B = [0 0 0 0 0 1 2 3 4 5 5 5 5;
     0 0 0 1 2 3 4 5 6 7 7 7 7;
     0 0 0 0 0 0 0 1 2 2 2 2 2];
</code>```

Please, if someone has any suggestion as I can't find something similar (I have several quite large matrix).

答:
There are two potential solutions depending on how you want to handle a case where you have more than one string of ones per row (if that is a possibility). If you want the cumulative sum to reset every time a new string of ones is encountered, use the more complex solution. If you don't want the cumulative sum to reset for each new string of ones, or you only ever have one string per row, use the simpler solution:

Simple solution (one string or no cumsum resetting): You can perform the cumulative sum, then use A (specifically its negation) as a logical index to set entries back to zero:

```<code>B = cumsum(A, 2);
B(~A) = 0;

B =

     0     0     0     0     0     1     2     3     4     5     0     0     0
     0     0     0     1     2     3     4     5     6     7     0     0     0
     0     0     0     0     0     0     0     1     2     0     0     0     0
</code>```

Complex solution (reset cumsum for each string): Let's say you can have more than one string of ones per row, such as (notice the last row):

```<code>A =

     0     0     0     0     0     1     1     1     1     1     0     0     0
     0     0     0     1     1     1     1     1     1     1     0     0     0
     0     0     0     1     1     0     0     1     1     0     0     0     0
</code>```

In this case, we can take the values of the cumulative sum at the end of each string of ones, place those in a new matrix, apply cummax, then subtract from our cumulative sum:

```<code>B = cumsum(A, 2);
index = find([zeros(size(A, 1), 1) diff(A, 1, 2)] == -1);
C = zeros(size(B));
C(index) = B(index);
B = B-cummax(C, 2);

B =

     0     0     0     0     0     1     2     3     4     5     0     0     0
     0     0     0     1     2     3     4     5     6     7     0     0     0
     0     0     0     1     2     0     0     1     2     0     0     0     0
                                               ^-- sum resets
</code>```

Applying the simpler solution in this case would instead yield:

```<code>B =

     0     0     0     0     0     1     2     3     4     5     0     0     0
     0     0     0     1     2     3     4     5     6     7     0     0     0
     0     0     0     1     2     0     0     3     4     0     0     0     0
                                               ^-- no reset
</code>```

OwnerDisplayName: siaskel

Body:
I need to do a cumulative sum in MATLAB, for a matrix of zeros and ones for each row, but I need to stop it when there are no more ones. Example, if I start with:

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

I want the result:

B = [0 0 0 0 0 1 2 3 4 5 0 0 0;
     0 0 0 1 2 3 4 5 6 7 0 0 0;
     0 0 0 0 0 0 0 1 2 0 0 0 0];

If I use cumsum, it will continue adding the values and give another result:

B = [0 0 0 0 0 1 2 3 4 5 5 5 5;
     0 0 0 1 2 3 4 5 6 7 7 7 7;
     0 0 0 0 0 0 0 1 2 2 2 2 2];

Please, if someone has any suggestion as I can't find something similar (I have several quite large matrix).

Body:
There are two potential solutions depending on how you want to handle a case where you have more than one string of ones per row (if that is a possibility). If you want the cumulative sum to reset every time a new string of ones is encountered, use the more complex solution. If you don't want the cumulative sum to reset for each new string of ones, or you only ever have one string per row, use the simpler solution:

Simple solution (one string or no cumsum resetting): You can perform the cumulative sum, then use A (specifically its negation) as a logical index to set entries back to zero:

B = cumsum(A, 2);
B(~A) = 0;

B =

     0     0     0     0     0     1     2     3     4     5     0     0     0
     0     0     0     1     2     3     4     5     6     7     0     0     0
     0     0     0     0     0     0     0     1     2     0     0     0     0

Complex solution (reset cumsum for each string): Let's say you can have more than one string of ones per row, such as (notice the last row):

A =

     0     0     0     0     0     1     1     1     1     1     0     0     0
     0     0     0     1     1     1     1     1     1     1     0     0     0
     0     0     0     1     1     0     0     1     1     0     0     0     0

In this case, we can take the values of the cumulative sum at the end of each string of ones, place those in a new matrix, apply cummax, then subtract from our cumulative sum:

B = cumsum(A, 2);
index = find([zeros(size(A, 1), 1) diff(A, 1, 2)] == -1);
C = zeros(size(B));
C(index) = B(index);
B = B-cummax(C, 2);

B =

     0     0     0     0     0     1     2     3     4     5     0     0     0
     0     0     0     1     2     3     4     5     6     7     0     0     0
     0     0     0     1     2     0     0     1     2     0     0     0     0
                                               ^-- sum resets

Applying the simpler solution in this case would instead yield:

B =

     0     0     0     0     0     1     2     3     4     5     0     0     0
     0     0     0     1     2     3     4     5     6     7     0     0     0
     0     0     0     1     2     0     0     3     4     0     0     0     0
                                               ^-- no reset


问:
Why is it so difficult to find the right format for date and time for matplotlib
I need to display the time in the x axis using matplotlib, not panda. The y axis should display the temperature. The data has been generated from an api and extracted, before being placed into a multidimensional list. My latest attempt is below. the time is not displayed accurately.</p>

```<code>import matplotlib.pyplot as plt
import numpy as np
import urllib.request
import json
from datetime import datetime, timedelta, time
import matplotlib

def graph_data():

weather_api = 'http://api.openweathermap.org/data/2.5/forecast?q=London&id='
source_code = urllib.request.urlopen(weather_api)
content = source_code.read()
codes = json.loads(content.decode("utf8"))

#get the data required and put it in an array called 'weather_data'
weather_data=[]

for each in codes['list']:
    weather_data.append([
                         each['dt_txt'],
                         each['weather'][0]['description'],
                         int(each['main']['humidity']),
                         float(each['wind']['speed']),
                         int(each['main']['temp_min']),
                         int(each['main']['temp_max'])])

#store the weather details for each day
day1 = datetime.now()+timedelta(days=1)
forecast_list = []

for each in weather_data:
    date=datetime.strptime(each[0], '%Y-%m-%d %H:%M:%S') #convert string to date
    if day1.day == date.day:
        d=datetime.strptime(each[0],'%Y-%m-%d %H:%M:%S')
#           time=d.strftime('%H:%M:%S')
        forecast_list.append([d, each[4]])

time=[]
temp=[]

for each in forecast_list:
    time.append(each[0])
    temp.append(each[1])
print(time)

plt.plot(time, temp, label = 'Temperature')
plt.gcf().autofmt_xdate()
plt.xlabel('Time')
plt.ylabel('Temperature')
plt.title('Temperature for {0}'.format(day1.strftime('%Y-%d-%d')))
plt.legend()
plt.show()

graph_data()
</code>```

答:
You say "displays part of the year and a random number"—probably it is displaying the time accurately, but as a fractional year. What format do you want it to use?

Try using plt.plot_date instead of plt.plot.

Or, after plotting, you can do

```<code>ax = plt.gca()
ax.xaxis_date() # treat the x-axis as dates
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M')) # specify the format you want
</code>```

Body:
I need to display the time in the x axis using matplotlib, not panda. The y axis should display the temperature. The data has been generated from an api and extracted, before being placed into a multidimensional list. My latest attempt is below. the time is not displayed accurately.

import matplotlib.pyplot as plt
import numpy as np
import urllib.request
import json
from datetime import datetime, timedelta, time
import matplotlib

def graph_data():

weather_api = 'http://api.openweathermap.org/data/2.5/forecast?q=London&id='
source_code = urllib.request.urlopen(weather_api)
content = source_code.read()
codes = json.loads(content.decode("utf8"))

#get the data required and put it in an array called 'weather_data'
weather_data=[]

for each in codes['list']:
    weather_data.append([
                         each['dt_txt'],
                         each['weather'][0]['description'],
                         int(each['main']['humidity']),
                         float(each['wind']['speed']),
                         int(each['main']['temp_min']),
                         int(each['main']['temp_max'])])

#store the weather details for each day
day1 = datetime.now()+timedelta(days=1)
forecast_list = []

for each in weather_data:
    date=datetime.strptime(each[0], '%Y-%m-%d %H:%M:%S') #convert string to date
    if day1.day == date.day:
        d=datetime.strptime(each[0],'%Y-%m-%d %H:%M:%S')
#           time=d.strftime('%H:%M:%S')
        forecast_list.append([d, each[4]])

time=[]
temp=[]

for each in forecast_list:
    time.append(each[0])
    temp.append(each[1])
print(time)

plt.plot(time, temp, label = 'Temperature')
plt.gcf().autofmt_xdate()
plt.xlabel('Time')
plt.ylabel('Temperature')
plt.title('Temperature for {0}'.format(day1.strftime('%Y-%d-%d')))
plt.legend()
plt.show()

graph_data()

Body:
You say "displays part of the year and a random number"—probably it is displaying the time accurately, but as a fractional year. What format do you want it to use?

Try using plt.plot_date instead of plt.plot.

Or, after plotting, you can do

ax = plt.gca()
ax.xaxis_date() # treat the x-axis as dates
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M')) # specify the format you want


问:
How to set SGEN toolpath in Msbuild to target 3.5 framework
I've just upgraded a project from VS2008 to VS2010 but I'm still targeting the 3.5 framework.

In my project file I have a custom task to run SGEN to generate my XmlSerializers.dll. However the version of sgen being run targets the 4.0 framework. As a result, when I run my application I get the error message:

"Could not load file or assembly 'XXXX.XXXX.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded."

The Sgen task looks like this:

```<code>  <Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
    <!-- Delete the file because I can't figure out how to force the SGen task. -->
    <Delete Files="$(TargetDir)$(TargetName).XmlSerializers.dll" ContinueOnError="true" />
    <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
      <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
    </SGen>
  </Target>
</code>```

There's the ToolPath="$(SGenToolPath)". How do I make it run the version that targets 3.5?

There's a similar question here but it doesn't help me much.

答:
I found this to be the easiest way and it works with: <GenerateSerializationAssemblies>On</ GenerateSerializationAssemblies> </p>

```<code><SGenToolPath>C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin</SGenToolPath>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've just upgraded a project from VS2008 to VS2010 but I'm still targeting the 3.5 framework.

In my project file I have a custom task to run SGEN to generate my XmlSerializers.dll. However the version of sgen being run targets the 4.0 framework. As a result, when I run my application I get the error message:

"Could not load file or assembly 'XXXX.XXXX.XmlSerializers' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded."

The Sgen task looks like this:

  <Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">

    <Delete Files="$(TargetDir)$(TargetName).XmlSerializers.dll" ContinueOnError="true" />
    <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
      <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
    </SGen>
  </Target>

There's the ToolPath="$(SGenToolPath)". How do I make it run the version that targets 3.5?

There's a similar question here but it doesn't help me much.

Body:
I found this to be the easiest way and it works with: <GenerateSerializationAssemblies>On</ GenerateSerializationAssemblies>

<SGenToolPath>C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin</SGenToolPath>


问:
Regex split fails at cyrillic string
I need a simple and easy way to isolate words from strings of different languages. I know this is not a trivial task, but I just want to split on common punctuation like .,;:?!@#. Currently I'm using:

```<code>x = "this is sparta, or not."
print re.split([^-\w]', x)
['this', 'is', 'sparta', '', 'Or', 'not', '']
</code>```

But, when I use a Cyrillic string:

```<code>x =  u'правил произношение суффиксов можно иногда'
w = re.split(r'[^-\w]', x)
</code>```

I get:

```<code>[u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']
</code>```

How can I make a single generic splitter, which solves this problem? Thank you!

EDIT: The issue above is on Python 2.7.10.

答:
I copy and past your code on Python3 console, everything works but when I try it on Python2.7 it had same issue as you got.

That's unicode issue.

```<code>x =  u'правил произношение суффиксов можно иногда'
myinput = raw_input(x.encode('utf8'))
w = re.split(r'[^-\w]', myinput)
</code>```

Title: Regex split fails at cyrillic string

Body:
I need a simple and easy way to isolate words from strings of different languages. I know this is not a trivial task, but I just want to split on common punctuation like .,;:?!@#. Currently I'm using:

x = "this is sparta, or not."
print re.split([^-\w]', x)
['this', 'is', 'sparta', '', 'Or', 'not', '']

But, when I use a Cyrillic string:

x =  u'правил произношение суффиксов можно иногда'
w = re.split(r'[^-\w]', x)

I get:

[u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']

How can I make a single generic splitter, which solves this problem? Thank you!

EDIT: The issue above is on Python 2.7.10.

Body:
I copy and past your code on Python3 console, everything works but when I try it on Python2.7 it had same issue as you got.

That's unicode issue.

x =  u'правил произношение суффиксов можно иногда'
myinput = raw_input(x.encode('utf8'))
w = re.split(r'[^-\w]', myinput)


问:
How can i do a count of two columns in mysql?
i want to do a count of two columns in mysql. One of the columns is a string but another is a date like 06/08/2017 and when i do my query i get 0 results.

SELECT count(*) FROM `castigos` WHERE inicio_normal=05/06/2017 AND cod_emplazamiento=1```

I have entries of that data but its dont show me anything. Maybe the type of data in the date is wrong?

What should i do?

答:
Add the date field to your select and group by it.  Otherwise mysql extensions doesn't recognize you want to group by the date and will aggregrate all the results into 1 column.  And since you are getting 0 count, you're where clause must not be working.

Your date format seems malformed. usually YYYY/MM/DD format (standard format);
or specify a format using SELECT STR_TO_DATE('17/09/2010','%d/%m/%Y');

MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

the below uses the implicit casting and default date format to convert the string date to a valid date.

```<code>SELECT inicio_normal, count(*)
FROM `castigos`
WHERE inicio_normal='2017/05/06'
  AND cod_emplazamiento=1
GROUP BY inicio_normal
</code>```

Otherwise its doing math and comparing that date to the number stored for the date.

Understand dates should be stored in a date datatype and when you query dates you're passing in a string that is being cast to a date datatype for comparison.  So you need to use the standard format, or cast your string to a date so the db engine knows how to convert your format to a date.

Body:
i want to do a count of two columns in mysql. One of the columns is a string but another is a date like 06/08/2017 and when i do my query i get 0 results.

SELECT count(*) FROM `castigos` WHERE inicio_normal=05/06/2017 AND cod_emplazamiento=1

I have entries of that data but its dont show me anything. Maybe the type of data in the date is wrong?

What should i do?

Body:
Add the date field to your select and group by it.  Otherwise mysql extensions doesn't recognize you want to group by the date and will aggregrate all the results into 1 column.  And since you are getting 0 count, you're where clause must not be working.

Your date format seems malformed. usually YYYY/MM/DD format (standard format);
or specify a format using SELECT STR_TO_DATE('17/09/2010','%d/%m/%Y');

MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

the below uses the implicit casting and default date format to convert the string date to a valid date.

SELECT inicio_normal, count(*)
FROM `castigos`
WHERE inicio_normal='2017/05/06'
  AND cod_emplazamiento=1
GROUP BY inicio_normal

Otherwise its doing math and comparing that date to the number stored for the date.

Understand dates should be stored in a date datatype and when you query dates you're passing in a string that is being cast to a date datatype for comparison.  So you need to use the standard format, or cast your string to a date so the db engine knows how to convert your format to a date.


问:
How to disable mouse scroll wheel scaling with Google Maps API
I am using Google Maps API (v3) to draw a few maps on a page. One thing I'd like to do is disable zooming when you scroll the mouse wheel over the map, but I'm unsure how.

I have disabled the scaleControl (i.e. removed the scaling UI element), but this doesn't prevent scroll wheel scaling.

Here is part of my function (it's a simple jQuery plugin):

```<code>$.fn.showMap = function(options, addr){
  options = $.extend({
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }, options);
  var map = new google.maps.Map(document.getElementById($(this).attr('id')), options);

  // Code cut from this example as not relevant
};
</code>```

答:
A simple solution:

// DISABLE MOUSE SCROLL IN MAPS
// enable the pointer events only on click;
$('.gmap-wrapper').on('click', function () {
  $('.gmap-wrapper iframe').removeClass('scrolloff'); // set the pointer events true on click
});
// you want to disable pointer events when the mouse leave the canvas area;
$(".gmap-wrapper").mouseleave(function () {
  $('.gmap-wrapper iframe').addClass('scrolloff'); // set the pointer events to none when mouse leaves the map area
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.scrolloff{ pointer-events: none; }</code>```

```

Source: https://github.com/Corsidia/scrolloff

Body:
I am using Google Maps API (v3) to draw a few maps on a page. One thing I'd like to do is disable zooming when you scroll the mouse wheel over the map, but I'm unsure how.

I have disabled the scaleControl (i.e. removed the scaling UI element), but this doesn't prevent scroll wheel scaling.

Here is part of my function (it's a simple jQuery plugin):

$.fn.showMap = function(options, addr){
  options = $.extend({
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }, options);
  var map = new google.maps.Map(document.getElementById($(this).attr('id')), options);

  // Code cut from this example as not relevant
};

Body:
A simple solution:

// DISABLE MOUSE SCROLL IN MAPS
// enable the pointer events only on click;
$('.gmap-wrapper').on('click', function () {
  $('.gmap-wrapper iframe').removeClass('scrolloff'); // set the pointer events true on click
});
// you want to disable pointer events when the mouse leave the canvas area;
$(".gmap-wrapper").mouseleave(function () {
  $('.gmap-wrapper iframe').addClass('scrolloff'); // set the pointer events to none when mouse leaves the map area
});

.scrolloff{ pointer-events: none; }

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="gmap-wrapper">
<iframe class="scrolloff" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d44754.55736493158!2d9.151166379101554!3d45.486726!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4786bfca7e8fb1cb%3A0xee8d99c9d153be98!2sCorsidia!5e0!3m2!1sit!2sit!4v1496947992608" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</html>

Source: https://github.com/Corsidia/scrolloff


答:
Change your print with the loop counters to help debugging:-

```<code>for (i = 0; i<16; i++){
  printf("\n[%d %d] %d",round, i, state[i]);
}
</code>```

Output:-

```<code>[0 0] 99
[0 1] 202
....
....
[9 14] 165
[9 15] 255
</code>```

10 X 16 = 160 lines

Title: printf printing more lines in the for loop

Body:
I am having problem with an encryption algorithm in C, I'm encoding an AES criptography, I'm debugging one function, and this function is printing more lines than the for loop count. Below the entire code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned char key[]   = {
                              0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                              0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
                             };

                              unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

    const unsigned char sbox[256] =
    {
//0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
        0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0
        0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1
        0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2
        0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3
        0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4
        0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5
        0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6
        0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7
        0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8
        0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9
        0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A
        0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B
        0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C
        0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D
        0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E
        0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
    }; //F

    const unsigned char Rcon[10] = {
    0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};

    unsigned char buf1, buf2, buf3, buf4, round, i;
    unsigned char rcon;

      for (round = 0; round < 10; round++){
    //add key + sbox
    for (i = 0; i <16; i++){
      state[i]=sbox[state[i] ^ key[i]];
    }
    for (i = 0; i<16; i++){
      printf("\n%d",state[i]);
    }
  }
}

The print function (as shown above):

   for (round = 0; round < 10; round++){
        //add key + sbox
        for (i = 0; i <16; i++){
          state[i]=sbox[state[i] ^ key[i]];
        }
        for (i = 0; i<16; i++){
          printf("\n%d",state[i]);
        }
      }

The output:

99
202
183
4
9
83
208
81
205
96
224
231
186
112
225
140
251
31
213
197
215
177
246
177
166
249
135
206
78
255
223
236
15
114
14
180
102
141
140
78
228
140
93
166
44
137
62
17
118
143
254
169
170
196
126
59
206
151
91
149
183
95
4
114
56
25
176
172
228
120
188
235
180
11
209
11
234
0
103
255
7
173
55
121
225
255
244
206
101
119
185
99
142
215
249
140
197
145
150
218
217
45
137
221
60
243
109
69
19
87
104
236
166
96
34
53
193
52
115
87
24
45
133
47
192
190
51
17
36
239
183
5
166
199
157
83
202
54
115
54
75
109
39
114
54
40
213
111
58
37
20
32
37
117
182
39
160
208
165
255

Someone knows what is happening?

Body:
Change your print with the loop counters to help debugging:-

for (i = 0; i<16; i++){
  printf("\n[%d %d] %d",round, i, state[i]);
}

Output:-

[0 0] 99
[0 1] 202
....
....
[9 14] 165
[9 15] 255

10 X 16 = 160 lines


答:
Try this :</p>

```<code>SELECT count(*) FROM `castigos` WHERE inicio_normal="05/06/2017" AND cod_emplazamiento=1 GROUP BY inicio_normal
</code>```

Title: How can i do a count of two columns in mysql?

Body:
Try this :

SELECT count(*) FROM `castigos` WHERE inicio_normal="05/06/2017" AND cod_emplazamiento=1 GROUP BY inicio_normal


问:
Issue with division of a 0 / input validation
I'm getting an exception at line 223: //calculation for vat ( room cost take 25% )

System.DivideByZeroException: 'Attempted to divide by zero.'

the fixes i have tried have been to add in if else statements from lines 224 to 230 to allow the sum to retry so that it just puts a number without the crash but this has not helped. any possible fix ?

```<code>public partial class paint : Form
{
    private int price, price21;

    public paint()
    {
        InitializeComponent();
    }

    // Button for Calculations
    private void SUB_Click(object sender, EventArgs e)
    {
        if (validation() == 0)
        {
            errorProvider1.Clear();
            MessageBox.Show("Totals Below");
        }

        // northwall calculations and inputs to variables
        if (txtnorthheight.Text == "")
        {
            txtnorthheight.Text = ("0");
        }

        if (txtnorthlength.Text == "")
        {
            txtnorthlength.Text = ("0");
        }

        decimal height1 = decimal.Parse(txtnorthheight.Text);
        decimal length1 = decimal.Parse(txtnorthlength.Text);
        decimal area1 = height1 * length1;
        lblnortharea.Text = area1.ToString("n");

        // southwall calculations and inputs to variables
        if (txtsouthheight.Text == "")
        {
            txtsouthheight.Text = ("0");
        }

        if (txtsouthlength.Text == "")
        {
            txtsouthlength.Text = ("0");
        }

        decimal height2 = decimal.Parse(txtsouthheight.Text);
        decimal length2 = decimal.Parse(txtsouthlength.Text);
        decimal area2 = height2 * length2;
        lblsoutharea.Text = area2.ToString("n");

        // Eastwall calculations and inputs to variables
        if (txteasthheight.Text == "")
        {
            txteasthheight.Text = ("0");
        }

        if (txteasthlength.Text == "")
        {
            txteasthlength.Text = ("0");
        }

        decimal height3 = decimal.Parse(txteasthheight.Text);
        decimal length3 = decimal.Parse(txteasthlength.Text);
        decimal area3 = height3 * length3;
        lbleastarea.Text = area3.ToString("n");

        // Westhwall calculations and inputs to variables
        if (txtwesthheight.Text == "")
        {
            txtwesthheight.Text = ("0");
        }

        if (txtwestlength.Text == "")
        {
            txtwestlength.Text = ("0");
        }

        decimal height4 = decimal.Parse(txtwesthheight.Text);
        decimal length4 = decimal.Parse(txtwestlength.Text);
        decimal area4 = height4 * length4;
        lblwestharea.Text = area4.ToString("n");

        // window frame calculations and inputs to variables
        if (txtwinheight.Text == "")
        {
            txtwinheight.Text = ("0");
        }

        if (txtwinlength.Text == "")
        {
            txtwinlength.Text = ("0");
        }

        decimal height5 = decimal.Parse(txtwinheight.Text);
        decimal length5 = decimal.Parse(txtwinlength.Text);
        decimal area5 = height5 * length5;
        lblwinharea.Text = area5.ToString("n");

        // culculation to work out total area - window size. this is borken in to two aprts:
        // area 1 + area 2 + area 3 + area 5 then take away area 5 which is the window.
        decimal areatotal = (area1 + area2 + area3 + area4) - area5;

        lbltotalarea.Text = areatotal.ToString("n");

        // culculations for total height and length for output in invoice.
        decimal Heightt = (height1 + height2 + height3 + height4) - height5;
        decimal Legntht = (length1 + length2 + length3 + length4) - length5;
        Height2.Text = Heightt.ToString("n");
        Legnth.Text = Legntht.ToString("n");

        // variables for inputs taken on qucilty options and undercoat option.
        if (txtunder.Text == "")
        {
            txtunder.Text = ("0");
        }
        if (txtprice.Text == "")
        {
            txtprice.Text = ("0");
        }

        decimal price = decimal.Parse(txtprice.Text);
        decimal undercoat = decimal.Parse(txtunder.Text);
        decimal roomcost = (Heightt * Legntht) * price * undercoat;
        lblcost.Text = roomcost.ToString("c");

        //culculation for vat ( room cost take 25% )
        decimal Vattotal = (25 % roomcost);
        lblvat.Text = Vattotal.ToString("c");

         //culculation for roomcost + vat
         Decimal vt = Vattotal + roomcost;
         lblbt.Text = vt.ToString("c");
    }

    // reset form button
    private void Totalcost_Click(object sender, EventArgs e)
    {
        txtwinlength.Text = "";
        txtnorthheight.Text = "";
        txtnorthlength.Text = "";
        txtwesthheight.Text = "";
        txtwestlength.Text = "";
        txtsouthheight.Text = "";
        txtsouthlength.Text = "";
        txteasthheight.Text = "";
        txteasthlength.Text = "";
        txtwinheight.Text = "";
        txtprice.Text = "";
        lblnortharea.Text = "";
        lblsoutharea.Text = "";
        lblwestharea.Text = "";
        lbleastarea.Text = "";
        lblwinharea.Text = "";
        lblcost.Text = "";
        lbltotalarea.Text = "";
        Height2.Text = "";
        Legnth.Text = "";
        invoice.Text = "";
    }

    // invoice number genrator
    private void button1_Click(object sender, EventArgs e)
    {
        Random slumpGenerator = new Random(); int tal;
        tal = slumpGenerator.Next();
        invoice.Text = tal.ToString("n");
    }

    // invoice OUTput
    private void label22_Click_2(object sender, EventArgs e)
    {
        Random slumpGenerator = new Random(); int tal;
        tal = slumpGenerator.Next();
        invoice.Text = tal.ToString("n");
    }

    //input vaildation only allowing numbers and decimals.
    private void txtnorthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtnorthlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtsouthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtsouthlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtprice_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwesthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwestlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txteasthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txteasthlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwinheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwinlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtunder_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    public int validation ()
    {
        int flag = 0;

        //North input valdation
        if (txtnorthheight.Text == "")
        {
            txtnorthheight.Focus();
            errorProvider1.SetError(txtnorthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtnorthlength.Text == "")
        {
            txtnorthlength.Focus();
            errorProvider1.SetError(txtnorthlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //South input valdation
        if (txtsouthheight.Text == "")
        {
            txtsouthheight.Focus();
            errorProvider1.SetError(txtsouthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtsouthlength.Text == "")
        {
            txtsouthlength.Focus();
            errorProvider1.SetError(txtsouthlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //West  input valdation
        if (txtwesthheight.Text == "")
        {
            txtwesthheight.Focus();
            errorProvider1.SetError(txtwesthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtwestlength.Text == "")
        {
            txtwestlength.Focus();
            errorProvider1.SetError(txtwestlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //East input valdation
        if (txteasthheight.Text == "")
        {
            txteasthheight.Focus();
            errorProvider1.SetError(txteasthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txteasthlength.Text == "")
        {
            txteasthlength.Focus();
            errorProvider1.SetError(txteasthlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //Window input valdation
        if (txtwinheight.Text == "")
        {
            txtwinheight.Focus();
            errorProvider1.SetError(txtwinheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtwinlength.Text == "")
        {
            txtwinlength.Focus();
            errorProvider1.SetError(txtwinlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //quality input valdation
        if (txtprice.Text == "")
        {
            txtprice.Focus();
            errorProvider1.SetError(txtprice, MessageBox.Show("please Enter a vaild input of the above options ( You Must Enter 1 of the Options).", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        // undercoat valdation
        if (txtunder.Text == "")
        {
            txtunder.Focus();
            errorProvider1.SetError(txtunder, MessageBox.Show("Please enter the Undercoat input of 0.45, if you do not want undercoat enter 0.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }
        return flag;
    }

    private void txtnorthheight_Click(object sender, EventArgs e)
    {
        errorProvider1.Clear();
    }
    //end of valdation
}
</code>```

答:
The % symbol is the modulus operator in C#, which means it gives you the remainder after dividing the left side by the right side. In your code, it looks like you want to get 25% of the room cost, not the remainder of 25 divided by the room cost.

So, this line:

```<code>decimal Vattotal = (25 % roomcost);
</code>```

Should be changed to:

```<code>decimal Vattotal = roomcost * .25;
</code>```

The reason you're getting the exception is that roomcost is 0, and dividing by zero is an illegal operation.

Body:
I'm getting an exception at line 223: //calculation for vat ( room cost take 25% )

System.DivideByZeroException: 'Attempted to divide by zero.'

the fixes i have tried have been to add in if else statements from lines 224 to 230 to allow the sum to retry so that it just puts a number without the crash but this has not helped. any possible fix ?

public partial class paint : Form
{
    private int price, price21;

    public paint()
    {
        InitializeComponent();
    }

    // Button for Calculations
    private void SUB_Click(object sender, EventArgs e)
    {
        if (validation() == 0)
        {
            errorProvider1.Clear();
            MessageBox.Show("Totals Below");
        }

        // northwall calculations and inputs to variables
        if (txtnorthheight.Text == "")
        {
            txtnorthheight.Text = ("0");
        }

        if (txtnorthlength.Text == "")
        {
            txtnorthlength.Text = ("0");
        }

        decimal height1 = decimal.Parse(txtnorthheight.Text);
        decimal length1 = decimal.Parse(txtnorthlength.Text);
        decimal area1 = height1 * length1;
        lblnortharea.Text = area1.ToString("n");

        // southwall calculations and inputs to variables
        if (txtsouthheight.Text == "")
        {
            txtsouthheight.Text = ("0");
        }

        if (txtsouthlength.Text == "")
        {
            txtsouthlength.Text = ("0");
        }

        decimal height2 = decimal.Parse(txtsouthheight.Text);
        decimal length2 = decimal.Parse(txtsouthlength.Text);
        decimal area2 = height2 * length2;
        lblsoutharea.Text = area2.ToString("n");

        // Eastwall calculations and inputs to variables
        if (txteasthheight.Text == "")
        {
            txteasthheight.Text = ("0");
        }

        if (txteasthlength.Text == "")
        {
            txteasthlength.Text = ("0");
        }

        decimal height3 = decimal.Parse(txteasthheight.Text);
        decimal length3 = decimal.Parse(txteasthlength.Text);
        decimal area3 = height3 * length3;
        lbleastarea.Text = area3.ToString("n");

        // Westhwall calculations and inputs to variables
        if (txtwesthheight.Text == "")
        {
            txtwesthheight.Text = ("0");
        }

        if (txtwestlength.Text == "")
        {
            txtwestlength.Text = ("0");
        }

        decimal height4 = decimal.Parse(txtwesthheight.Text);
        decimal length4 = decimal.Parse(txtwestlength.Text);
        decimal area4 = height4 * length4;
        lblwestharea.Text = area4.ToString("n");

        // window frame calculations and inputs to variables
        if (txtwinheight.Text == "")
        {
            txtwinheight.Text = ("0");
        }

        if (txtwinlength.Text == "")
        {
            txtwinlength.Text = ("0");
        }

        decimal height5 = decimal.Parse(txtwinheight.Text);
        decimal length5 = decimal.Parse(txtwinlength.Text);
        decimal area5 = height5 * length5;
        lblwinharea.Text = area5.ToString("n");

        // culculation to work out total area - window size. this is borken in to two aprts:
        // area 1 + area 2 + area 3 + area 5 then take away area 5 which is the window.
        decimal areatotal = (area1 + area2 + area3 + area4) - area5;

        lbltotalarea.Text = areatotal.ToString("n");

        // culculations for total height and length for output in invoice.
        decimal Heightt = (height1 + height2 + height3 + height4) - height5;
        decimal Legntht = (length1 + length2 + length3 + length4) - length5;
        Height2.Text = Heightt.ToString("n");
        Legnth.Text = Legntht.ToString("n");

        // variables for inputs taken on qucilty options and undercoat option.
        if (txtunder.Text == "")
        {
            txtunder.Text = ("0");
        }
        if (txtprice.Text == "")
        {
            txtprice.Text = ("0");
        }

        decimal price = decimal.Parse(txtprice.Text);
        decimal undercoat = decimal.Parse(txtunder.Text);
        decimal roomcost = (Heightt * Legntht) * price * undercoat;
        lblcost.Text = roomcost.ToString("c");

        //culculation for vat ( room cost take 25% )
        decimal Vattotal = (25 % roomcost);
        lblvat.Text = Vattotal.ToString("c");

         //culculation for roomcost + vat
         Decimal vt = Vattotal + roomcost;
         lblbt.Text = vt.ToString("c");
    }

    // reset form button
    private void Totalcost_Click(object sender, EventArgs e)
    {
        txtwinlength.Text = "";
        txtnorthheight.Text = "";
        txtnorthlength.Text = "";
        txtwesthheight.Text = "";
        txtwestlength.Text = "";
        txtsouthheight.Text = "";
        txtsouthlength.Text = "";
        txteasthheight.Text = "";
        txteasthlength.Text = "";
        txtwinheight.Text = "";
        txtprice.Text = "";
        lblnortharea.Text = "";
        lblsoutharea.Text = "";
        lblwestharea.Text = "";
        lbleastarea.Text = "";
        lblwinharea.Text = "";
        lblcost.Text = "";
        lbltotalarea.Text = "";
        Height2.Text = "";
        Legnth.Text = "";
        invoice.Text = "";
    }

    // invoice number genrator
    private void button1_Click(object sender, EventArgs e)
    {
        Random slumpGenerator = new Random(); int tal;
        tal = slumpGenerator.Next();
        invoice.Text = tal.ToString("n");
    }

    // invoice OUTput
    private void label22_Click_2(object sender, EventArgs e)
    {
        Random slumpGenerator = new Random(); int tal;
        tal = slumpGenerator.Next();
        invoice.Text = tal.ToString("n");
    }

    //input vaildation only allowing numbers and decimals.
    private void txtnorthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtnorthlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtsouthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtsouthlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtprice_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwesthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwestlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txteasthheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txteasthlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwinheight_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtwinlength_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    private void txtunder_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
            MessageBox.Show("Please Enter A Valid Value");
        }
    }

    public int validation ()
    {
        int flag = 0;

        //North input valdation
        if (txtnorthheight.Text == "")
        {
            txtnorthheight.Focus();
            errorProvider1.SetError(txtnorthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtnorthlength.Text == "")
        {
            txtnorthlength.Focus();
            errorProvider1.SetError(txtnorthlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //South input valdation
        if (txtsouthheight.Text == "")
        {
            txtsouthheight.Focus();
            errorProvider1.SetError(txtsouthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtsouthlength.Text == "")
        {
            txtsouthlength.Focus();
            errorProvider1.SetError(txtsouthlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //West  input valdation
        if (txtwesthheight.Text == "")
        {
            txtwesthheight.Focus();
            errorProvider1.SetError(txtwesthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtwestlength.Text == "")
        {
            txtwestlength.Focus();
            errorProvider1.SetError(txtwestlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //East input valdation
        if (txteasthheight.Text == "")
        {
            txteasthheight.Focus();
            errorProvider1.SetError(txteasthheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txteasthlength.Text == "")
        {
            txteasthlength.Focus();
            errorProvider1.SetError(txteasthlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //Window input valdation
        if (txtwinheight.Text == "")
        {
            txtwinheight.Focus();
            errorProvider1.SetError(txtwinheight, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        if (txtwinlength.Text == "")
        {
            txtwinlength.Focus();
            errorProvider1.SetError(txtwinlength, MessageBox.Show("please Enter a vaild input between 0.9m and 1.5m.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        //quality input valdation
        if (txtprice.Text == "")
        {
            txtprice.Focus();
            errorProvider1.SetError(txtprice, MessageBox.Show("please Enter a vaild input of the above options ( You Must Enter 1 of the Options).", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }

        // undercoat valdation
        if (txtunder.Text == "")
        {
            txtunder.Focus();
            errorProvider1.SetError(txtunder, MessageBox.Show("Please enter the Undercoat input of 0.45, if you do not want undercoat enter 0.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
            flag = 1;
        }
        return flag;
    }

    private void txtnorthheight_Click(object sender, EventArgs e)
    {
        errorProvider1.Clear();
    }
    //end of valdation
}

Body:
The % symbol is the modulus operator in C#, which means it gives you the remainder after dividing the left side by the right side. In your code, it looks like you want to get 25% of the room cost, not the remainder of 25 divided by the room cost.

So, this line:

decimal Vattotal = (25 % roomcost);

Should be changed to:

decimal Vattotal = roomcost * .25;

The reason you're getting the exception is that roomcost is 0, and dividing by zero is an illegal operation.


问:
How to show opaque background on jQuery click event
In order to show an opaque background or animated gif while executing some method after an button click fails to show this. It only runs after all the code has been executed.

Can I do this in jQuery, i.e. on a click event render html changes before and after main code.

The long running method is adding 100-500 divs to the page that takes about 10 seconds to finish.

```
$('#button).click(function() {
    $('#curtain').css('visibility', 'visible');
    longRunningMethod();
    $('#curtain').css('visibility', 'hidden');
 });
```

The problem is that the #curtain div never shows, as the complete javascript has to be executed before rendering all the changes.

Style:

```

#curtain {
    position: fixed;
    _position: absolute;
    z-index: 99;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    _height: expression(document.body.offsetHeight + "px");
    background-color: #CCCCCC;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    visibility: hidden;
}

```

答:
You should never have long running methods in the UI thread of a webpage.  It will make the page appear to lock up and is very annoying for the user.

Instead you should use asynchronous callback.  The long running method I assume does some AJAX calls.  In which case it should accept a function as an argument (like the jquery "click", "ajax", etc.).  Then pass that function to the ajax method as the completion or success callback.

Then you can do:

```<code>$('#button).click(function() {
    $('#curtain').css('visibility', 'visible');
    longRunningMethod(function() {$('#curtain').css('visibility', 'hidden');});
 });
</code>```

Body:
In order to show an opaque background or animated gif while executing some method after an button click fails to show this. It only runs after all the code has been executed.

Can I do this in jQuery, i.e. on a click event render html changes before and after main code.

The long running method is adding 100-500 divs to the page that takes about 10 seconds to finish.

$('#button).click(function() {
    $('#curtain').css('visibility', 'visible');
    longRunningMethod();
    $('#curtain').css('visibility', 'hidden');
 });

The problem is that the #curtain div never shows, as the complete javascript has to be executed before rendering all the changes.

Style:

#curtain {
    position: fixed;
    _position: absolute;
    z-index: 99;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    _height: expression(document.body.offsetHeight + "px");
    background-color: #CCCCCC;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    visibility: hidden;
}

Body:
You should never have long running methods in the UI thread of a webpage.  It will make the page appear to lock up and is very annoying for the user.

Instead you should use asynchronous callback.  The long running method I assume does some AJAX calls.  In which case it should accept a function as an argument (like the jquery "click", "ajax", etc.).  Then pass that function to the ajax method as the completion or success callback.

Then you can do:

$('#button).click(function() {
    $('#curtain').css('visibility', 'visible');
    longRunningMethod(function() {$('#curtain').css('visibility', 'hidden');});
 });


问:
Google Cloud Shell HttpAccessTokenRefreshError: This can occur if a VM was created with no service account or scopes
I am trying to run a simple script from
https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/data_analysis/lab2/python/grepc.py
(this code is a Dataflow pipeline connecting to Google Storage)

It worked last week. But when I am running it now, I always get the same error:

```<code>> Traceback (most recent call last):
  File "grepc.py", line 50, in <module>
    run()
  File "grepc.py", line 44, in run
    | 'write' >> beam.io.WriteToText(output_prefix)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 391, in __init__
    skip_header_lines=skip_header_lines)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 89, in __init__
    validate=validate)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 105, in __init__
    self._validate()
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/options/value_provider.py", line 109, in _f
    return fnc(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 165, in _validate
    match_result = FileSystems.match([pattern], limits=[1])[0]
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filesystems.py", line 131, in match
    return filesystem.match(patterns, limits)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/gcsfilesystem.py", line 138, in match
    raise BeamIOError("Match operation failed", exceptions)
apache_beam.io.filesystem.BeamIOError: Match operation failed with exceptions {'gs://{MY_BUCKET}/javahelp/*.java': HttpAccessTokenRefreshError(u' This can occur if a VM was created with no service account or scopes.',)}
</code>```

I have no idea how to solve this. And a lot of Googling did not help neither.

答:
I'm assuming the {MYBUCKET} in the error message is not literal and was replaced by your bucket name.

If you're running this from a GCE VM instance, can you run this command and paste the output here?

gcloud compute instances describe {instance-name} --zone {instance-zone}

The above would tell you what service accounts and scopes your VM instance has. And also:

gcloud projects get-iam-policy {project-name}

This would tell you what service accounts your project has. Please wipe out the project number or any info that you deem sensitive.

Body:
I am trying to run a simple script from
https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/data_analysis/lab2/python/grepc.py
(this code is a Dataflow pipeline connecting to Google Storage)

It worked last week. But when I am running it now, I always get the same error:

> Traceback (most recent call last):
  File "grepc.py", line 50, in <module>
    run()
  File "grepc.py", line 44, in run
    | 'write' >> beam.io.WriteToText(output_prefix)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 391, in __init__
    skip_header_lines=skip_header_lines)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 89, in __init__
    validate=validate)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 105, in __init__
    self._validate()
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/options/value_provider.py", line 109, in _f
    return fnc(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 165, in _validate
    match_result = FileSystems.match([pattern], limits=[1])[0]
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filesystems.py", line 131, in match
    return filesystem.match(patterns, limits)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/gcsfilesystem.py", line 138, in match
    raise BeamIOError("Match operation failed", exceptions)
apache_beam.io.filesystem.BeamIOError: Match operation failed with exceptions {'gs://{MY_BUCKET}/javahelp/*.java': HttpAccessTokenRefreshError(u' This can occur if a VM was created with no service account or scopes.',)}

I have no idea how to solve this. And a lot of Googling did not help neither.


问:
Parse EOF token in CUP
I'm having trouble making my CUP parser parse the EOF token. I read in the documentation that using the %cup flag in my Jflex code implies that there is something present like this:

```<code>%eofval{
  return new java_cup.runtime.Symbol(<CUPSYM>.EOF);
%eofval}
%eofclose
</code>```

This is all good and well, but when I try the following first rule in my grammar (CUP file):

```<code>program                 ::=   program declaration EOF
                          | /* Empty */
                          ;
</code>```

I get the error message that EOF is not declared by CUP.

```<code>Error : java_cup.runtime.Symbol "EOF" has not been declared
</code>```

Allrighty, so I add the following to my CUP file:

```<code>terminal EOF;
</code>```

No, because then CUP tells me:

```<code>Fatal : JavaCUP Internal Error Detected: Duplicate terminal (EOF) created
enter code here
</code>```

However, without defining the terminal EOF, and I have a look in the sym.java class that Cup generates I do find:

```<code>  public static final int EOF = 0;
</code>```

So I'm pretty lost on how to fix this. The documentation for both is really vague on the issue.

Edit:
The main reason I want to parse the EOF token is because I want to print out my symbol table in the end and other stuff for debugging purposes.

答: Make sure you didn´t forgot a ";" in any of your grammar productions corresponding to your "file.cup".</p>

Title: Parse EOF token in CUP

Body:
I'm having trouble making my CUP parser parse the EOF token. I read in the documentation that using the %cup flag in my Jflex code implies that there is something present like this:

%eofval{
  return new java_cup.runtime.Symbol(<CUPSYM>.EOF);
%eofval}
%eofclose

This is all good and well, but when I try the following first rule in my grammar (CUP file):

program                 ::=   program declaration EOF
                          | /* Empty */
                          ;

I get the error message that EOF is not declared by CUP.

Error : java_cup.runtime.Symbol "EOF" has not been declared

Allrighty, so I add the following to my CUP file:

terminal EOF;

No, because then CUP tells me:

Fatal : JavaCUP Internal Error Detected: Duplicate terminal (EOF) created
enter code here

However, without defining the terminal EOF, and I have a look in the sym.java class that Cup generates I do find:

  public static final int EOF = 0;

So I'm pretty lost on how to fix this. The documentation for both is really vague on the issue.

Edit:
The main reason I want to parse the EOF token is because I want to print out my symbol table in the end and other stuff for debugging purposes.