问:
Piping in c w/h terminal command: ./process arg | ./process arg
I have 2 files, one that generates random integers with two arguments, number of integers and the seed. The other file searches for a value in an array.

What I want to do is for the first file to give its randomly generated numbers as an array input for the second file.

like so in terminal.

./random_no 100 50 | ./find 42 -

I know this is meant to pipe the input from random_no into find.

the problem is I don't know how to receive or manipulate that input from the find file.

if it doesn't make sense or you want to see code as an example please tell me. Thanks :)

答:
You should clarify you question.
Which operating system are we dealing with? AIX, Linux?
Also it helps if you clarified what is it that you are trying to achieve as there may be better ways than what you are trying to do.

Pipe uses plain text via the stdout and stdin .... you are not working with objects, like an array.

random_no need to write to stdout and find would need to read from stdin.

but really you could use many standard command line utilities to achieve different tasks and should not need to write a C application.

for example to "find" 42 from the output of random_no

./random_no 100 50 | grep 42

But what does that achieve exactly?


来源: stackexchange

问:
There's an issue with Input in my Python code
so I'm a beginner in python and I was trying to get an input function to work. It looks to me like Python isn't taking the data I give it, like it's not reading user input correctly. here is my code:

```<code>var = input
    input("press ENTER to choose an app")
    if var==1:
        clock()
    elif var==2:
        oshelp()
    elif var==3:
        ebooks()
    elif var==4:
        what_is_new()
    else:
        print("Application Not Found.")
</code>```

right now, the IDLE just prints "Application Not Found" even when i type a valid number and I'm not sure why. can anyone help me with this? (please include examples). Thanks!

答:
The python input returns a string and you are comparing ints. If you would like to compare ints, then:

```<code>inputInt = int(input("please ENTER"))
</code>```

or you could use eval

```<code>inputInt = eval(input("please ENTER"))
</code>```

be careful with eval as it can cause problems, but it will handle just numbers and floats for you.

ContentLicense: CC BY-SA 3.0

Body:
so I'm a beginner in python and I was trying to get an input function to work. It looks to me like Python isn't taking the data I give it, like it's not reading user input correctly. here is my code:

var = input
    input("press ENTER to choose an app")
    if var==1:
        clock()
    elif var==2:
        oshelp()
    elif var==3:
        ebooks()
    elif var==4:
        what_is_new()
    else:
        print("Application Not Found.")

right now, the IDLE just prints "Application Not Found" even when i type a valid number and I'm not sure why. can anyone help me with this? (please include examples). Thanks!

Body:
The python input returns a string and you are comparing ints. If you would like to compare ints, then:

inputInt = int(input("please ENTER"))

or you could use eval

inputInt = eval(input("please ENTER"))

be careful with eval as it can cause problems, but it will handle just numbers and floats for you.


问:
Reject String If Contains Any Non-Alpha Numeric Character
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

```<code>Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^
</code>```

Here is my applicable code:

```<code>while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}
</code>```

答:
Well since no one posted REGEX one, here you go:</p>

```<code>package com.company;

public class Main {

    public static void main(String[] args) {

       String x = "ABCDEF123456";
       String y = "ABC$DEF123456";

       isValid(x);
       isValid(y);

    }

    public static void isValid(String s){

        if (s.matches("[A-Za-z0-9]*"))
            System.out.println("String doesn't contain non alphanumeric characters !");
        else
            System.out.println("Invalid characters in string !");
    }
}
</code>```

Body:
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^

Here is my applicable code:

while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}

Body:
Well since no one posted REGEX one, here you go:

package com.company;

public class Main {

    public static void main(String[] args) {

       String x = "ABCDEF123456";
       String y = "ABC$DEF123456";

       isValid(x);
       isValid(y);

    }

    public static void isValid(String s){

        if (s.matches("[A-Za-z0-9]*"))
            System.out.println("String doesn't contain non alphanumeric characters !");
        else
            System.out.println("Invalid characters in string !");
    }
}


答: The input will be a string and not ints. You can change your conditions from checking var == 1 to var == "1" etc. Or you can create an int from the input, using int(input()). However beware of the case where the input is not convertible to an int in that case an exception will be thrown.

Title: There's an issue with Input in my Python code


问:
AWS API Gateway MTLS client auth
Everytime I searched for Mutual Auth over SSL for AWS API Gateway I can only find MTLS between AWS API Gateway and Backend Services. But I'm looking to secure my AWS API Gateway endpoints itself with MTLS (client auth).

For instance, I have a backed service QueryCustomer which I have proxied through AWS API Gateway. Now I can put an SSL Cert on API Gateway but it's usual 1-way SSL. What I want to achieve is to have an MTLS with client auth where the consumer of APIs from AWS API Gateway first have to exchange their public certificates which we configure on the AWS truststores and AWS public certificates will be stored on API consumer end as well.

Now during the handshake as with other API Gateways and application servers should there be a property which says something like this AWS API Gateway endpoint 'requires client auth' so that only if API consumer's public cert is in API Gateway truststore should be authenticated to access the endpoint, otherwise just throw normal SSL handshake error.

Can someone advise if this is achievable on AWS API Gateway?

答: This is not currently available from API Gateway, but we have had requests from multiple customers for this feature. Unfortunately, I can't comment on ETA or availability. </p>

Title: AWS API Gateway MTLS client auth


问:
CSS not overiding Bootstrap
Below is a bootstrap that I found and implemented in my coding. Im trying to generate the hover effect from white to green. However it is not letting me do so.
My sass file is not overriding the bootstrap. Can someone help? Thanks.</p>

```<code> <div class="col-sm-3 sidebar">
       <ul class="nav nav-pills nav-stacked">
           <li  id="activeRow"class="active"><a href="#">Dashboard</a></li>
           <li><a href="#">Users</a></li>
           <li><a href="#">Suppliers</a></li>
           <li><a href="#">Online Course</a></li>
       </ul>
 </div>

 #activeRow
      background-color:green
</code>```

答:
It's all about specificity, also as mentioned in the comments your SASS files need to be loaded after the bootstrap files so they are parsed last. They're called cascading stylesheets for a reason :)

Read up on specificity here, it's a fundamental CSS concept

Try adding a unique class/id to one of your parent elements (if needbe) but just this should be specific enough:

```<code>.sidebar .nav #activeRow:hover
</code>```

if not then add that unique id/class

```<code>#awesome.sidebar .nav #activeRow:hover
</code>```

If nothing works, you're in a rush etc. use:

```<code>background-color: green !important
</code>```

This isn't great practice though, you can end up digging yourself a hole. It's better to work out what's got greatest specificity and write more specific code.

Better yet if you're comfortable with SASS, download the bootstrap libraries SASS files and update the bootstrap core, this is quite an advanced option though.

I assume you're also using :hover?

If you're just styling nav li{ color: white} and then #activeRow { color: green} that wont work. You need to use #activeRow:hover

To be view parsed CSS in your inspector, right click the page, click inspect, make sure you're on the 'Elements' tab then you'll see this:

Title: CSS not overiding Bootstrap

Body:
Below is a bootstrap that I found and implemented in my coding. Im trying to generate the hover effect from white to green. However it is not letting me do so.
My sass file is not overriding the bootstrap. Can someone help? Thanks.

Dashboard

Users

Suppliers

Online Course

 #activeRow
      background-color:green

Body:
It's all about specificity, also as mentioned in the comments your SASS files need to be loaded after the bootstrap files so they are parsed last. They're called cascading stylesheets for a reason :)

Read up on specificity here, it's a fundamental CSS concept

Try adding a unique class/id to one of your parent elements (if needbe) but just this should be specific enough:

.sidebar .nav #activeRow:hover

if not then add that unique id/class

#awesome.sidebar .nav #activeRow:hover

If nothing works, you're in a rush etc. use:

background-color: green !important

This isn't great practice though, you can end up digging yourself a hole. It's better to work out what's got greatest specificity and write more specific code.

Better yet if you're comfortable with SASS, download the bootstrap libraries SASS files and update the bootstrap core, this is quite an advanced option though.

I assume you're also using :hover?

If you're just styling nav li{ color: white} and then #activeRow { color: green} that wont work. You need to use #activeRow:hover

To be view parsed CSS in your inspector, right click the page, click inspect, make sure you're on the 'Elements' tab then you'll see this:


问:
How to design an ASP.NET MVC site for caching with Velocity?
I'm coming from the LAMP world, where the "cache everything" mentality is prevalent.  Everything is put in memcache.

I'm starting a new project with ASP.NET MVC and SQL Server.  I'll probably go with LINQ to SQL or maybe Entity Framework.  Are there design decisions I need to make now for caching, or is it easy enough to start using Velocity if that becomes necessary?  Just to be clear, I'm talking about Microsoft's Velocity cache and not the Apache Velocity template engine.

I'm hoping that I can ignore caching for the moment, because learning C#, ASP.NET MVC, LINQ, IIS, SQL Server, and becoming proficient in VS is keeping my plate full.

答:
Stephen Walther has a great article on how to do this

ASP.NET MVC Tip #39 – Use the Velocity Distributed Cache

OwnerDisplayName: Bob

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ben Alpert

OwnerDisplayName: dswatik


问:
How to post UTF-8 text from MySQL to Twitter successfully
I have some text in UTF-8. I put it into a MySQL database, collation utf8_general_ci and then I've been auto-posting it to Twitter via Net::Twitter.

But when I post it, even though Twitter itself seems to be expecting UTF-8, going by the content-type in their input pages, I'm getting those artefacts you get when UTF-8 text is misinterpreted: é comes out as Ã© for instance.

So ... at what point is this going wrong? How can I ensure it makes the trip undamaged?

Set my script to treat all text as UTF-8 somehow?

Make sure I extract it from the database in UTF-8?

Tell Net::Twitter that it's posting in UTF-8?

答:
You probably need to enable the mysql_enable_utf8 attribute when opening your db connection:

```<code>my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost",
                       "user", "password",
                       { mysql_enable_utf8 => 1});
</code>```

This will tell Perl that strings retrieved from the database are UTF-8 encoded.

Body:
You probably need to enable the mysql_enable_utf8 attribute when opening your db connection:

my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost",
                       "user", "password",
                       { mysql_enable_utf8 => 1});

This will tell Perl that strings retrieved from the database are UTF-8 encoded.


问:
jQuery Validation - error placement
I'm trying to use 'errorPlacement' from jQuery Validation DOCS:

```<code>$("#myform").validate({
  errorPlacement: function(error, element) {
     error.appendTo( element.parent("td").next("td") );
   },
   debug:true
 })
</code>```

I want to place error before not valid input, but this does not work:

```<code>$("#myform").validate({
      errorPlacement: function(error, element) {
         error.appendTo( element.parent("form").prev("input") );
       },
       debug:true
     })
</code>```

LIVE DEMO

Any help much appreciated!

答:
I recommend to use a html template to specify the position and styling like so:

```<code><input name="patient_gender" required>
<label for="patient_gender" class="validation_error_message help-block"></label>
</code>```

and overwrite function for error placement

```<code>$.validator.setDefaults({
    errorPlacement: function(error, element) {
        var name = element.attr('name');
        var errorSelector = '.validation_error_message[for="' + name + '"]';
        var $element = $(errorSelector);
        if ($element.length) {
            $(errorSelector).html(error.html());
        } else {
            error.insertAfter(element);
        }
    }
});
</code>```

Title: jQuery Validation - error placement

Body:
I'm trying to use 'errorPlacement' from jQuery Validation DOCS:

$("#myform").validate({
  errorPlacement: function(error, element) {
     error.appendTo( element.parent("td").next("td") );
   },
   debug:true
 })

I want to place error before not valid input, but this does not work:

$("#myform").validate({
      errorPlacement: function(error, element) {
         error.appendTo( element.parent("form").prev("input") );
       },
       debug:true
     })

LIVE DEMO

Any help much appreciated!

Body:
I recommend to use a html template to specify the position and styling like so:

<input name="patient_gender" required>
<label for="patient_gender" class="validation_error_message help-block"></label>

and overwrite function for error placement

$.validator.setDefaults({
    errorPlacement: function(error, element) {
        var name = element.attr('name');
        var errorSelector = '.validation_error_message[for="' + name + '"]';
        var $element = $(errorSelector);
        if ($element.length) {
            $(errorSelector).html(error.html());
        } else {
            error.insertAfter(element);
        }
    }
});


问:
Check if an instance is either an Array or a Collection in Java
I want to create a method in Java that receives either an array or a collection, it does not matter, because all i do is iterate it. I don't want to create a list from the array because it would impact on the performance of the algorithm and i am really tired of always creating an overloading method for every method which accepts a List. Is there a convenient parent class for both, like "Iterable", or something? </p>

答:
If performance is truly so critical that you cannot afford to wrap an array in an ArrayList, then you need to write separate algorithms for arrays and collections. It's really that simple.

The benefits of polymorphism rest on the assumption that you can afford to trade off a few microseconds to get shorter and more readable code. If you can't afford that, you can't have the convenience.


答:
input returns a string, but you're checking it against ints. One way to do this would be to check the input, as explained here. You could also just compare it to strings:

```<code>if var == '1':
</code>```

Or convert the input to an int directly:

```<code>var = int(input(...))
</code>```

Be careful with the last one, as it will fail if the user does not input a valid int.

Body:
input returns a string, but you're checking it against ints. One way to do this would be to check the input, as explained here. You could also just compare it to strings:

if var == '1':

Or convert the input to an int directly:

var = int(input(...))

Be careful with the last one, as it will fail if the user does not input a valid int.


问:
PHP Form sends Email even if Email and Name are invalid
Hi everyone and thanks for your time!

Although it's the first time that I try PHP, I've been making a PHP Form and so far I've been able to make it validate the fields, and also that the form doesn't send anything if the fields are empty.
Now... The fields "Name" and "Email" have validation filters...
"Name" doesn't allow more than "letters and white spaces" and "Email" doesn't allow an "invalid Email format".

Example:
Name: Rob3rt... it has a number
Email: anything... isn't an Email address
Subject and Message have no validation filters...

The problem is, that if I fill up all fields, the form sends the Email, even if the information written on "Name" and "Email" doesn't agree with their validation filters...

Q: How can I hold the form from sending an Email, until all fields have the correct information inside?

Here's the code:

// This is the validation code //

<?php

// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subjectErr = "";
$name = $email = $comment = $subject = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (empty($_POST["name"])) {
    $nameErr = "
Name is required
";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "
Only letters and white space allowed
";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "
Email is required
";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "
Invalid email format
";
    }
  }

  if (empty($_POST["comment"])) {
    $commentErr = "
Message is required
";
  } else {
    $comment = test_input($_POST["comment"]);
  }

if (empty($_POST["subject"])) {
    $subjectErr = "
Subject is required
";
  } else {
    $subject = test_input($_POST["subject"]);
  }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>

<form>
Form comes here
</form>

// This is the sending code... I think the problem is here... //

<?php

if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {

$to = "myemail@whatever.com";
$email = "From: " . $email . "\r\n";
$subject = "" . $subject . "\r\n";
$comment = "" . $comment . "\r\n";

mail($to,$subject,$comment,$email);
   echo "good";
   }
   else {
   "bad";
   }

?>```

答:
It is not working, because you never check if an error occurred, you are only checking if the fields are not empty before you send the mail.

The simplest way to fix it is replacing

```<code>if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
</code>```

with

```<code>if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nameErr === '' && $emailErr === '' && $commentErr === '' && $subjectErr === '') {
</code>```

There is no no need to check for empty fields again, you have already done it before, so you just need to check if you are POSTing the form and if all errors are empty.

Some advice on how to generally improve your code:

1) Do not handle the HTTP POST in two positions (once above the form and once below). Merge it together in one PHP code block.

2) At least make sure that the user can't re-submit a successful form by reloading the site. After a successful submit, redirect the page. Something like this:

```<code>mail($to,$subject,$comment,$email);
header('Location:' . $_SERVER['REQUEST_URI'] . '?status=ok');
exit();
</code>```

3) separate your HTML from your PHP or you will end up with a huge file which gets hard to maintain. Put your HTML form in a separate file and include it.

Although imho the nicest solution for a form is to sanitize in in JavaScript, submit it via AJAX (with angular, react, jQuery, whatever), handle it (and sanitize the data again) in PHP, send a 4xx HTTP header on error and return the error messages as a JSON object, which you then use in JavaScript.

Body:
It is not working, because you never check if an error occurred, you are only checking if the fields are not empty before you send the mail.

The simplest way to fix it is replacing

if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {

with

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nameErr === '' && $emailErr === '' && $commentErr === '' && $subjectErr === '') {

There is no no need to check for empty fields again, you have already done it before, so you just need to check if you are POSTing the form and if all errors are empty.

Some advice on how to generally improve your code:

1) Do not handle the HTTP POST in two positions (once above the form and once below). Merge it together in one PHP code block.

2) At least make sure that the user can't re-submit a successful form by reloading the site. After a successful submit, redirect the page. Something like this:

mail($to,$subject,$comment,$email);
header('Location:' . $_SERVER['REQUEST_URI'] . '?status=ok');
exit();

3) separate your HTML from your PHP or you will end up with a huge file which gets hard to maintain. Put your HTML form in a separate file and include it.

Although imho the nicest solution for a form is to sanitize in in JavaScript, submit it via AJAX (with angular, react, jQuery, whatever), handle it (and sanitize the data again) in PHP, send a 4xx HTTP header on error and return the error messages as a JSON object, which you then use in JavaScript.


问:
Window form execute a batch file
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

```<code> Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }
</code>```

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

```<code>public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }
</code>```

My main question is about process method,  can i execute it like that?  thanks

答: Beside Eric's answer, I would suggest to use NumericUpDown control instead.</p>

Title: Window form execute a batch file

Body:
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

 Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }

My main question is about process method,  can i execute it like that?  thanks


问:
Robot Framework Ride is not working on mac
I am trying to run command on terminal on Mac ride.py and getting an

error as segmentation fault 11

The Logs of the error are as mentioned below

Process:               Python [2126]
Path :/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
```

<p>Timestamp:</p>

<pre class="lang-none prettyprint-override"><code>Identifier:            org.python.python
Version:               2.7.9 (2.7.9)
Code Type:             X86-64 (Native)
Parent Process:        bash [2121]
Responsible:           Terminal [2103]
User ID:               501

Date/Time:             2015-08-13 10:20:19.195 +0530
OS Version:            Mac OS X 10.10.2 (14C109)
Report Version:        11
Anonymous UUID:        BB484FE8-9B7B-6FB8-4160-F47065883AE5
</code>```

答:
This solution worked like a charm for me:

I went to this directory: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/robotframework_ride-2.0a1-py2.7.egg/robotide

and then ran arch -i386 python __init__.py,

It launched RIDE editor and attaching the screenshot.

Body:
I am trying to run command on terminal on Mac ride.py and getting an

error as segmentation fault 11

The Logs of the error are as mentioned below

Process:               Python [2126]
Path :/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python

Timestamp:

Identifier:            org.python.python
Version:               2.7.9 (2.7.9)
Code Type:             X86-64 (Native)
Parent Process:        bash [2121]
Responsible:           Terminal [2103]
User ID:               501

Date/Time:             2015-08-13 10:20:19.195 +0530
OS Version:            Mac OS X 10.10.2 (14C109)
Report Version:        11
Anonymous UUID:        BB484FE8-9B7B-6FB8-4160-F47065883AE5


问:
How to use icontains in a key value of a DictField in Django queryset?
Given the following model:

```<code>class Team(models.Model):
    name = models.CharField(max_length=50)
    others = DictField()
</code>```

And the following code:

```<code>bahia = Team()
bahia.name = "E.C. Bahia"
bahia.others = {"title": "Ninguém nos Vence em Vibração!!!"}
bahia.save()

vicetoria = Team()
vicetoria.name = "E.C. Vicetoria"
vicetoria.others = {"title": "Vice de tudo!"}
vicetoria.save()
</code>```

I want to find the object that have the word vence, (case insensitive) contained in title value of the field others.

I tried something like:

```<code>teams = Team.objects.filter(others__title__icontains="vence")
</code>```

that gives me the following error:

```<code>FieldError: Join on field 'others' not permitted. Did you misspell 'title' for the lookup type?
</code>```

I also already tried:

```<code>teams = Team.objects.filter(others__icontains={"title":"vence"})
</code>```

that returns None and I know there is at least one collection as result.

SOLUTION:

```<code>teams = Team.objects.raw_query({"others.title": {"$regex" : "vence", "$options": "i"}})
</code>```

The i option makes the search insensitive.

答:
I believe (correct me if I'm wrong) that djangotoolbox DictField doesn't support icontain.

To filter the Dict Field you need to do something like:

Team.objects.raw_query({'title': { $regex : /vence/i } })

Check out this answer: How do I filter based on dict contents in a DictField on a model using the Django-MongoDB Engine?

This answer shows how to do case insensitive mongodb queries: How do I make case-insensitive queries on Mongodb?

Body:
Given the following model:

class Team(models.Model):
    name = models.CharField(max_length=50)
    others = DictField()

And the following code:

bahia = Team()
bahia.name = "E.C. Bahia"
bahia.others = {"title": "Ninguém nos Vence em Vibração!!!"}
bahia.save()

vicetoria = Team()
vicetoria.name = "E.C. Vicetoria"
vicetoria.others = {"title": "Vice de tudo!"}
vicetoria.save()

I want to find the object that have the word vence, (case insensitive) contained in title value of the field others.

I tried something like:

teams = Team.objects.filter(others__title__icontains="vence")

that gives me the following error:

FieldError: Join on field 'others' not permitted. Did you misspell 'title' for the lookup type?

I also already tried:

teams = Team.objects.filter(others__icontains={"title":"vence"})

that returns None and I know there is at least one collection as result.

SOLUTION:

teams = Team.objects.raw_query({"others.title": {"$regex" : "vence", "$options": "i"}})

The i option makes the search insensitive.


问:
Detecting when a SerialPort gets disconnected
I have an open SerialPort and receive data through the DataReceived event.

Is there any way to detect if the SerialPort gets disconnected?

I tried the ErrorReceived and PinChanged events but no luck.

In addition to that, SerialPort.IsOpen returns true when physically disconnected.

答:
Use the C# SerialPort.CDHolding flag.

So save the bool to a lastCDHolding flag,  before your open and read loop.

After you read test SerialPort.CDHolding != lastCDHolding to trap changes or just test SerialPort.CDHoldin==false to detect the port was closed.


问:
C# new in method declaration
```<code>public new int AdjustedBaseValue
</code>```

<p>What does the new here mean or do? </p>

答: In this case, new is a modifier that hides an inherited member from the base class. See the documentation.

Title: C# new in method declaration

Body:
public new int AdjustedBaseValue

What does the new here mean or do?

ContentLicense: CC BY-SA 4.0


答:
SASS rule has to be:

```<code>#activeRow>a:focus,#activeRow>a:hover
   background-color: green
</code>```

Example: https://codepen.io/anon/pen/MOxZaE

Title: CSS not overiding Bootstrap

Body:
SASS rule has to be:

#activeRow>a:focus,#activeRow>a:hover
   background-color: green

Example: https://codepen.io/anon/pen/MOxZaE


问:
Printing items from a list in Python
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

```<code>l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')
</code>```

答:
This will do:</p>

```<code>for column in range(2):
    print("   ".join([str(row[column]) for row in l]))
</code>```

```<code>>>> l = [[2,3],[5,6],[4,8]]
>>> for column in range(2):
...     print("   ".join([str(row[column]) for row in l]))
...
2   5   4
3   6   8
</code>```

Title: Printing items from a list in Python

Body:
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')

Body:
This will do:

for column in range(2):
    print("   ".join([str(row[column]) for row in l]))

>>> l = [[2,3],[5,6],[4,8]]
>>> for column in range(2):
...     print("   ".join([str(row[column]) for row in l]))
...
2   5   4
3   6   8


问:
get all tuples with maximum second value
How to fix the number of occurrence in a list of tuples and return an item with max value.

```<code>        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]
</code>```

How do you do this without doing anything to complex.

答:
```<code>from itertools import groupby
groups = groupby(sorted(given, key = lambda x: x[0]), key = lambda x: x[0])
print [max(g) for k,g in groups]
</code>```

<p>results in </p>

```<code>[('a', 3), ('b', 3), ('c', 5)]
</code>```

Body:
How to fix the number of occurrence in a list of tuples and return an item with max value.

        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]

How do you do this without doing anything to complex.

Body:
from itertools import groupby
groups = groupby(sorted(given, key = lambda x: x[0]), key = lambda x: x[0])
print [max(g) for k,g in groups]

results in

[('a', 3), ('b', 3), ('c', 5)]


问:
Python: open either zipped or unzipped file using "with"
I'm looking for a solution to open a file using "with". Hoever, I would like to check if the file is either gzipped or not and then either use gzip.open or just open something like:

```<code>if f.endswith(".gz"):
    with gzip.open() as f:
else:
    with open() as f:
for line in f:
</code>```

Any ideas?

答:
One way you could do this is by making your own context manager that does it for you.

```<code>from contextlib import contextmanager

@contextmanager
def open_file(filename):
    if filename.endswith(".gz"):
        with gzip.open(filename) as f:
            yield f
    else:
        with open(filename) as f:
            yield f
</code>```

Then you can just open files using this instead.

```<code>with open_file("filename") as f:
    # f will be either the result of `gzip.open` or `open`, depending on its filename.
    for line in f:
        pass
</code>```

This gives you the ability to keep the advantages of using a with clause, whilst giving you the flexibility to choose which function to call.

Body:
I'm looking for a solution to open a file using "with". Hoever, I would like to check if the file is either gzipped or not and then either use gzip.open or just open something like:

if f.endswith(".gz"):
    with gzip.open() as f:
else:
    with open() as f:
for line in f:

Any ideas?

Body:
One way you could do this is by making your own context manager that does it for you.

from contextlib import contextmanager

@contextmanager
def open_file(filename):
    if filename.endswith(".gz"):
        with gzip.open(filename) as f:
            yield f
    else:
        with open(filename) as f:
            yield f

Then you can just open files using this instead.

with open_file("filename") as f:
    # f will be either the result of `gzip.open` or `open`, depending on its filename.
    for line in f:
        pass

This gives you the ability to keep the advantages of using a with clause, whilst giving you the flexibility to choose which function to call.


问:
How to use boost::smart_ptr in polymorphism?
Boost smart pointers can be used with polymorphism, but how do you cast the subclass back to the pointer?

```<code>using namespace boost;
// ...
shared_ptr<SuperClass> a_ptr(new SubClass);
// ...
shared_ptr<SubClass> b_ptr = (shared_ptr<SubClass>)a_ptr; // Doesn't compile
</code>```

The last line doesn't compile and gives error C2440: 'type cast' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'

答:
You need to use static_pointer_cast:

```<code>struct B { virtual ~B() { } };
struct D : B { };

shared_ptr<B> bp(new D);
shared_ptr<D> dp(static_pointer_cast<D>(b));
</code>```

(There are also dynamic_pointer_cast and const_pointer_cast for performing dynamic and const casts respectively.)

Body:
Boost smart pointers can be used with polymorphism, but how do you cast the subclass back to the pointer?

using namespace boost;
// ...
shared_ptr<SuperClass> a_ptr(new SubClass);
// ...
shared_ptr<SubClass> b_ptr = (shared_ptr<SubClass>)a_ptr; // Doesn't compile

The last line doesn't compile and gives error C2440: 'type cast' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'

Body:
You need to use static_pointer_cast:

struct B { virtual ~B() { } };
struct D : B { };

shared_ptr<B> bp(new D);
shared_ptr<D> dp(static_pointer_cast<D>(b));

(There are also dynamic_pointer_cast and const_pointer_cast for performing dynamic and const casts respectively.)


问:
UIPageViewController Gesture recognizers
I have a UIPageViewController load with my Viewcontroller.

The view controllers have buttons which are overridden by the PageViewControllers gesture recognizers.

For example I have a button on the right side of the viewcontroller and when you press the button, the PageViewController takes over and changes the page.

How can I make the button receive the touch and cancel the gesture recognizer in the PageViewController?

I think the PageViewController makes my ViewController a subview of its view.

I know I could turn off all of the Gestures, but this isn't the effect I'm looking for.

I would prefer not to subclass the PageViewController as apple says this class is not meant to be subclassed.

答:
I ended up here while looking for a simple, catch-all way to respond to taps on my child view controllers within a UIPageViewController. The core of my solution (Swift 4, Xcode 9) wound up being as simple as this, in my RootViewController.swift (same structure as Xcode's "Page-Based App" template):

override func viewDidLoad() {
    super.viewDidLoad()

    ...

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(pageTapped(sender:)))
    self.pageViewController?.view.subviews[0].addGestureRecognizer(tapGesture)
}

...

@objc func pageTapped(sender: UITapGestureRecognizer) {
    print("pageTapped")
}
```

(I also made use of this answer to let me keep track of which page was actually tapped, ie. the current one.)

Body:
I ended up here while looking for a simple, catch-all way to respond to taps on my child view controllers within a UIPageViewController. The core of my solution (Swift 4, Xcode 9) wound up being as simple as this, in my RootViewController.swift (same structure as Xcode's "Page-Based App" template):

override func viewDidLoad() {
    super.viewDidLoad()

    ...

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(pageTapped(sender:)))
    self.pageViewController?.view.subviews[0].addGestureRecognizer(tapGesture)
}

...

@objc func pageTapped(sender: UITapGestureRecognizer) {
    print("pageTapped")
}

(I also made use of this answer to let me keep track of which page was actually tapped, ie. the current one.)


问:
Python TypeError: integer argument expected, got float
Hello I am trying to run code that involves drawing a box but keeps returning the error

```<code>TypeError: integer argument expected, got float
</code>```

The first issue in the code that appeared was

```<code>def draw_box(Image, x, y, w, h):
    cv2.line(Image, (x, y), (x + (w/5) ,y), WHITE, 2)
    cv2.line(Image, (x+((w/5)*4), y), (x+w, y), WHITE, 2)
    cv2.line(Image, (x, y), (x, y+(h/5)), WHITE, 2)
    cv2.line(Image, (x+w, y), (x+w, y+(h/5)), WHITE, 2)
    cv2.line(Image, (x, (y+(h/5*4))), (x, y+h), WHITE, 2)
    cv2.line(Image, (x, (y+h)), (x + (w/5) ,y+h), WHITE, 2)
    cv2.line(Image, (x+((w/5)*4), y+h), (x + w, y + h), WHITE, 2)
    cv2.line(Image, (x+w, (y+(h/5*4))), (x+w, y+h), WHITE, 2)
</code>```

Which I fixed by replacing the division signs with python floor division, though then the next area of box drawing which returns the same Type Error

```<code>cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), (0,0,0), -2)
</code>```

I've tried putting cv2.rectangle(int(Image, (Name_..  only to receive back

```<code>TypeError: int() takes at most 2 arguments (5 given)
</code>```

Any ideas on how to fix this?

答:
As with the original error, the problem in your rectangle() call is that the arguments which specify pixel coordinates are not integers. Even though there's no division, it's not clear whether some of your original variables are floats or if multiplying just converted some of them to floats and not integers...either way, if you just cast each coordinate as an integer, you should be good to go. For e.g.:

```<code>cv2.rectangle(Image,
              (int(Name_X_pos-10), int(Name_y_pos-25)),
              (int(Name_X_pos +10 + (len(NAME) * 7)), int(Name_y_pos-1)),
              (0,0,0), -2)
</code>```

Body:
Hello I am trying to run code that involves drawing a box but keeps returning the error

TypeError: integer argument expected, got float

The first issue in the code that appeared was

def draw_box(Image, x, y, w, h):
    cv2.line(Image, (x, y), (x + (w/5) ,y), WHITE, 2)
    cv2.line(Image, (x+((w/5)*4), y), (x+w, y), WHITE, 2)
    cv2.line(Image, (x, y), (x, y+(h/5)), WHITE, 2)
    cv2.line(Image, (x+w, y), (x+w, y+(h/5)), WHITE, 2)
    cv2.line(Image, (x, (y+(h/5*4))), (x, y+h), WHITE, 2)
    cv2.line(Image, (x, (y+h)), (x + (w/5) ,y+h), WHITE, 2)
    cv2.line(Image, (x+((w/5)*4), y+h), (x + w, y + h), WHITE, 2)
    cv2.line(Image, (x+w, (y+(h/5*4))), (x+w, y+h), WHITE, 2)

Which I fixed by replacing the division signs with python floor division, though then the next area of box drawing which returns the same Type Error

cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), (0,0,0), -2)

I've tried putting cv2.rectangle(int(Image, (Name_..  only to receive back

TypeError: int() takes at most 2 arguments (5 given)

Any ideas on how to fix this?

Body:
As with the original error, the problem in your rectangle() call is that the arguments which specify pixel coordinates are not integers. Even though there's no division, it's not clear whether some of your original variables are floats or if multiplying just converted some of them to floats and not integers...either way, if you just cast each coordinate as an integer, you should be good to go. For e.g.:

cv2.rectangle(Image,
              (int(Name_X_pos-10), int(Name_y_pos-25)),
              (int(Name_X_pos +10 + (len(NAME) * 7)), int(Name_y_pos-1)),
              (0,0,0), -2)


问:
Grep a string in Linux
I have a log file that records string like this:  (1512424528.554:0:1880:1880).   I need to grep out only the lines where the last value is over 1000 and print them.  Thoughts?</p>

答:
Grep is not the most pragmatic tool for this task. As @WilliamPursell adviced use awk or other tools for this problem.

Solutions:

Using grep: You can solve it but not perfectly by looking for at least 4 digits starting with a digit 1 to 9 ([1-9][0-9]{3,}) between the last colon (.*: matching everything until the last colon) and the end of the line ($) using perl-regexp (-P flag). This solution is not perfect since it gives you result for greater than or equal to 1000.

```<code>grep -P '.*:[1-9][0-9]{3,}$' your_file
</code>```

Using awk: You can simply compare the last field ($NF) to 1000 after setting the field delimiter with -F.

```<code>awk -F':' '$NF > 1000 { print $0 }' your_file
</code>```

Using perl: You can lookup for the last digits between the last colon and the end of the line and capture those digits (\d+) into $1 that is compared to 1000.

```<code>perl -ne 'print if (/.*:(\d+)$/ and  $1>1000)' your_file
</code>```

UPDATE

Based on the comments of @vaettchen I added solutions to take into account the parenthesis if they are part of the logged strings.

grep:

```<code>grep -P '.*:[1-9][0-9]{3,}\)$' your_file
</code>```

awk:

```<code>awk -F':' 'substr($NF, 0, length($NF)-1)*1 > 1000' your_file
</code>```

perl:

```<code>perl -ne 'print if (/.*:(\d+)\)$/ and  $1>1000)' your_file
</code>```

Title: Grep a string in Linux

Body:
Grep is not the most pragmatic tool for this task. As @WilliamPursell adviced use awk or other tools for this problem.

Solutions:

Using grep: You can solve it but not perfectly by looking for at least 4 digits starting with a digit 1 to 9 ([1-9][0-9]{3,}) between the last colon (.*: matching everything until the last colon) and the end of the line ($) using perl-regexp (-P flag). This solution is not perfect since it gives you result for greater than or equal to 1000.

grep -P '.*:[1-9][0-9]{3,}$' your_file

Using awk: You can simply compare the last field ($NF) to 1000 after setting the field delimiter with -F.

awk -F':' '$NF > 1000 { print $0 }' your_file

Using perl: You can lookup for the last digits between the last colon and the end of the line and capture those digits (\d+) into $1 that is compared to 1000.

perl -ne 'print if (/.*:(\d+)$/ and  $1>1000)' your_file

UPDATE

Based on the comments of @vaettchen I added solutions to take into account the parenthesis if they are part of the logged strings.

grep:

grep -P '.*:[1-9][0-9]{3,}\)$' your_file

awk:

awk -F':' 'substr($NF, 0, length($NF)-1)*1 > 1000' your_file

perl:

perl -ne 'print if (/.*:(\d+)\)$/ and  $1>1000)' your_file


答:
U already made it just add a line break outside both loops and your good to go:

```<code>l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')

print('\n') #take note this needs to be outside both loops

for obj in l:
    print(obj[1], end = '  ')
</code>```

However if you just want it to be on the next line immediately,

```<code>l = [[2,3],[5,6],[4,8]]
    for item in l:
        print(item[0], end = '  ')

print() #take note this needs to be outside both loops

for obj in l:
   print(obj[1], end = '  ')
</code>```

Title: Printing items from a list in Python

Body:
U already made it just add a line break outside both loops and your good to go:

l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')

print('\n') #take note this needs to be outside both loops

for obj in l:
    print(obj[1], end = '  ')

However if you just want it to be on the next line immediately,

l = [[2,3],[5,6],[4,8]]
    for item in l:
        print(item[0], end = '  ')

print() #take note this needs to be outside both loops

for obj in l:
   print(obj[1], end = '  ')


问:
How to detect page change in UIWebView and do something before it starts loading?
I need to do something on each page change, before that page starts loading/executing.

First, I tried using -webView:shouldStartLoadWithRequest: but that won't work, because it's also called for XHR requests and iframe requests.

Second, I tried using -webViewDidStartLoad: and comparing webView.request to it's previous value, to see if it changed. This doesn't work, because webView.request is updated only some time after the call.

Any more ideas?

答: Have you tried using KVO to observe UIWebView.request?


问:
How to set autolayout so image takes up full screen?
I have the image to cover the page but when you rotate the phone the image does not cover the full screen in landscape. What am I missing?</p>

```<code>func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)
    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
}
</code>```

答:
You could track that the device's orientation has changed.
So far your code does use the UIScreen.main.bounds of portrait mode.

Try using this tracking the change of orientation with a Notification like this:

in ViewDidLoad add:

```<code>    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
</code>```

Add rotated function:

```<code>func rotated() {
if UIDevice.current.orientation.isLandscape {
   // change frame of subview in here
} else {
   // change frame again in case you rotated back.
}
}
</code>```

be careful using this in terms of having the option of Portrait Upside Down etc.

Body:
I have the image to cover the page but when you rotate the phone the image does not cover the full screen in landscape. What am I missing?

func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)
    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
}

Body:
You could track that the device's orientation has changed.
So far your code does use the UIScreen.main.bounds of portrait mode.

Try using this tracking the change of orientation with a Notification like this:

in ViewDidLoad add:

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

Add rotated function:

func rotated() {
if UIDevice.current.orientation.isLandscape {
   // change frame of subview in here
} else {
   // change frame again in case you rotated back.
}
}

be careful using this in terms of having the option of Portrait Upside Down etc.


答:
Since it is an integer, to concatenate with strings ,use map!

```<code>>>> "   ".join(str(item[0]) for item in l)
'2   5   4'
>>> "   ".join(str(item[1]) for item in l)
'3   6   8'
</code>```

Or use zip!

zip - to put it in a simple way, it groups all elements of same index in sublist to a single list.

This function returns a list of tuples, where the i-th tuple contains
  the i-th element from each of the argument sequences or iterables. The
  returned list is truncated in length to the length of the shortest
  argument sequence. When there are multiple arguments which are all of
  the same length, zip() is similar to map() with an initial argument of
  None. With a single sequence argument, it returns a list of 1-tuples.
  With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed.
  This makes possible an idiom for clustering a data series into
  n-length groups using zip(*[iter(s)]*n).

```<code>>>> l
[[2, 3], [5, 6], [4, 8]]
>>> zip(*l)
[(2, 5, 4), (3, 6, 8)]
>>> for each in zip(*l):
...     "    ".join(map(str,each))
...
'2    5    4'
'3    6    8'
</code>```

Title: Printing items from a list in Python

Body:
Since it is an integer, to concatenate with strings ,use map!

>>> "   ".join(str(item[0]) for item in l)
'2   5   4'
>>> "   ".join(str(item[1]) for item in l)
'3   6   8'

Or use zip!

zip - to put it in a simple way, it groups all elements of same index in sublist to a single list.

This function returns a list of tuples, where the i-th tuple contains
  the i-th element from each of the argument sequences or iterables. The
  returned list is truncated in length to the length of the shortest
  argument sequence. When there are multiple arguments which are all of
  the same length, zip() is similar to map() with an initial argument of
  None. With a single sequence argument, it returns a list of 1-tuples.
  With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed.
  This makes possible an idiom for clustering a data series into
  n-length groups using zip(*[iter(s)]*n).

>>> l
[[2, 3], [5, 6], [4, 8]]
>>> zip(*l)
[(2, 5, 4), (3, 6, 8)]
>>> for each in zip(*l):
...     "    ".join(map(str,each))
...
'2    5    4'
'3    6    8'


问:
Node promise error propagation between classes
Im currently in the process of making my code object oriented and have a problem with propagating promise errors between class instances.

Page.js:

```<code>exports.Page = class {
  constructor(link, limiter){
    this.link = link;
    //limiter is a instance of bottleneck, use it for rate limiting
    this.limiter = limiter;
  }

  setResults(){
    return new Request(this.link, this.limiter).makeRequest()
    .catch(err => {
      //i dont get here
      console.log(err);
    })
  }
}
</code>```

(is called and initiated from another class)

Request.js:

```<code>exports.Request = class {
  constructor(options, limiter){
    this.options = options;
    this.limiter = limiter;
  }

  makeRequest(){
    return this.limiter.schedule(this.request, this.options)
    .catch(err => {
      //i get here
      throw err;
    });
  }

  request(url){
    return rp("https://httpstat.us/500")
    .catch(err => {
      //i get here
      throw err;
    })
  }
}
</code>```

So my problem is, that the error wont be propagated back to the page.js but instead prints an unhandled rejection error in the console. I've tried running this without limiter.schedule but it doesnt make a difference. Would be great to get some pointers, cant figure it out.

答: Throwing an error in a catch might not work correctly when the error is thrown inside an asynchronous function. Replacing throw err; with return Promise.reject(err); should work.

Body:
Im currently in the process of making my code object oriented and have a problem with propagating promise errors between class instances.

Page.js:

exports.Page = class {
  constructor(link, limiter){
    this.link = link;
    //limiter is a instance of bottleneck, use it for rate limiting
    this.limiter = limiter;
  }

  setResults(){
    return new Request(this.link, this.limiter).makeRequest()
    .catch(err => {
      //i dont get here
      console.log(err);
    })
  }
}

(is called and initiated from another class)

Request.js:

exports.Request = class {
  constructor(options, limiter){
    this.options = options;
    this.limiter = limiter;
  }

  makeRequest(){
    return this.limiter.schedule(this.request, this.options)
    .catch(err => {
      //i get here
      throw err;
    });
  }

  request(url){
    return rp("https://httpstat.us/500")
    .catch(err => {
      //i get here
      throw err;
    })
  }
}

So my problem is, that the error wont be propagated back to the page.js but instead prints an unhandled rejection error in the console. I've tried running this without limiter.schedule but it doesnt make a difference. Would be great to get some pointers, cant figure it out.


问:
My ball is not moving and staying in the center although it should be moving
I am coding a primitive Pong game and I have coded it so for when the ball goes off the left hand side of the screen, it goes to the center of the screen and moves in a random directton. However, upon start the ball always stays in the center and never moves(despite the fact the ball's X coordinate is not less than 0 at start.)

```<code>import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Pong extends JPanel
{
  private static final int FRAME_WIDTH = 400;
  private static final Color BACKGROUND = new Color(204, 204, 204);
  private static final Color BALL_COLOR = Color.BLACK;
  private static final Color PRIZE_COLOR = Color.BLACK;
  private static final int BALL_DIAM = 50;
  private static final int PRIZE_DIAM = 25;
  private static final int PRIZE_SHIFT = 10;
  private BufferedImage myImage;
  private Graphics myBuffer;
  private Ball ball;
  private int score1;
  private int score2;
  private Polkadot prize;
  private Bumper bumper;
  private Bumper bumper2;
  private Timer t;
  private int hits;

  public Pong()
  {
    myImage = new BufferedImage(400, 400, 1);
    myBuffer = this.myImage.getGraphics();
    myBuffer.setColor(BACKGROUND);
    myBuffer.fillRect(0, 0, 400, 400);

    ball = new Ball(0, 0, 35, BALL_COLOR);
    ball.jump(400, 400);

    prize = new Polkadot(0, 0, 25, PRIZE_COLOR);
    prize.jump(400, 400);
    bumper = new Bumper(380,70,50,100,Color.RED);

    bumper2 = new Bumper(30,70,50,100,Color.BLUE);

    hits = 0;

    t = new Timer(5, new Listener());
    t.start();

    addMouseListener(new Mouse());

    addKeyListener(new Key());
    setFocusable(true);
  }

  public void paintComponent(Graphics g)
  {
    g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
  }

  private class Mouse extends MouseAdapter
  {
    private Mouse() {}

    public void mousePressed(MouseEvent e)
    {
      if (e.isMetaDown())
      {
        ball.setX(e.getX());
        ball.setY(e.getY());
      }
      else if (e.isShiftDown())
      {
       ball.setdx((int)(Math.random() * 11.0D - 6.0D));
       ball.setdy((int)(Math.random() * 11.0D - 6.0D));
      }
      else
      {
        prize.setX(e.getX());
        prize.setY(e.getY());
      }
    }
  }

  private class Key extends KeyAdapter
  {
    private Key() {}

    public void keyPressed(KeyEvent e)
    {
      if ((e.getKeyCode() == 38) && (bumper.getY() > 0)) {
        bumper.setY(bumper.getY() - 10);
      } else if ((e.getKeyCode() == 40) && (bumper.getY() < 438)) {
        bumper.setY(bumper.getY() + 10);
      } else if ((e.getKeyCode() == 87) && (bumper2.getY() > 0)) {
        bumper2.setY(bumper2.getY() - 10);
      } else if ((e.getKeyCode() == 83) && (bumper2.getY() < 438)) {
        bumper2.setY(bumper2.getY() + 10);
      }
    }
  }

  private class Listener implements ActionListener
  {
    private Listener() {}

    public void actionPerformed(ActionEvent e)
    {
      myBuffer.setColor(BACKGROUND);
      myBuffer.fillRect(0, 0, 400, 400);

      ball.move(400, 400);
      collide(ball, prize);
      BumperCollision.collide(bumper,ball);
      BumperCollision.collide(bumper2,ball);

      ball.draw(myBuffer);
      prize.draw(myBuffer);
      bumper.draw(myBuffer);
      bumper2.draw(myBuffer);
      myBuffer.setColor(Color.red);
      myBuffer.setFont(new Font("Comic Sans MS", 1, 24));
      myBuffer.drawString("Count: " + score1, 100, 25);
      if(score1 >= 10)
         myBuffer.drawString("This man is the Legend27", 50, 102);
      if(score2 >= 10)
         myBuffer.drawString("The other man might be the legend27", 160, 102);
      if(ball.getX() < -100)
         score1++;
         ball.setX(208);
         ball.setY(50);
         ball.setdx(20);

      repaint();
    }
  }

  public void collide(Ball b, Polkadot p)
  {
    double dist = distance(b.getX(), b.getY(), p.getX(), p.getY());
    if (dist < 37.0D)
    {
      hits += 1;

      p.jump(400, 400);
    }
  }

  private double distance(double x1, double y1, double x2, double y2)
  {
    return Math.sqrt(Math.pow(x1 - x2, 2.0D) + Math.pow(y1 - y2, 2.0D));
  }
}
</code>```

Ball:

```<code>//Name:              Date:
   import java.awt.*;
    public class Ball extends Polkadot
   {
      private double dx;       // pixels to move each time step() is called.
      private double dy;
    // constructors
       public Ball()         //default constructor
      {
         super(200, 200, 50, Color.BLACK);
         dx = Math.random() * 12 - 6;          // to move vertically
         dy = Math.random() * 12 - 6;          // to move sideways
      }
       public Ball(double x, double y, double dia, Color c)
      {
         super(x, y, dia, c);
         dx = Math.random()* 12 - 6;
         dy = Math.random() * 12 - 6;
      }

     //modifier methods
       public void setdx(double x)
      {
         dx = x;
      }
       public void setdy(double y)
      {
         dy = y;
      }

      //accessor methods
       public double getdx()
      {
         return dx;
      }
       public double getdy()
      {
         return dy;
      }

     //instance methods
       public void move(double rightEdge, double bottomEdge)
      {
         setX(getX()+ dx);      // move vert.
         setY(getY()+ dy);

         if(getX() >= rightEdge - getRadius())
         {
            setX(rightEdge - getRadius());
            dx = dx * -1;
         }
         else if(getX() <= getRadius())
         {
          setX(getRadius());
          dx = dx * -1;
         }
         if(getY() >= bottomEdge - getRadius())
         {
          setY(bottomEdge - getRadius());
          dy = dy * -1;
         }
         else if (getY() <= getRadius())
         {
          setY(getRadius());
          dy = dy * -1;
         }
     }
   }
</code>```

答:
You seem to have two different values for the position of the ball, first you have x, y which are from your parent class, the name of which I do not know. Then you have the position delta member variables of the Ball class called dx and dy. Since your constructor you call the parent constructor

```<code>super(x, y, dia, c);
</code>```

Where x, y are 200 respectively and then they are never touched after. My guess is that those hold the true position of your ball and therefore those values need to be set. Use the setters after you create the random delta positions in your Ball constructor like so

```<code>public Ball(double x, double y, double dia, Color c)
{
     super(x, y, dia, c);
     dx = Math.random()* 12 - 6;
     dy = Math.random() * 12 - 6;
     setX(getX() + dx); //add your x difference
     setY(getY() + dy); //add your y difference
}
</code>```

This should now add your deltas to the Ball object on creation and when it gets painted for the first time it will have a random position on your game board every time a Ball gets created.

How about this line inside the actionPerformed()

```<code>if(ball.getX() < -100)
    score1++;
    ball.setX(208);
    ball.setY(50);
    ball.setdx(20);
</code>```

If the setters should be called only when ball.getX() < -100 then you need to use brackets with your if. No brackets after an if only executes the next line, and nothing more.

```<code>if(ball.getX() < -100)
{
    score1++;
    ball.setX(208);
    ball.setY(50);
    ball.setdx(20);
}
</code>```

Body:
I am coding a primitive Pong game and I have coded it so for when the ball goes off the left hand side of the screen, it goes to the center of the screen and moves in a random directton. However, upon start the ball always stays in the center and never moves(despite the fact the ball's X coordinate is not less than 0 at start.)

import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Pong extends JPanel
{
  private static final int FRAME_WIDTH = 400;
  private static final Color BACKGROUND = new Color(204, 204, 204);
  private static final Color BALL_COLOR = Color.BLACK;
  private static final Color PRIZE_COLOR = Color.BLACK;
  private static final int BALL_DIAM = 50;
  private static final int PRIZE_DIAM = 25;
  private static final int PRIZE_SHIFT = 10;
  private BufferedImage myImage;
  private Graphics myBuffer;
  private Ball ball;
  private int score1;
  private int score2;
  private Polkadot prize;
  private Bumper bumper;
  private Bumper bumper2;
  private Timer t;
  private int hits;

  public Pong()
  {
    myImage = new BufferedImage(400, 400, 1);
    myBuffer = this.myImage.getGraphics();
    myBuffer.setColor(BACKGROUND);
    myBuffer.fillRect(0, 0, 400, 400);

    ball = new Ball(0, 0, 35, BALL_COLOR);
    ball.jump(400, 400);

    prize = new Polkadot(0, 0, 25, PRIZE_COLOR);
    prize.jump(400, 400);
    bumper = new Bumper(380,70,50,100,Color.RED);

    bumper2 = new Bumper(30,70,50,100,Color.BLUE);

    hits = 0;

    t = new Timer(5, new Listener());
    t.start();

    addMouseListener(new Mouse());

    addKeyListener(new Key());
    setFocusable(true);
  }

  public void paintComponent(Graphics g)
  {
    g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
  }

  private class Mouse extends MouseAdapter
  {
    private Mouse() {}

    public void mousePressed(MouseEvent e)
    {
      if (e.isMetaDown())
      {
        ball.setX(e.getX());
        ball.setY(e.getY());
      }
      else if (e.isShiftDown())
      {
       ball.setdx((int)(Math.random() * 11.0D - 6.0D));
       ball.setdy((int)(Math.random() * 11.0D - 6.0D));
      }
      else
      {
        prize.setX(e.getX());
        prize.setY(e.getY());
      }
    }
  }

  private class Key extends KeyAdapter
  {
    private Key() {}

    public void keyPressed(KeyEvent e)
    {
      if ((e.getKeyCode() == 38) && (bumper.getY() > 0)) {
        bumper.setY(bumper.getY() - 10);
      } else if ((e.getKeyCode() == 40) && (bumper.getY() < 438)) {
        bumper.setY(bumper.getY() + 10);
      } else if ((e.getKeyCode() == 87) && (bumper2.getY() > 0)) {
        bumper2.setY(bumper2.getY() - 10);
      } else if ((e.getKeyCode() == 83) && (bumper2.getY() < 438)) {
        bumper2.setY(bumper2.getY() + 10);
      }
    }
  }

  private class Listener implements ActionListener
  {
    private Listener() {}

    public void actionPerformed(ActionEvent e)
    {
      myBuffer.setColor(BACKGROUND);
      myBuffer.fillRect(0, 0, 400, 400);

      ball.move(400, 400);
      collide(ball, prize);
      BumperCollision.collide(bumper,ball);
      BumperCollision.collide(bumper2,ball);

      ball.draw(myBuffer);
      prize.draw(myBuffer);
      bumper.draw(myBuffer);
      bumper2.draw(myBuffer);
      myBuffer.setColor(Color.red);
      myBuffer.setFont(new Font("Comic Sans MS", 1, 24));
      myBuffer.drawString("Count: " + score1, 100, 25);
      if(score1 >= 10)
         myBuffer.drawString("This man is the Legend27", 50, 102);
      if(score2 >= 10)
         myBuffer.drawString("The other man might be the legend27", 160, 102);
      if(ball.getX() < -100)
         score1++;
         ball.setX(208);
         ball.setY(50);
         ball.setdx(20);

      repaint();
    }
  }

  public void collide(Ball b, Polkadot p)
  {
    double dist = distance(b.getX(), b.getY(), p.getX(), p.getY());
    if (dist < 37.0D)
    {
      hits += 1;

      p.jump(400, 400);
    }
  }

  private double distance(double x1, double y1, double x2, double y2)
  {
    return Math.sqrt(Math.pow(x1 - x2, 2.0D) + Math.pow(y1 - y2, 2.0D));
  }
}

Ball:

//Name:              Date:
   import java.awt.*;
    public class Ball extends Polkadot
   {
      private double dx;       // pixels to move each time step() is called.
      private double dy;
    // constructors
       public Ball()         //default constructor
      {
         super(200, 200, 50, Color.BLACK);
         dx = Math.random() * 12 - 6;          // to move vertically
         dy = Math.random() * 12 - 6;          // to move sideways
      }
       public Ball(double x, double y, double dia, Color c)
      {
         super(x, y, dia, c);
         dx = Math.random()* 12 - 6;
         dy = Math.random() * 12 - 6;
      }

     //modifier methods
       public void setdx(double x)
      {
         dx = x;
      }
       public void setdy(double y)
      {
         dy = y;
      }

      //accessor methods
       public double getdx()
      {
         return dx;
      }
       public double getdy()
      {
         return dy;
      }

     //instance methods
       public void move(double rightEdge, double bottomEdge)
      {
         setX(getX()+ dx);      // move vert.
         setY(getY()+ dy);

         if(getX() >= rightEdge - getRadius())
         {
            setX(rightEdge - getRadius());
            dx = dx * -1;
         }
         else if(getX() <= getRadius())
         {
          setX(getRadius());
          dx = dx * -1;
         }
         if(getY() >= bottomEdge - getRadius())
         {
          setY(bottomEdge - getRadius());
          dy = dy * -1;
         }
         else if (getY() <= getRadius())
         {
          setY(getRadius());
          dy = dy * -1;
         }
     }
   }

Body:
You seem to have two different values for the position of the ball, first you have x, y which are from your parent class, the name of which I do not know. Then you have the position delta member variables of the Ball class called dx and dy. Since your constructor you call the parent constructor

super(x, y, dia, c);

Where x, y are 200 respectively and then they are never touched after. My guess is that those hold the true position of your ball and therefore those values need to be set. Use the setters after you create the random delta positions in your Ball constructor like so

public Ball(double x, double y, double dia, Color c)
{
     super(x, y, dia, c);
     dx = Math.random()* 12 - 6;
     dy = Math.random() * 12 - 6;
     setX(getX() + dx); //add your x difference
     setY(getY() + dy); //add your y difference
}

This should now add your deltas to the Ball object on creation and when it gets painted for the first time it will have a random position on your game board every time a Ball gets created.

How about this line inside the actionPerformed()

if(ball.getX() < -100)
    score1++;
    ball.setX(208);
    ball.setY(50);
    ball.setdx(20);

If the setters should be called only when ball.getX() < -100 then you need to use brackets with your if. No brackets after an if only executes the next line, and nothing more.

if(ball.getX() < -100)
{
    score1++;
    ball.setX(208);
    ball.setY(50);
    ball.setdx(20);
}


问:
What is the recommended way to upgrade a dataproc cluster?
Dataproc seems to be designed to be Stateless / Immutable. Is this assumption correct? Should we just quit right now if we are planning to deploy a Hive/Presto data warehouse?

We are struggling to find any documentation that suggests how one should care for a cluster once has been provisioned?

How to upgrade components?

How to install tools (e.g. Hue etc) after a cluster was established?

How to secure access to data + services once deployed?

The FAQs "Can I run a persistent cluster?" don't really address this either.

The internet
is suggesting we should just create a new cluster if we have a problem. As a developer I'm quite happy with the "Minimize State" argument but I work in the enterprise world that like solutions like Hive (and its metadata store), Hue and Zeppellin and want to connect external tools like Tableau into a cluster.

The documentation should really make it clear which use-cases dataproc excels at (Batch, on-demand & short lived workloads) vs things it isn't really designed for (e.g. OLAP)?

答:
Dataproc indeed provides the most benefit for on-demand use cases, but this isn't necessarily at odds with being used for OLAP. The main idea is that the stateful components can all be separated from the "processing" resources so that you can better adjust resources according to needs at different points in time.

The recommended architecture for your Hive metadata is to keep your Hive metastore backend off the cluster, e.g. in a CloudSQL instance; many are able to use Dataproc in this way with short-lived or semi-short-lived clusters (e.g. keeping a pool of live clusters but deleting/recreating the oldest each day or each week) combined with initialization actions pointing the Hiveserver at CloudSQL: https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/tree/master/cloud-sql-proxy

In this world, the stateful metastore pieces are all in CloudSQL and bulk storage is all in GCS. Some clusters might sync from GCS to local HDFS for performance reasons (especially if running HDFS on local-SSD), but even for interactive OLAP use cases, this isn't usually necessary; running queries directly against GCS works fine too. There are admittedly some performance pitfalls for older formats due to longer round-trip latency to GCS, but a bit of tuning can bring it mostly in-line; here's a (non-google-owned) blog post about Presto on Dataproc going over some of those.

This also provides much easier ways to handle traditional cluster admin; upgrades are just swapping out entire clusters, additional tools should be done in initialization actions for easy reproducibility on new clusters, and you can more easily define security perimeters at a per-cluster granularity.


问:
How to setup wxPython/robot framework RIDE on MAC?the wxPython did not work after run ride.py(on MAC OS)
I try to install Robot Framework RIDE to MAC(version 10.9.5) today.

python version is 2.7.9(is default version in MAC)

installed wxPython 2.8.12.1, install success.

install Robot Framework(robotframework-ride-1.1) success.

when I try to open graphic tool RIDE and run ride.py.

I got return:

wxPython not found. You need to install wxPython 2.8 or 2.9 toolkit
  with unicode support to run RIDE. See http://wxpython.org for more
  information.

Actually, I have installed wxPython 2.8.12.1, and when I try to run "import wx" in python env, I can got wxPython information return.

Anyone know how should I open graphic tool RIDE? Thanks!

答:
This solution worked like a charm for me:

I went to this directory: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/robotframework_ride-2.0a1-py2.7.egg/robotide

and then ran arch -i386 python __init__.py,

It launched RIDE editor!


问:
Trying to loop through a pandas dataframe and display specific values in a column
So I'm trying to code a stroop task by looping through a preexisting .csv file. To do this I read the stimuli.csv file into a dataframe.

The .csv file is organized like this:

```<code>  Colours   Congruent   Word
0   red       0        blue
1   red       1        red
2   red       0        green
3   blue      1        blue
</code>```

I then try to loop through the dataframe checking values in the 'Colours' column and 'Words' column. Colours should be displayed as the font of the word so I check the indexed value in the Colour column to properly display the corresponding colour font. The word displayed itself should be the value indexed in the 'Word' column. I'm getting:

Keyerror: 0

I've looked online but no specific examples help me. Can anyone tell me if i'm going about this all wrong?

```<code>import pygame
import sys
import psychopy
import os
import csv
import pandas as pd
pygame.init()
screen = pygame.display.set_mode((1000, 500))
screen.fill((0, 0, 0))
myfont= pygame.font.SysFont("Calibri", 30)
blue= (0,0,255)
green= (0,255,0)
red= (255,0,0)
while 1:
    file= r'stimuli.csv'
    df= pd.read_csv('%s' %file, delimiter=',', encoding="utf-8-sig")
    word= df['Word']
    congruent= df['Congruent']
    colour= df['Colours']
    for index, row in df.iterrows():
        word= df[index].iloc['Word']
        congruent= df[index].iloc['Congruent']
        colour= df[index].iloc['Colours']
        if df.iloc[index].iloc['Colours']== 'red':
            stim= myfont.render('%s' %word, 1, (255,0,0))
            screen.blit(stim, (300,300))
            pygame.display.flip()
        if df.iloc[index].iloc['Colours']== 'green':
            stim= myfont.render('%s' %word, 1, (0,255,0))
            screen.blit(stim, (300,300))
            pygame.display.flip()
        if df.iloc[index].iloc['Colours']== 'blue':
            stim= myfont.render('%s' %word, 1, (0,0,255))
            screen.blit(stim, (300,300))
            pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key== pygame.K_ESCAPE:
                msg2= myfont.render("Exiting now", 1, (0, 255, 0))
                screen.blit(msg2, (300, 300))
                pygame.display.flip()

                pygame.display.quit()
pygame.quit()
</code>```

答:
Have a look at this example to minify your code. Use it to update your code and make things more readable.</p>

```<code>df = pd.DataFrame(dict(Colours=['Red','Blue']))

d_colour = dict(Red=(255,0,0),Green=(0,255,0),Blue=(0,0,255))

for index, row in df.iterrows():
    colour= df.loc[index,'Colours']
    colour_code = d_colour.get(colour)
    print(colour_code)
    #stim= myfont.render('%s' %word, 1, colour_code)
    #screen.blit(stim, (300,300))
    #pygame.display.flip()
</code>```

Body:
So I'm trying to code a stroop task by looping through a preexisting .csv file. To do this I read the stimuli.csv file into a dataframe.

The .csv file is organized like this:

  Colours   Congruent   Word
0   red       0        blue
1   red       1        red
2   red       0        green
3   blue      1        blue

I then try to loop through the dataframe checking values in the 'Colours' column and 'Words' column. Colours should be displayed as the font of the word so I check the indexed value in the Colour column to properly display the corresponding colour font. The word displayed itself should be the value indexed in the 'Word' column. I'm getting:

Keyerror: 0

I've looked online but no specific examples help me. Can anyone tell me if i'm going about this all wrong?

import pygame
import sys
import psychopy
import os
import csv
import pandas as pd
pygame.init()
screen = pygame.display.set_mode((1000, 500))
screen.fill((0, 0, 0))
myfont= pygame.font.SysFont("Calibri", 30)
blue= (0,0,255)
green= (0,255,0)
red= (255,0,0)
while 1:
    file= r'stimuli.csv'
    df= pd.read_csv('%s' %file, delimiter=',', encoding="utf-8-sig")
    word= df['Word']
    congruent= df['Congruent']
    colour= df['Colours']
    for index, row in df.iterrows():
        word= df[index].iloc['Word']
        congruent= df[index].iloc['Congruent']
        colour= df[index].iloc['Colours']
        if df.iloc[index].iloc['Colours']== 'red':
            stim= myfont.render('%s' %word, 1, (255,0,0))
            screen.blit(stim, (300,300))
            pygame.display.flip()
        if df.iloc[index].iloc['Colours']== 'green':
            stim= myfont.render('%s' %word, 1, (0,255,0))
            screen.blit(stim, (300,300))
            pygame.display.flip()
        if df.iloc[index].iloc['Colours']== 'blue':
            stim= myfont.render('%s' %word, 1, (0,0,255))
            screen.blit(stim, (300,300))
            pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key== pygame.K_ESCAPE:
                msg2= myfont.render("Exiting now", 1, (0, 255, 0))
                screen.blit(msg2, (300, 300))
                pygame.display.flip()

                pygame.display.quit()
pygame.quit()

Body:
Have a look at this example to minify your code. Use it to update your code and make things more readable.

df = pd.DataFrame(dict(Colours=['Red','Blue']))

d_colour = dict(Red=(255,0,0),Green=(0,255,0),Blue=(0,0,255))

for index, row in df.iterrows():
    colour= df.loc[index,'Colours']
    colour_code = d_colour.get(colour)
    print(colour_code)
    #stim= myfont.render('%s' %word, 1, colour_code)
    #screen.blit(stim, (300,300))
    #pygame.display.flip()


问:
Injecting DbContext to class library project in same Asp.Net Core 2 solution
Something that used to be relatively easy, isn't so anymore. Of the dozens of times I've searched, I rarely find an answer to this situation, which I cannot believe is anything other than prevalent in most project structures.

I have the standard Core 2.0 Web app, and for now, for simplicity sake, an Infrastructure project and a unit test project. I have a good idea how to accomplish the test scenario since the test project doesn't run asp.net and I have a great video tutorial on how to accomplish it.

The problem lies with getting access to the DbContext in my infrastructure project. (.Net Core class library)

The DbContext sets up perfectly fine in Startup

```<code>var connString = Configuration.GetSection("ApplicationConfiguration:ConnectionStrings:DefaultConnection").Value;
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(connString));
</code>```

And in a controller I can access it

```<code>private ApplicationDbContext _context;
private IConfiguration Configuration { get; set; }

public HomeController(IConfiguration configuration, ApplicationDbContext context)
{
    _context = context;
    Configuration = configuration;
}

public IActionResult Index()
{
     // gets users from the DI injected context in the controller
    var users = _context.AppUsers.ToList();

    // if GetUsers is defined statically, this doesn't work because the injected context is always null
    //var diUsers = DatabaseService.GetUsers():

    // making it non-static and newing it up works, but defeats the purpose because you are passing the context, asp.net is not injecting it
    var ds = new DatabaseService(_context);
    var diUsers = ds.GetUsers();

    var svm = SettingsViewModel();

    return View(svm);
}
</code>```

DatabaseService

```<code>private ApplicationDbContext _context;
//this is the constructor for DatabaseService class
public DatabaseService(ApplicationDbContext context)
{
    _context = context;
}

public List<ApplicationUser> GetUsers()
{
    var users = _context.AppUsers.ToList();
    return users;
}
</code>```

Yes, I know I should be using a repository and I will once I get this figured out correctly. How do I set up my classes in the Infrastructure project so I have the injected DbContext created at Startup and not have to pass it as a parameter.

Addendum:

Using the answer provided by Nkosi, I can inject the data service in the controller and use it.

But if I have a separate Infrastructure project (Asp.net core 2 class library), which implements my repository and UoW

```<code> public class GenericRepository<T> : IRepository<T> where T : class
{
    public GenericRepository()
    {

    }
    //rest of code removed
}
</code>```

How can I get the DbContext injected there? Do I need to create an Interface, IDbContext, to wrap DbContext, and register that in startup?

答:
Assuming you have the following for your service

```<code>public interface IDatabaseService {
    List<ApplicationUser> GetUsers();
    //...
}

public class DatabaseService : IDatabaseService {

    public DatabaseService(ApplicationDbContext context) {
        //...code removed for brevity
    }

    //...code removed for brevity
}
</code>```

The service explicitly depends on the ApplicationDbContext which will be injected when the implementation is being resolved from the service container.

Register the service in Startup.ConfigureServices

```<code>var connString = Configuration.GetSection("ApplicationConfiguration:ConnectionStrings:DefaultConnection").Value;
services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(connString));
services.AddScoped<IDatabaseService, DatabaseService>();
</code>```

And refactor the controller to explicitly depend on the service

```<code>private IDatabaseService ds;
private IConfiguration Configuration { get; set; }

public HomeController(IConfiguration configuration, IDatabaseService ds) {
    this.ds = ds;
    Configuration = configuration;
}

public IActionResult Index() {
    var diUsers = ds.GetUsers();

    var svm = SettingsViewModel();

    return View(svm);
}
</code>```

Body:
Something that used to be relatively easy, isn't so anymore. Of the dozens of times I've searched, I rarely find an answer to this situation, which I cannot believe is anything other than prevalent in most project structures.

I have the standard Core 2.0 Web app, and for now, for simplicity sake, an Infrastructure project and a unit test project. I have a good idea how to accomplish the test scenario since the test project doesn't run asp.net and I have a great video tutorial on how to accomplish it.

The problem lies with getting access to the DbContext in my infrastructure project. (.Net Core class library)

The DbContext sets up perfectly fine in Startup

var connString = Configuration.GetSection("ApplicationConfiguration:ConnectionStrings:DefaultConnection").Value;
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(connString));

And in a controller I can access it

private ApplicationDbContext _context;
private IConfiguration Configuration { get; set; }

public HomeController(IConfiguration configuration, ApplicationDbContext context)
{
    _context = context;
    Configuration = configuration;
}

public IActionResult Index()
{
     // gets users from the DI injected context in the controller
    var users = _context.AppUsers.ToList();

    // if GetUsers is defined statically, this doesn't work because the injected context is always null
    //var diUsers = DatabaseService.GetUsers():

    // making it non-static and newing it up works, but defeats the purpose because you are passing the context, asp.net is not injecting it
    var ds = new DatabaseService(_context);
    var diUsers = ds.GetUsers();

    var svm = SettingsViewModel();

    return View(svm);
}

DatabaseService

private ApplicationDbContext _context;
//this is the constructor for DatabaseService class
public DatabaseService(ApplicationDbContext context)
{
    _context = context;
}

public List<ApplicationUser> GetUsers()
{
    var users = _context.AppUsers.ToList();
    return users;
}

Yes, I know I should be using a repository and I will once I get this figured out correctly. How do I set up my classes in the Infrastructure project so I have the injected DbContext created at Startup and not have to pass it as a parameter.

Addendum:

Using the answer provided by Nkosi, I can inject the data service in the controller and use it.

But if I have a separate Infrastructure project (Asp.net core 2 class library), which implements my repository and UoW

 public class GenericRepository<T> : IRepository<T> where T : class
{
    public GenericRepository()
    {

    }
    //rest of code removed
}

How can I get the DbContext injected there? Do I need to create an Interface, IDbContext, to wrap DbContext, and register that in startup?

Body:
Assuming you have the following for your service

public interface IDatabaseService {
    List<ApplicationUser> GetUsers();
    //...
}

public class DatabaseService : IDatabaseService {

    public DatabaseService(ApplicationDbContext context) {
        //...code removed for brevity
    }

    //...code removed for brevity
}

The service explicitly depends on the ApplicationDbContext which will be injected when the implementation is being resolved from the service container.

Register the service in Startup.ConfigureServices

var connString = Configuration.GetSection("ApplicationConfiguration:ConnectionStrings:DefaultConnection").Value;
services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(connString));
services.AddScoped<IDatabaseService, DatabaseService>();

And refactor the controller to explicitly depend on the service

private IDatabaseService ds;
private IConfiguration Configuration { get; set; }

public HomeController(IConfiguration configuration, IDatabaseService ds) {
    this.ds = ds;
    Configuration = configuration;
}

public IActionResult Index() {
    var diUsers = ds.GetUsers();

    var svm = SettingsViewModel();

    return View(svm);
}


问:
eConnect to Great Plains Error: 'Timeout expired' - How to fix?
Receiving the following error when trying to pull reconciled orders from the last 30 days in Great Plains from a SOAP call:

Server</faultcode><faultstring>System.Web.Services.Protocols.SoapException:
  Server was unable to process request.
  ---> System.Data.SqlClient.SqlException:
  Timeout expired.  The timeout period
  elapsed prior to completion of the
  operation or the server is not
  responding.
   at
  System.Data.SqlClient.SqlConnection.OnError(SqlException
  exception, Boolean
  breakConnection)
   at
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection)

How can I determine or change the timeout setting? Is that a connection string variable? In our web service method, it has this at the beginning:

```<code>ConnectionString = ConfigurationManager.ConnectionStrings["gp"].ToString();
</code>```

Which it gets from a web.config file:

```<code><configuration>

    <appSettings/>
    <connectionStrings>
        <add name="gp" connectionString="Data Source=10.10.10.90;Integrated Security=SSPI;Persist Security Info=False;trusted_connection=true;Initial Catalog=DEFAULT;" />
    </connectionStrings>
    <system.web>
</code>```

Not all that versed in ASP/eConnect and this has worked up until a few weeks ago when the timeout error started.

答: Reducing the amount of records returned to 15 days seems to alleviate this issue.</p>

Body:
Receiving the following error when trying to pull reconciled orders from the last 30 days in Great Plains from a SOAP call:

Server</faultcode><faultstring>System.Web.Services.Protocols.SoapException:
  Server was unable to process request.
  ---> System.Data.SqlClient.SqlException:
  Timeout expired.  The timeout period
  elapsed prior to completion of the
  operation or the server is not
  responding.
   at
  System.Data.SqlClient.SqlConnection.OnError(SqlException
  exception, Boolean
  breakConnection)
   at
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection)

How can I determine or change the timeout setting? Is that a connection string variable? In our web service method, it has this at the beginning:

ConnectionString = ConfigurationManager.ConnectionStrings["gp"].ToString();

Which it gets from a web.config file:

<configuration>

    <appSettings/>
    <connectionStrings>
        <add name="gp" connectionString="Data Source=10.10.10.90;Integrated Security=SSPI;Persist Security Info=False;trusted_connection=true;Initial Catalog=DEFAULT;" />
    </connectionStrings>
    <system.web>

Not all that versed in ASP/eConnect and this has worked up until a few weeks ago when the timeout error started.