问:
What's the official Microsoft way to track counts of dynamic controls to be reconstructed upon Postback?
When creating dynamic controls based on a data source of arbitrary and changing size, what is the official way to track exactly how many controls need to be rebuilt into the page's control collection after a Postback operation (i.e. on the server side during the ASP.NET page event lifecycle) specifically the point at which dynamic controls are supposed to be rebuilt?  Where is the arity stored for retrieval and reconstruction usage?

By "official" I mean the Microsoft way of doing it. There exist hacks like Session storage, etc but I want to know the bonafide or at least Microsoft-recommended way.  I've been unable to find a documentation page stating this information. Usually code samples work with a set of dynamic controls of known numbers. It's as if doing otherwise would be tougher.

Update: I'm not inquiring about user controls or static expression of declarative controls, but instead about dynamically injecting controls completely from code-behind, whether they be mine, 3rd-party or built-in ASP.NET controls.

答:
This greatly depends on the problem at hand, and the type of controls you're recreating. Are they all simple text boxes or various different complex custom user controls. the main thing here is: if you want your dynamic control to regain state after a post-back, you have to re-create it in the Init phase of a page life-cycle.

Anyway. There's nothing like a Microsoft way or Microsoft recommended way basically. When you're dynamically adding several simple controls of the same type a hidden field with a count would do the trick, but when you have several complex controls other ways would have to be used. You could still hidden fields and save control's full type strings in them (ie. System.Web.UI.WebControls.TextBox) and re-instantiate them. But think of an even more complex example of putting various controls on different parts in the page... And initializing them to a specific state. That would be a bit more challenging. Hence no Microsoft way... The recommended way is to recreate in Init phase. And that's it.

Everything can be solved, but sometimes one took a wrong direction in the UI and things could be done easier using a different approach.

Additional explanation

This state-full technique of ViewState that Asp.net uses is considered the worse culprit with web developers in general. That's why Asp.net MVC developers think the new framework is bliss since its much more suited to the state-less HTTP protocol. Me being one of them. :D


来源: stackexchange

问:
How to center the ul in the HTML
I have this html and CSS code on which I have spent the last 3 hrs and I am still not able to figure out how to center align the top menu bar in my code. The code is as follows:

#container ul {
  list-style: none;
  margin: auto;
  padding: 0;
}

#container ul li a {
  color: #FFFFFF;
}

#container ul li {
  background-color: #6068FF;
  width: 180px;
  border: 1px solid white;
  height: 50px;
  line-height: 50px;
  text-align: center;
  float: left;
  align-items: center;
  color: #FFFFFF;
  font-size: 18;
}

#container ul li:hover {
  background-color: #0BF5F5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <ul>
    <li>Student Attendance</li>
    <li>Edit Students</li>
    <li>Profile</li>
    <li>Logout</li>
  </ul>
</div></code>```

答:
You either need to display the list as an inline element or give it a fixed with, otherwise it always will take full available horizontal space.</p>

```<code>#container ul {
    display: inline-block;
    list-style:none;
    margin:auto;
    padding: 0;
}

/* or */

#container ul {
    width: 50%; /* whatever */
    list-style:none;
    margin:auto;
    padding: 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to center the ul in the HTML

Body:
I have this html and CSS code on which I have spent the last 3 hrs and I am still not able to figure out how to center align the top menu bar in my code. The code is as follows:

#container ul {
  list-style: none;
  margin: auto;
  padding: 0;
}

#container ul li a {
  color: #FFFFFF;
}

#container ul li {
  background-color: #6068FF;
  width: 180px;
  border: 1px solid white;
  height: 50px;
  line-height: 50px;
  text-align: center;
  float: left;
  align-items: center;
  color: #FFFFFF;
  font-size: 18;
}

#container ul li:hover {
  background-color: #0BF5F5;
}

Student Attendance

Edit Students

Profile

Logout

Body:
You either need to display the list as an inline element or give it a fixed with, otherwise it always will take full available horizontal space.

#container ul {
    display: inline-block;
    list-style:none;
    margin:auto;
    padding: 0;
}

/* or */

#container ul {
    width: 50%; /* whatever */
    list-style:none;
    margin:auto;
    padding: 0;
}


问:
How can I load the CSS file with HTML in Swift 3?
I have an HTML file which is being displayed fine on my device but it does not load the CSS file in it on my device. When I do open the HTML on my browser, my CSS is working fine.

This is my HTML code:

```<code><head>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
    <h1>Prateek Bhatt</h1>
    <br>
    <p>is the greatest</p>
</body>
</code>```

This is my CSS file named stylesheet.css:

```<code>body {
    background-color: lightblue;
}

h1 {
    color: navy;
    margin-left: 20px;
}
</code>```

Also this is the code for Swift 3:

```<code>class ViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let htmlFile = Bundle.main.path(forResource: "index", ofType: "html")
        let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        webView.loadHTMLString(html!, baseURL: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

答:
Follow these four steps to load a CSS file in a WebView:

Step 1:
Access the local CSS file from the Bundle.

guard let path = Bundle.main.path(forResource: "Style", ofType: "css") else { return }

Step 2:
Get the CSS content in String format.

let cssString = try! String(contentsOfFile: path).trimmingCharacters(in: .whitespacesAndNewlines)

Step 3:
Write your JavaScript in a string to be evaluated later by the WebView.

let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"

Step 4: Render the JavaScript.

webView.evaluateJavaScript(jsString, completionHandler: nil)

DOCUMENTATION

Framework: WebKit
https://developer.apple.com/documentation/webkit/

Class: WKWebView
https://developer.apple.com/documentation/webkit/wkwebview

Instance Method: evaluateJavaScript(_:completionHandler:)
https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript

Body:
I have an HTML file which is being displayed fine on my device but it does not load the CSS file in it on my device. When I do open the HTML on my browser, my CSS is working fine.

This is my HTML code:

    <link rel="stylesheet" type="text/css" href="stylesheet.css">

Prateek Bhatt

is the greatest

This is my CSS file named stylesheet.css:

body {
    background-color: lightblue;
}

h1 {
    color: navy;
    margin-left: 20px;
}

Also this is the code for Swift 3:

class ViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let htmlFile = Bundle.main.path(forResource: "index", ofType: "html")
        let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        webView.loadHTMLString(html!, baseURL: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

ContentLicense: CC BY-SA 4.0


问:
Found input variables with inconsistent numbers of samples when fitting LogisticRegression
I am creating LogisticRegression classifier with the following code:

```<code>regressor = LogisticRegression()
regressor.fit(x_train, y_train)
</code>```

Both x_train and y_train shapes are

```<code><class 'tuple'>: (32383,)
</code>```

x_train contains values around range [0..1], and y_train contains only 0s and 1s.

Unfortunately, fit fails with error

```<code>ValueError: Found input variables with inconsistent numbers of samples: [1, 32383]
</code>```

Adding transpose to arguments doesn't help.

答:
I guess a little reshaping is necessary. I tried it like this :

```<code>    from sklearn.linear_model import LogisticRegression
    import numpy as np

    #x_train = np.random.randn(10,1)
    x_train = np.asarray(x_train).reshape(32383,1)
    con = np.ones_like(x_train)

    x_train = np.concatenate((con,x_train), axis =1)

    #y = np.random.randn(10,1)
    #y_train = np.where(y<0.5,1,0)
    y_train = np.asarray(y_train).reshape(32383,1)
    regressor = LogisticRegression()
    regressor.fit(x_train,y_train)
</code>```

The comments are just what i did to create some data. And dont forget to ad a constant like in the example, as far as i know sklearn isn't doing it. Also Statsmodels could be helpfull to you if you are interested in some statistical test and a pretty print of the results :

```<code>    from statsmodels.api import Logit

    logit =Logit(y_train, x_train)

    fit= logit.fit()
    fit.summary()
</code>```

That will give you a little more statistical intel without much effort.

Body:
I am creating LogisticRegression classifier with the following code:

regressor = LogisticRegression()
regressor.fit(x_train, y_train)

Both x_train and y_train shapes are

<class 'tuple'>: (32383,)

x_train contains values around range [0..1], and y_train contains only 0s and 1s.

Unfortunately, fit fails with error

ValueError: Found input variables with inconsistent numbers of samples: [1, 32383]

Adding transpose to arguments doesn't help.

Body:
I guess a little reshaping is necessary. I tried it like this :

    from sklearn.linear_model import LogisticRegression
    import numpy as np

    #x_train = np.random.randn(10,1)
    x_train = np.asarray(x_train).reshape(32383,1)
    con = np.ones_like(x_train)

    x_train = np.concatenate((con,x_train), axis =1)

    #y = np.random.randn(10,1)
    #y_train = np.where(y<0.5,1,0)
    y_train = np.asarray(y_train).reshape(32383,1)
    regressor = LogisticRegression()
    regressor.fit(x_train,y_train)

The comments are just what i did to create some data. And dont forget to ad a constant like in the example, as far as i know sklearn isn't doing it. Also Statsmodels could be helpfull to you if you are interested in some statistical test and a pretty print of the results :

    from statsmodels.api import Logit

    logit =Logit(y_train, x_train)

    fit= logit.fit()
    fit.summary()

That will give you a little more statistical intel without much effort.


问:
Sorting A Character Dataframe According to desired way
I have a dataframe k which contains following strings in the same order:

```<code>6 to 12 months
12 to 24 months
36 to 60 months
60 to 96 months
0 to 6 months
24 to 36 months
96 to 120 months
120 months & above.
</code>```

When I apply the sort command it sorts by the integer values For eg. the string 120 months and above is placed before 6-12 months. Can anyone tell me how to sort it like below using some R command:

```<code>0 to 6 months
6 to 12 months
12 to 24 months
24 to 36 months
36 to 60 months
60 to 96 months
96 to 120 months
120 months & above.
</code>```

答:
When the custom sort does not work, you need to manually specify the order. Create a factor with your specified order, and sort it. Works, even if the array does not contain the group you mention in order.

```<code>col1 = c("6 to 12 months",
        "12 to 24 months",
        "36 to 60 months",
        "60 to 96 months",
        "0 to 6 months",
        "24 to 36 months",
        "96 to 120 months",
        "120 months & above")

order <- c("0 to 6 months",
         "6 to 12 months",
         "12 to 24 months",
         "24 to 36 months",
         "36 to 60 months",
         "60 to 96 months",
         "96 to 120 months",
         "120 months & above")
col2 <- factor(col1, levels = order)
sort(col2)
</code>```

Just make sure that the order contains all the possible values in your array. This example looks very trivial because the input vector is unique. If the input is of length 100, with these 8 possible values then it makes sense.

When there are many more such partitions, use this

```<code>names(sort(sapply(col1, function(x)
  as.integer(stringr::str_split(x, pattern = ' ')[[1]][1]))))
</code>```

Both the methods give the same output. I would prefer the first method because it is much less prone to mistakes.

Body:
I have a dataframe k which contains following strings in the same order:

6 to 12 months
12 to 24 months
36 to 60 months
60 to 96 months
0 to 6 months
24 to 36 months
96 to 120 months
120 months & above.

When I apply the sort command it sorts by the integer values For eg. the string 120 months and above is placed before 6-12 months. Can anyone tell me how to sort it like below using some R command:

0 to 6 months
6 to 12 months
12 to 24 months
24 to 36 months
36 to 60 months
60 to 96 months
96 to 120 months
120 months & above.

Body:
When the custom sort does not work, you need to manually specify the order. Create a factor with your specified order, and sort it. Works, even if the array does not contain the group you mention in order.

col1 = c("6 to 12 months",
        "12 to 24 months",
        "36 to 60 months",
        "60 to 96 months",
        "0 to 6 months",
        "24 to 36 months",
        "96 to 120 months",
        "120 months & above")

order <- c("0 to 6 months",
         "6 to 12 months",
         "12 to 24 months",
         "24 to 36 months",
         "36 to 60 months",
         "60 to 96 months",
         "96 to 120 months",
         "120 months & above")
col2 <- factor(col1, levels = order)
sort(col2)

Just make sure that the order contains all the possible values in your array. This example looks very trivial because the input vector is unique. If the input is of length 100, with these 8 possible values then it makes sense.

When there are many more such partitions, use this

names(sort(sapply(col1, function(x)
  as.integer(stringr::str_split(x, pattern = ' ')[[1]][1]))))

Both the methods give the same output. I would prefer the first method because it is much less prone to mistakes.


问:
Error establishing a database connection on wordpress
i have a blog with wordpress but sometimes i have problem with that

i got blow error

Error establishing a database connection
This either means that the username and password information in your wp-config.php file is incorrect or we can't contact the database server at %s. This could mean your host's database server is down.

Are you sure you have the correct username and password?
Are you sure that you have typed the correct hostname?
Are you sure that the database server is running?
If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums

and this is my config file

```<code>define('WP_HOME','http://www.mysite.com');
define('WP_SITEURL','http://www.mysite.come');
define('DB_NAME', 'mydbname');

/** MySQL database username */
define('DB_USER', 'dbusername');

/** MySQL database password */
define('DB_PASSWORD', 'dbpassword');

/** MySQL hostname */
define('DB_HOST', 'mysite.com');
</code>```

why i got this error sometimes what do you think about this problem?

i contact with my admins server and they said "we dont have any problem with server and mysql service"

does my server have problem or my config have problem?

答:
Some time this happen , just because of incorrect credentials so check your credentials or try to reset your user name and passward ,  some time host issue or you can repair the database just go to your wp-config file and write
define ( 'WP_ALLOW_REPAIR' , true);
and repair it and don't forget to remove this line after repair.</p>

ContentLicense: CC BY-SA 2.5

Body:
i have a blog with wordpress but sometimes i have problem with that

i got blow error

Error establishing a database connection
This either means that the username and password information in your wp-config.php file is incorrect or we can't contact the database server at %s. This could mean your host's database server is down.

Are you sure you have the correct username and password?
Are you sure that you have typed the correct hostname?
Are you sure that the database server is running?
If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums

and this is my config file

define('WP_HOME','http://www.mysite.com');
define('WP_SITEURL','http://www.mysite.come');
define('DB_NAME', 'mydbname');

/** MySQL database username */
define('DB_USER', 'dbusername');

/** MySQL database password */
define('DB_PASSWORD', 'dbpassword');

/** MySQL hostname */
define('DB_HOST', 'mysite.com');

why i got this error sometimes what do you think about this problem?

i contact with my admins server and they said "we dont have any problem with server and mysql service"

does my server have problem or my config have problem?


问:
.htaccess returns 500 but gets fixed when re-arranging the rules
Some weird stuff happening in .htaccess file

File that does not works

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*?)/([a-z0-9_-]+)$ $1/post?id=$2 [L,QSA]
RewriteRule ^(.*?)/edit/([a-z0-9_-]+)$ $1/editpost.php?id=$2 [L,QSA]

#RewriteRule ^users/(\d+)*$ ./profile.php?id=$1
</code>```

But this works

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*?)/edit/([a-z0-9_-]+)$ $1/editpost.php?id=$2 [L,QSA]
RewriteRule ^(.*?)/([a-z0-9_-]+)$ $1/post?id=$2 [L,QSA]

#RewriteRule ^users/(\d+)*$ ./profile.php?id=$1
</code>```

I simply re-arranged the rewrite rule and it fixed the issue. Can anyone explain why this happened? I was stuck in this for more than 2 hrs.

I am new to URL rewriting so please explain in detail. And what actually [L, QSA] does?

答:
RewriteCond is only applicable to nearest RewriteRule. So in your first example it is applied to only this rule:

```<code>RewriteRule ^(.*?)/([a-z0-9_-]+)$ $1/post?id=$2 [L,QSA]
</code>```

Two bottom RewriteRule are executed without any RewriteCond and cause infinite loop.

You can have your rules as:

```<code>RewriteEngine On
RewriteBase /

# skip all files and directories from rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^(.*?)/edit/([\w-]+)/?$ $1/editpost.php?id=$2 [L,QSA]

RewriteRule ^users/(\d+)/?$ profile.php?id=$1 [L,QSA]

RewriteRule ^(.*?)/([\w-]+)/?$ $1/post?id=$2 [L,QSA]
</code>```

Body:
Some weird stuff happening in .htaccess file

File that does not works

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*?)/([a-z0-9_-]+)$ $1/post?id=$2 [L,QSA]
RewriteRule ^(.*?)/edit/([a-z0-9_-]+)$ $1/editpost.php?id=$2 [L,QSA]

#RewriteRule ^users/(\d+)*$ ./profile.php?id=$1

But this works

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*?)/edit/([a-z0-9_-]+)$ $1/editpost.php?id=$2 [L,QSA]
RewriteRule ^(.*?)/([a-z0-9_-]+)$ $1/post?id=$2 [L,QSA]

#RewriteRule ^users/(\d+)*$ ./profile.php?id=$1

I simply re-arranged the rewrite rule and it fixed the issue. Can anyone explain why this happened? I was stuck in this for more than 2 hrs.

I am new to URL rewriting so please explain in detail. And what actually [L, QSA] does?

Body:
RewriteCond is only applicable to nearest RewriteRule. So in your first example it is applied to only this rule:

RewriteRule ^(.*?)/([a-z0-9_-]+)$ $1/post?id=$2 [L,QSA]

Two bottom RewriteRule are executed without any RewriteCond and cause infinite loop.

You can have your rules as:

RewriteEngine On
RewriteBase /

# skip all files and directories from rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^(.*?)/edit/([\w-]+)/?$ $1/editpost.php?id=$2 [L,QSA]

RewriteRule ^users/(\d+)/?$ profile.php?id=$1 [L,QSA]

RewriteRule ^(.*?)/([\w-]+)/?$ $1/post?id=$2 [L,QSA]


问:
DataGridView retrieve entire row
I'm using CellClick to open a message box and show the row contents of a single row from a DataGridView in a form. I was stumped in trying to find something more elegant than what I've got so far. I was searching for a way to display the contents of the column header, and the row value, possibly using foreach or a for loop, but no avail. Any recommendations?</p>

```<code>private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (authorDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show("Author Number: " + authorDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()
                + "\nAuthor First Name: " + authorDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()
                + "\nAuthor Last Name: " + authorDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString());
        }
    }
</code>```

答:
You could add a Show method in the Model-Class of the Objects you are Displaying in your Dgv:

```<code>public class Author
{
  public int Number { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }

  public void Show()
  {
    MessageBox.Show($"Author Number: {Number}\nAuthor First Name: {FirstName}\nAuthor Last Name: {LastName}");
  }
</code>```

This way you can easily call it in your CellClick-Method

```<code>private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
  var author = ((DataGridView)sender).Rows[e.RowIndex].DataBoundObject
  //now you have an author-type object and just call your show method
  author.Show()
}
</code>```

as far as you get your items into the Dgv by using the DataSource prop, you can always get them back again with the DataBoundObject Property.

Title: DataGridView retrieve entire row

Body:
I'm using CellClick to open a message box and show the row contents of a single row from a DataGridView in a form. I was stumped in trying to find something more elegant than what I've got so far. I was searching for a way to display the contents of the column header, and the row value, possibly using foreach or a for loop, but no avail. Any recommendations?

private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (authorDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show("Author Number: " + authorDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()
                + "\nAuthor First Name: " + authorDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()
                + "\nAuthor Last Name: " + authorDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString());
        }
    }

Body:
You could add a Show method in the Model-Class of the Objects you are Displaying in your Dgv:

public class Author
{
  public int Number { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }

  public void Show()
  {
    MessageBox.Show($"Author Number: {Number}\nAuthor First Name: {FirstName}\nAuthor Last Name: {LastName}");
  }

This way you can easily call it in your CellClick-Method

private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
  var author = ((DataGridView)sender).Rows[e.RowIndex].DataBoundObject
  //now you have an author-type object and just call your show method
  author.Show()
}

as far as you get your items into the Dgv by using the DataSource prop, you can always get them back again with the DataBoundObject Property.


问:
How do i convert the following xml based spring bean to java annotation based beans?
```<code> <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>
</code>```

I want to convert this to java annotation based bean (@Bean).

答:
One more option

```<code>   @Bean
public com.ce.indiabringsService getIndiabringsService(com.ce.indiabrings.consumer
 consumerBean,com.ce.indiabrings.value.function functionBean){
 indiabringsService indiabringsServiceBean =new indiabringsService();
 indiabringsServiceBean.setConsumer(consumerBean);
 indiabringsServiceBean.setFunction(functionBean);
 return indiabringsServiceBean;
}
</code>```

you can inject indiabringsService by using @Autowired.

for creating indiabringsService  bean, Internally  spring will automatically inject consumer  and function  beans while creating indiabringsService  bean.

Body:
 <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>

I want to convert this to java annotation based bean (@Bean).

Body:
One more option

   @Bean
public com.ce.indiabringsService getIndiabringsService(com.ce.indiabrings.consumer
 consumerBean,com.ce.indiabrings.value.function functionBean){
 indiabringsService indiabringsServiceBean =new indiabringsService();
 indiabringsServiceBean.setConsumer(consumerBean);
 indiabringsServiceBean.setFunction(functionBean);
 return indiabringsServiceBean;
}

you can inject indiabringsService by using @Autowired.

for creating indiabringsService  bean, Internally  spring will automatically inject consumer  and function  beans while creating indiabringsService  bean.


问:
while loop condition needs to check if dictionary contains items and return to main menu if not
I have the following code:
https://repl.it/JRi4/2
in which I am trying to implement a while loop in the searchplayer() sub.

Basically, I need to check to see if the dictionary player_info is full, and only then continue with the search. If it is empty (no items in player_info) then it needs to print "Add player details" and return to the mainmenu()

The code in question is here:

```<code>def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   mainmenu()

main()
</code>```

I have tried the following, that does not work:

```<code>def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   while player_info:
     if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   print("Nothing in player_info")
   mainmenu()

main()
</code>```

Error

```<code>player_info not defined
</code>```

The error suggests player_info is not defined, but it has been declared as a global variable

答:
Assuming your player_info really is defined globally, here's a code to loop until a name is entered which exists in the player_info dictionary, or to fail with explanation if player_info is empty initially:

```<code>def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   while len(player_info) > 0:
       print("Please enter a valid player name:")
       name = input("Player name : ")
       if name in player_info.keys():
           print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
           break
   else:
       print("No players found. Please add some first.")
   print()
   mainmenu()
</code>```

Update. To remove recursion you must wrap your menu with an infinite loop (you're exiting with sys.exit, or simply with break, if this is called directly from main):

```<code>def mainmenu():
    while True:
        choice = int(input("Enter choice:"))
        if choice == 1:
            addplayers()
        elif choice == 2:
            searchplayer()
        elif choice == 3:
            update()
        elif choice == 4:
            viewall()
        elif choice == 5:
            sys.exit()
        else:
            print("You must make a valid choice - 1, 2 or 3")
</code>```

Now you can simply remove all occurrences of calls to mainmenu() from choice handling functions (last line in viewall, update, addplayers and searchplayer).

Body:
I have the following code:
https://repl.it/JRi4/2
in which I am trying to implement a while loop in the searchplayer() sub.

Basically, I need to check to see if the dictionary player_info is full, and only then continue with the search. If it is empty (no items in player_info) then it needs to print "Add player details" and return to the mainmenu()

The code in question is here:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   mainmenu()

main()

I have tried the following, that does not work:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   name = input("Player name : ")
   while player_info:
     if name in player_info.keys():
     #print student_info
      print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
   else:
      print("Please enter a valid player name:")
   print()
   print("Nothing in player_info")
   mainmenu()

main()

Error

player_info not defined

The error suggests player_info is not defined, but it has been declared as a global variable

Body:
Assuming your player_info really is defined globally, here's a code to loop until a name is entered which exists in the player_info dictionary, or to fail with explanation if player_info is empty initially:

def searchplayer():
   print("===============SEARCH by player: Calculate average goals==================")
   while len(player_info) > 0:
       print("Please enter a valid player name:")
       name = input("Player name : ")
       if name in player_info.keys():
           print ("Average player goals : ", str(sum(player_info[name].values())/3.0))
           break
   else:
       print("No players found. Please add some first.")
   print()
   mainmenu()

Update. To remove recursion you must wrap your menu with an infinite loop (you're exiting with sys.exit, or simply with break, if this is called directly from main):

def mainmenu():
    while True:
        choice = int(input("Enter choice:"))
        if choice == 1:
            addplayers()
        elif choice == 2:
            searchplayer()
        elif choice == 3:
            update()
        elif choice == 4:
            viewall()
        elif choice == 5:
            sys.exit()
        else:
            print("You must make a valid choice - 1, 2 or 3")

Now you can simply remove all occurrences of calls to mainmenu() from choice handling functions (last line in viewall, update, addplayers and searchplayer).


问:
MySQL composite index for OR condition
I have a huge table on which I want to run a query with an or condition

```<code>SELECT id, upload_key
FROM product_data
WHERE (status = 0 or updated = 0) and uploaded_on is NULL;
</code>```

The table is more than 50 million records now and takes minutes to execute. I tried creating a composite index on keys status, updated and uploaded_on (in the same order as query) but it as turns out, the query doesn't use composite indexes with an OR on two different columns.

Is there a way to create indexes to optimize the query, or should I just move uploaded_on as the first where clause and create an single column index on the same?

答:
Write the query using union all:

```<code>SELECT id, upload_key
FROM product_data
WHERE status = 0 and uploaded_on is NULL
UNION ALL
SELECT id, upload_key
FROM product_data
WHERE status <> 0 and updated = 0 and uploaded_on is NULL;
</code>```

You want two indexes:  (status, uploaded_on) and (updated, uploaded_on, status).

Title: MySQL composite index for OR condition

Body:
I have a huge table on which I want to run a query with an or condition

SELECT id, upload_key
FROM product_data
WHERE (status = 0 or updated = 0) and uploaded_on is NULL;

The table is more than 50 million records now and takes minutes to execute. I tried creating a composite index on keys status, updated and uploaded_on (in the same order as query) but it as turns out, the query doesn't use composite indexes with an OR on two different columns.

Is there a way to create indexes to optimize the query, or should I just move uploaded_on as the first where clause and create an single column index on the same?

Body:
Write the query using union all:

SELECT id, upload_key
FROM product_data
WHERE status = 0 and uploaded_on is NULL
UNION ALL
SELECT id, upload_key
FROM product_data
WHERE status <> 0 and updated = 0 and uploaded_on is NULL;

You want two indexes:  (status, uploaded_on) and (updated, uploaded_on, status).


问:
"sh: Error: Can't open display" when I try to start a program from python
I have this really strange problem, basically I want to start xpdf (or Libreoffice) from my Python script, that is started by a systemd-service. When I start the script from terminal everything is working fine, but when I plug in my USB device that start the Service, I'll get this Error in my syslog:

```<code>sh[2321]: Error: Can't open Display
</code>```

This error has something to do with X11, that's what my Google searches tell me.
So, my question is: How can I properly run a program like xpdf or libreoffice from Python?

```<code> import subprocess
 subprocess.call("/usr/bin/xpdf")
</code>```

This is it, basically. I know that it has something to do with the graphical enviroment, but I don't know how I can solve it.

答:
The X display system has very good security to stop random local processes from just displaying stuff to the local screen (It was more a problem in the old days of expensive Sun and SGI systems where computer labs would often let users telnet to other boxes. Much fun could be had!).

If the user running the xpdf is the same user as the one who's logged into the X session, then you simply need to tell xpdf where to connect it's UI to. This is usually done by exporting DISPLAY=:0 to the environment, which means "connect to the first local screen". Most X programs also support -display :0 argument.

So do:

```<code>/usr/bin/xpdf -display :0
</code>```

or:

```<code>DISPLAY=:0 /usr/bin/xpdf
</code>```

It's very unlikely that you have more than one X session so :0 will work 99% of the time.

Body:
I have this really strange problem, basically I want to start xpdf (or Libreoffice) from my Python script, that is started by a systemd-service. When I start the script from terminal everything is working fine, but when I plug in my USB device that start the Service, I'll get this Error in my syslog:

sh[2321]: Error: Can't open Display

This error has something to do with X11, that's what my Google searches tell me.
So, my question is: How can I properly run a program like xpdf or libreoffice from Python?

 import subprocess
 subprocess.call("/usr/bin/xpdf")

This is it, basically. I know that it has something to do with the graphical enviroment, but I don't know how I can solve it.

Body:
The X display system has very good security to stop random local processes from just displaying stuff to the local screen (It was more a problem in the old days of expensive Sun and SGI systems where computer labs would often let users telnet to other boxes. Much fun could be had!).

If the user running the xpdf is the same user as the one who's logged into the X session, then you simply need to tell xpdf where to connect it's UI to. This is usually done by exporting DISPLAY=:0 to the environment, which means "connect to the first local screen". Most X programs also support -display :0 argument.

So do:

/usr/bin/xpdf -display :0

or:

DISPLAY=:0 /usr/bin/xpdf

It's very unlikely that you have more than one X session so :0 will work 99% of the time.


问:
undefined is not an object (evaluating '_this.props.navigator.push') react native , when i am trying to navigate from one page to another
Here is the sample code , i am trying react-native-navigation

i used react-native init navigate to start the project
  and afterwards i installed

yarn add react-native-navigation@latest

the code run perfect for first screen , but as i am making a call to showNextScreen function it throws the error

undefined is not an object (evaluating 'this.props.navigator.push') react native

```<code>  import React, { Component } from 'react';
    import {
      AppRegistry,
      StyleSheet,
      Text,
      View
    } from 'react-native';
    import {Navigation} from 'react-native-navigation';
    import firstPage  from './app/components/firstPage';
    export default class navigate extends Component {
    //function to move to next screen
      showNextScreen = () =>{
        this.props.navigator.push({
          screen: 'firstPage',
          title: 'firstScreen'
        })
      }
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
              To get started, edit index.android.js
            </Text>
            <Text onPress={this.showNextScreen.bind(this)}
            style={styles.instructions}>
              Double tap R on your keyboard to reload,{'\n'}
              Shake or press menu button for dev menu
            </Text>
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
      instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
    });

    AppRegistry.registerComponent('navigate', () => navigate);
</code>```

答:
Using React Native Navigation, you have to bootstrap your app differently than how it's done originally. Native Navigation doesn't use the registerComponent setup since it's a native navigator.

The steps to fully setting up are listed in their docs https://wix.github.io/react-native-navigation/#/usage

Body:
Here is the sample code , i am trying react-native-navigation

i used react-native init navigate to start the project
  and afterwards i installed

yarn add react-native-navigation@latest

the code run perfect for first screen , but as i am making a call to showNextScreen function it throws the error

undefined is not an object (evaluating 'this.props.navigator.push') react native

  import React, { Component } from 'react';
    import {
      AppRegistry,
      StyleSheet,
      Text,
      View
    } from 'react-native';
    import {Navigation} from 'react-native-navigation';
    import firstPage  from './app/components/firstPage';
    export default class navigate extends Component {
    //function to move to next screen
      showNextScreen = () =>{
        this.props.navigator.push({
          screen: 'firstPage',
          title: 'firstScreen'
        })
      }
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
              To get started, edit index.android.js
            </Text>
            <Text onPress={this.showNextScreen.bind(this)}
            style={styles.instructions}>
              Double tap R on your keyboard to reload,{'\n'}
              Shake or press menu button for dev menu
            </Text>
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
      instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
    });

    AppRegistry.registerComponent('navigate', () => navigate);


问:
How to access data returned from Ajax post method call with index just like an array
Here is my code and it is not working to success function. Is there a possibility that I am not specifying in the right way tr and td elements

```<code>$(document).ready(function () {
    $("#search").blur(function () {
        //alert("ilir");
        $.ajax({
            type: "POST",
            data: { "barkodi": $(this).val() },
            dataType: 'json',
            success: function (data) {
                $('tr[class!="info"]').remove().after(function () {
                    $.each(function (index, data) {
                        $("tr").append(
                            $("<tr></tr>").html(
                            $("<td></td>").text(data[0].Barkodi),
                            $("<td></td>").text(data[0].Emri),
                            $("<td></td>").text(data[0].Cmimi),
                            $("<td></td>").text(data[0].Sasia))
                            );
                    });
                });
            }
        });
    });
})
</code>```

And here is my controller and action method I dont where is my bug here :(

```<code>[HttpPost]
    [AllowAnonymous]
    public JsonResult Index(string barkodi)
    {
        var produkti = _context.Produktets.SingleOrDefault(x => x.Barkodi == barkodi);

        List<ProduktetCustom> prod = new List<ProduktetCustom>();
        ProduktetCustom produkt = new ProduktetCustom()
        {
            Barkodi = produkti.Barkodi,
            Emri = produkti.Emri,
            Sasia = produkti.Sasia,
            Cmimi = produkti.Cmimi,
            Pershkrimi = produkti.Pershkrimi,
            IsDeleted = produkti.IsDeleted,
            DataModifikimit = produkti.DataModifikimit,
            DataShtimit = produkti.DataShtimit
        };

        prod.Add(produkt);
        return Json(prod,JsonRequestBehavior.AllowGet);
    }
</code>```

答:
Not tested but you can try parseJSON.

```<code>var objArray = $.parseJSON(data);
$.each(function (index, objArray) {
//other stuff
});
</code>```

Body:
Here is my code and it is not working to success function. Is there a possibility that I am not specifying in the right way tr and td elements

$(document).ready(function () {
    $("#search").blur(function () {
        //alert("ilir");
        $.ajax({
            type: "POST",
            data: { "barkodi": $(this).val() },
            dataType: 'json',
            success: function (data) {
                $('tr[class!="info"]').remove().after(function () {
                    $.each(function (index, data) {
                        $("tr").append(
                            $("

").html(
                            $("	").text(data[0].Barkodi),
                            $("	").text(data[0].Emri),
                            $("	").text(data[0].Cmimi),
                            $("	").text(data[0].Sasia))
                            );
                    });
                });
            }
        });
    });
})

And here is my controller and action method I dont where is my bug here :(

[HttpPost]
    [AllowAnonymous]
    public JsonResult Index(string barkodi)
    {
        var produkti = _context.Produktets.SingleOrDefault(x => x.Barkodi == barkodi);

        List<ProduktetCustom> prod = new List<ProduktetCustom>();
        ProduktetCustom produkt = new ProduktetCustom()
        {
            Barkodi = produkti.Barkodi,
            Emri = produkti.Emri,
            Sasia = produkti.Sasia,
            Cmimi = produkti.Cmimi,
            Pershkrimi = produkti.Pershkrimi,
            IsDeleted = produkti.IsDeleted,
            DataModifikimit = produkti.DataModifikimit,
            DataShtimit = produkti.DataShtimit
        };

        prod.Add(produkt);
        return Json(prod,JsonRequestBehavior.AllowGet);
    }

Body:
Not tested but you can try parseJSON.

var objArray = $.parseJSON(data);
$.each(function (index, objArray) {
//other stuff
});


问:
How to hide the line number with Google Test
I'm trying to hide the line number in the console GTest ouput if a test failed.

For example in:

```<code>/Projects/Dya/tests/main.cpp:22: Failure
      Expected: object->calc(expr, params)
      Which is: "5" To be equal to: "2"
</code>```

I'd like to hide this:

```<code>/Projects/Dya/tests/main.cpp:22:
</code>```

Is that possible?

Thanks for your answers.

答:
I'm pretty sure you cannot.  I see an option for hiding elapsed time and turning off colorized output, but nothing for filenames.

If you run your test program with the -h flag it will show you the list of supported options.  Here's what I get:

```<code>This program contains tests written using Google Test. You can use the
following command line flags to control its behavior:

Test Selection:
  --gtest_list_tests
      List the names of all tests instead of running them. The name of
      TEST(Foo, Bar) is "Foo.Bar".
  --gtest_filter=POSTIVE_PATTERNS[-NEGATIVE_PATTERNS]
      Run only the tests whose name matches one of the positive patterns but
      none of the negative patterns. '?' matches any single character; '*'
      matches any substring; ':' separates two patterns.
  --gtest_also_run_disabled_tests
      Run all disabled tests too.

Test Execution:
  --gtest_repeat=[COUNT]
      Run the tests repeatedly; use a negative count to repeat forever.
  --gtest_shuffle
      Randomize tests' orders on every iteration.
  --gtest_random_seed=[NUMBER]
      Random number seed to use for shuffling test orders (between 1 and
      99999, or 0 to use a seed based on the current time).

Test Output:
  --gtest_color=(yes|no|auto)
      Enable/disable colored output. The default is auto.
  --gtest_print_time=0
      Don't print the elapsed time of each test.
  --gtest_output=xml[:DIRECTORY_PATH/|:FILE_PATH]
      Generate an XML report in the given directory or with the given file
      name. FILE_PATH defaults to test_details.xml.

Assertion Behavior:
  --gtest_death_test_style=(fast|threadsafe)
      Set the default death test style.
  --gtest_break_on_failure
      Turn assertion failures into debugger break-points.
  --gtest_throw_on_failure
      Turn assertion failures into C++ exceptions.
  --gtest_catch_exceptions=0
      Do not report exceptions as test failures. Instead, allow them
      to crash the program or throw a pop-up (on Windows).

Except for --gtest_list_tests, you can alternatively set the corresponding
environment variable of a flag (all letters in upper-case). For example, to
disable colored text output, you can either specify --gtest_color=no or set
the GTEST_COLOR environment variable to no.

For more information, please read the Google Test documentation at
https://github.com/google/googletest/. If you find a bug in Google Test
(not one in your own code or tests), please report it to
<googletestframework@googlegroups.com>.
</code>```

Body:
I'm trying to hide the line number in the console GTest ouput if a test failed.

For example in:

/Projects/Dya/tests/main.cpp:22: Failure
      Expected: object->calc(expr, params)
      Which is: "5" To be equal to: "2"

I'd like to hide this:

/Projects/Dya/tests/main.cpp:22:

Is that possible?

Thanks for your answers.

Body:
I'm pretty sure you cannot.  I see an option for hiding elapsed time and turning off colorized output, but nothing for filenames.

If you run your test program with the -h flag it will show you the list of supported options.  Here's what I get:

This program contains tests written using Google Test. You can use the
following command line flags to control its behavior:

Test Selection:
  --gtest_list_tests
      List the names of all tests instead of running them. The name of
      TEST(Foo, Bar) is "Foo.Bar".
  --gtest_filter=POSTIVE_PATTERNS[-NEGATIVE_PATTERNS]
      Run only the tests whose name matches one of the positive patterns but
      none of the negative patterns. '?' matches any single character; '*'
      matches any substring; ':' separates two patterns.
  --gtest_also_run_disabled_tests
      Run all disabled tests too.

Test Execution:
  --gtest_repeat=[COUNT]
      Run the tests repeatedly; use a negative count to repeat forever.
  --gtest_shuffle
      Randomize tests' orders on every iteration.
  --gtest_random_seed=[NUMBER]
      Random number seed to use for shuffling test orders (between 1 and
      99999, or 0 to use a seed based on the current time).

Test Output:
  --gtest_color=(yes|no|auto)
      Enable/disable colored output. The default is auto.
  --gtest_print_time=0
      Don't print the elapsed time of each test.
  --gtest_output=xml[:DIRECTORY_PATH/|:FILE_PATH]
      Generate an XML report in the given directory or with the given file
      name. FILE_PATH defaults to test_details.xml.

Assertion Behavior:
  --gtest_death_test_style=(fast|threadsafe)
      Set the default death test style.
  --gtest_break_on_failure
      Turn assertion failures into debugger break-points.
  --gtest_throw_on_failure
      Turn assertion failures into C++ exceptions.
  --gtest_catch_exceptions=0
      Do not report exceptions as test failures. Instead, allow them
      to crash the program or throw a pop-up (on Windows).

Except for --gtest_list_tests, you can alternatively set the corresponding
environment variable of a flag (all letters in upper-case). For example, to
disable colored text output, you can either specify --gtest_color=no or set
the GTEST_COLOR environment variable to no.

For more information, please read the Google Test documentation at
https://github.com/google/googletest/. If you find a bug in Google Test
(not one in your own code or tests), please report it to
<googletestframework@googlegroups.com>.


问:
How to create a query dynamically for an array of elements?
I have a basic query as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
</code>```

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

```<code>$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
</code>```

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
</code>```

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

答:
```<code>SELECT * FROM files WHERE subject_code in ('SC1','SC2')
</code>```

Body:
I have a basic query as follows

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?


问:
How to animate UILabel?
I'm using UILabel to display some dynamic text. Sometime its over lap the width of the label. I want to slide the text if the UILabel goes out of bound.

How do I do the sliding animation with UILabel? Any help?

答:
```<code>-(void)repeat{

[NSTimer scheduledTimerWithTimeInterval:8.0
                                     target:self
                                   selector:@selector(LabelAnimation)
                                   userInfo:nil
                                    repeats:YES];

}

-(void)LabelAnimation
{

 NSArray *elements = [yourText componentsSeparatedByString:@","];
    NSMutableArray *outputElements = [[NSMutableArray alloc] init];
    for (int i=1;i<[elements count];i++)

            [outputElements addObject:[elements objectAtIndex:i]];

    NSString *outputString = [outputElements componentsJoinedByString:@","];

    [UIView animateWithDuration:3.0f delay:0.2f options:UIViewAnimationOptionTransitionNone animations:^{

        _header.labelHeaderName.text=outputString;
    } completion:^(BOOL finished)
     {
         if (outputString.length == 0) {
            _header.labelHeaderName.text=_strAddress(your saved address);
         }

     }];
    }
</code>```

Title: How to animate UILabel?


问:
Javascript unwanted lines connecting moving arcs
So i have this basic script which makes 4 circles move around a centre, and I have put in two circles which are the route which the circles follow.. The problem is that there's odd unwanted lines joining the circles to the stationary one's. I think it may be because the line for the circles ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI); is within the draw function. Does anyone know how to solve this? (Placing the stationary circles outside the draw function causes them to disappear when the canvas is cleared.

```<code>var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var dd = 3;
var dd2 = 3;
var dd3 = 3;
var dd4 = 3;
var angle = 0;
var angle2 = 0;
var angle3 = 0;
var angle4 = 0;
var cx = 1000;
var cy = 1000;
var radius = 200;
var radius2 = 300;
var radius3 = 400;
var radius4 = 500;
var fps = 100;
ctx.fillStyle = "yellow";
ctx.strokeStyle = "skyblue";
(function () {
    "use strict";
    function draw(x, y) {
        ctx.save();
        ctx.clearRect(0, 0, w, h);
        ctx.beginPath();
        ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
        ctx.fillStyle = "lightgray";
        ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    function draw1(x1, y1) {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = "orange";
        ctx.arc((x1 - 50 / 2) + 25, (y1 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 300, 300, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    function draw2(x2, y2) {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = "blue";
        ctx.arc((x2 - 50 / 2) + 25, (y2 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 400, 400, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    function draw3(x3, y3) {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = "red";
        ctx.arc((x3 - 50 / 2) + 25, (y3 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 500, 500, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / fps);
        };
    }());

    function animate() {
        setTimeout(function () {
            requestAnimFrame(animate);
            ctx.beginPath();
            angle += Math.acos(1 - Math.pow(dd / radius, 2) / 2);
            var newX = cx + radius * Math.cos(angle),
                newY = cy + radius * Math.sin(angle),
                newX1 = cx + radius2 * Math.cos(angle2),
                newY1 = cy + radius2 * Math.sin(angle2),
                newX2 = cx + radius3 * Math.cos(angle3),
                newY2 = cy + radius3 * Math.sin(angle3),
            newX3 = cx + radius4 * Math.cos(angle4),
                newY3 = cy + radius4 * Math.sin(angle4);
            draw(newX, newY);
            ctx.arc(cx, cy, radius, 0, Math.PI * 2);
            ctx.closePath();
            ctx.beginPath();
            angle2 += Math.acos(1 - Math.pow(dd2 / radius2, 2) / 2);
            draw1(newX1, newY1);
            ctx.arc(cx, cy, radius2, 0, 2 * Math.PI);
            ctx.closePath();
            ctx.beginPath();
            angle3 += Math.acos(1 - Math.pow(dd3 / radius3, 2) / 2);
            draw2(newX2, newY2);
            ctx.arc(cx, cy, radius3, 0, 2 * Math.PI);
            ctx.closePath();
            ctx.beginPath();
            angle4 += Math.acos(1 - Math.pow(dd4 / radius4, 2) / 2);
            draw3(newX3, newY3);
            ctx.arc(cx, cy, radius4, 0, 2 * Math.PI);
            ctx.closePath();
        }, 1000 / fps);
    }
    animate();
}());
</code>```

答:
You have to use ctx.beginPath(), ctx.closePath() and ctx.stroke() for EVERY arc you create, else it will connect them with lines (as you yourself also would have to, if you were drawing and were not allowed to take the pencil off the paper):

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var dd = 3;
var dd2 = 3;
var dd3 = 3;
var dd4 = 3;
var angle = 0;
var angle2 = 0;
var angle3 = 0;
var angle4 = 0;
var cx = 1000;
var cy = 1000;
var radius = 200;
var radius2 = 300;
var radius3 = 400;
var radius4 = 500;
var fps = 100;
ctx.fillStyle = "yellow";
ctx.strokeStyle = "skyblue";
(function () {
    "use strict";
    function draw(x, y) {
        ctx.save();
        ctx.clearRect(0, 0, w, h);
        ctx.beginPath();
        ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.fillStyle = "lightgray";
        ctx.beginPath();
        ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    function draw1(x1, y1) {
        ctx.save();
        ctx.fillStyle = "orange";
        ctx.beginPath();
        ctx.arc((x1 - 50 / 2) + 25, (y1 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 300, 300, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    function draw2(x2, y2) {
        ctx.save();
        ctx.fillStyle = "blue";
        ctx.beginPath();
        ctx.arc((x2 - 50 / 2) + 25, (y2 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 400, 400, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    function draw3(x3, y3) {
        ctx.save();
        ctx.fillStyle = "red";
        ctx.beginPath();
        ctx.arc((x3 - 50 / 2) + 25, (y3 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 500, 500, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / fps);
        };
    }());

    function animate() {
        setTimeout(function () {
            requestAnimFrame(animate);
            angle += Math.acos(1 - Math.pow(dd / radius, 2) / 2);
            var newX = cx + radius * Math.cos(angle),
                newY = cy + radius * Math.sin(angle),
                newX1 = cx + radius2 * Math.cos(angle2),
                newY1 = cy + radius2 * Math.sin(angle2),
                newX2 = cx + radius3 * Math.cos(angle3),
                newY2 = cy + radius3 * Math.sin(angle3),
            newX3 = cx + radius4 * Math.cos(angle4),
                newY3 = cy + radius4 * Math.sin(angle4);
            draw(newX, newY);
            ctx.arc(cx, cy, radius, 0, Math.PI * 2);
            angle2 += Math.acos(1 - Math.pow(dd2 / radius2, 2) / 2);
            draw1(newX1, newY1);
            ctx.arc(cx, cy, radius2, 0, 2 * Math.PI);
            angle3 += Math.acos(1 - Math.pow(dd3 / radius3, 2) / 2);
            draw2(newX2, newY2);
            ctx.arc(cx, cy, radius3, 0, 2 * Math.PI);
            angle4 += Math.acos(1 - Math.pow(dd4 / radius4, 2) / 2);
            draw3(newX3, newY3);
            ctx.arc(cx, cy, radius4, 0, 2 * Math.PI);
        }, 1000 / fps);
    }
    animate();
}());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="2000" height="2000"></canvas></code>```

E.g. I changed the following:

```<code>ctx.beginPath();
ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
ctx.fillStyle = "lightgray";
ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
</code>```

Into this:

```<code>ctx.beginPath();
ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
ctx.closePath(); //Added
ctx.stroke();    //Added
ctx.fillStyle = "lightgray";
ctx.beginPath(); //Added
ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
ctx.closePath(); //Added
ctx.stroke();    //Added
ctx.beginPath(); //Added
ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
ctx.closePath(); //Reversed order (doesn't really matter, but looks better IMO)
ctx.stroke();    //Reversed order (doesn't really matter, but looks better IMO)
</code>```

Body:
So i have this basic script which makes 4 circles move around a centre, and I have put in two circles which are the route which the circles follow.. The problem is that there's odd unwanted lines joining the circles to the stationary one's. I think it may be because the line for the circles ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI); is within the draw function. Does anyone know how to solve this? (Placing the stationary circles outside the draw function causes them to disappear when the canvas is cleared.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var dd = 3;
var dd2 = 3;
var dd3 = 3;
var dd4 = 3;
var angle = 0;
var angle2 = 0;
var angle3 = 0;
var angle4 = 0;
var cx = 1000;
var cy = 1000;
var radius = 200;
var radius2 = 300;
var radius3 = 400;
var radius4 = 500;
var fps = 100;
ctx.fillStyle = "yellow";
ctx.strokeStyle = "skyblue";
(function () {
    "use strict";
    function draw(x, y) {
        ctx.save();
        ctx.clearRect(0, 0, w, h);
        ctx.beginPath();
        ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
        ctx.fillStyle = "lightgray";
        ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    function draw1(x1, y1) {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = "orange";
        ctx.arc((x1 - 50 / 2) + 25, (y1 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 300, 300, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    function draw2(x2, y2) {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = "blue";
        ctx.arc((x2 - 50 / 2) + 25, (y2 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 400, 400, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    function draw3(x3, y3) {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = "red";
        ctx.arc((x3 - 50 / 2) + 25, (y3 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.arc(cx, cy, 500, 500, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
    window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / fps);
        };
    }());

    function animate() {
        setTimeout(function () {
            requestAnimFrame(animate);
            ctx.beginPath();
            angle += Math.acos(1 - Math.pow(dd / radius, 2) / 2);
            var newX = cx + radius * Math.cos(angle),
                newY = cy + radius * Math.sin(angle),
                newX1 = cx + radius2 * Math.cos(angle2),
                newY1 = cy + radius2 * Math.sin(angle2),
                newX2 = cx + radius3 * Math.cos(angle3),
                newY2 = cy + radius3 * Math.sin(angle3),
            newX3 = cx + radius4 * Math.cos(angle4),
                newY3 = cy + radius4 * Math.sin(angle4);
            draw(newX, newY);
            ctx.arc(cx, cy, radius, 0, Math.PI * 2);
            ctx.closePath();
            ctx.beginPath();
            angle2 += Math.acos(1 - Math.pow(dd2 / radius2, 2) / 2);
            draw1(newX1, newY1);
            ctx.arc(cx, cy, radius2, 0, 2 * Math.PI);
            ctx.closePath();
            ctx.beginPath();
            angle3 += Math.acos(1 - Math.pow(dd3 / radius3, 2) / 2);
            draw2(newX2, newY2);
            ctx.arc(cx, cy, radius3, 0, 2 * Math.PI);
            ctx.closePath();
            ctx.beginPath();
            angle4 += Math.acos(1 - Math.pow(dd4 / radius4, 2) / 2);
            draw3(newX3, newY3);
            ctx.arc(cx, cy, radius4, 0, 2 * Math.PI);
            ctx.closePath();
        }, 1000 / fps);
    }
    animate();
}());

Body:
You have to use ctx.beginPath(), ctx.closePath() and ctx.stroke() for EVERY arc you create, else it will connect them with lines (as you yourself also would have to, if you were drawing and were not allowed to take the pencil off the paper):

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var dd = 3;
var dd2 = 3;
var dd3 = 3;
var dd4 = 3;
var angle = 0;
var angle2 = 0;
var angle3 = 0;
var angle4 = 0;
var cx = 1000;
var cy = 1000;
var radius = 200;
var radius2 = 300;
var radius3 = 400;
var radius4 = 500;
var fps = 100;
ctx.fillStyle = "yellow";
ctx.strokeStyle = "skyblue";
(function () {
    "use strict";
    function draw(x, y) {
        ctx.save();
        ctx.clearRect(0, 0, w, h);
        ctx.beginPath();
        ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.fillStyle = "lightgray";
        ctx.beginPath();
        ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    function draw1(x1, y1) {
        ctx.save();
        ctx.fillStyle = "orange";
        ctx.beginPath();
        ctx.arc((x1 - 50 / 2) + 25, (y1 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 300, 300, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    function draw2(x2, y2) {
        ctx.save();
        ctx.fillStyle = "blue";
        ctx.beginPath();
        ctx.arc((x2 - 50 / 2) + 25, (y2 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 400, 400, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    function draw3(x3, y3) {
        ctx.save();
        ctx.fillStyle = "red";
        ctx.beginPath();
        ctx.arc((x3 - 50 / 2) + 25, (y3 - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(cx, cy, 500, 500, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
    window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / fps);
        };
    }());

    function animate() {
        setTimeout(function () {
            requestAnimFrame(animate);
            angle += Math.acos(1 - Math.pow(dd / radius, 2) / 2);
            var newX = cx + radius * Math.cos(angle),
                newY = cy + radius * Math.sin(angle),
                newX1 = cx + radius2 * Math.cos(angle2),
                newY1 = cy + radius2 * Math.sin(angle2),
                newX2 = cx + radius3 * Math.cos(angle3),
                newY2 = cy + radius3 * Math.sin(angle3),
            newX3 = cx + radius4 * Math.cos(angle4),
                newY3 = cy + radius4 * Math.sin(angle4);
            draw(newX, newY);
            ctx.arc(cx, cy, radius, 0, Math.PI * 2);
            angle2 += Math.acos(1 - Math.pow(dd2 / radius2, 2) / 2);
            draw1(newX1, newY1);
            ctx.arc(cx, cy, radius2, 0, 2 * Math.PI);
            angle3 += Math.acos(1 - Math.pow(dd3 / radius3, 2) / 2);
            draw2(newX2, newY2);
            ctx.arc(cx, cy, radius3, 0, 2 * Math.PI);
            angle4 += Math.acos(1 - Math.pow(dd4 / radius4, 2) / 2);
            draw3(newX3, newY3);
            ctx.arc(cx, cy, radius4, 0, 2 * Math.PI);
        }, 1000 / fps);
    }
    animate();
}());

<canvas id="canvas" width="2000" height="2000"></canvas>

E.g. I changed the following:

ctx.beginPath();
ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
ctx.fillStyle = "lightgray";
ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();

Into this:

ctx.beginPath();
ctx.arc(cx, cy, 75, 75, 0, 2 * Math.PI);
ctx.closePath(); //Added
ctx.stroke();    //Added
ctx.fillStyle = "lightgray";
ctx.beginPath(); //Added
ctx.arc((x - 50 / 2) + 25, (y - 30 / 2) + 15, 25, 25, 0, 2 * Math.PI);
ctx.closePath(); //Added
ctx.stroke();    //Added
ctx.beginPath(); //Added
ctx.arc(cx, cy, 200, 200, 0, 2 * Math.PI);
ctx.closePath(); //Reversed order (doesn't really matter, but looks better IMO)
ctx.stroke();    //Reversed order (doesn't really matter, but looks better IMO)


问:
Pygame Making A Sprite Face The Mouse
Im New To Pygame But Kinda OK On Python, Im Creating A Zombie Shooting Game With an overhead view.

I managed to make the character move when pressing the arrow keys. But now i need to get the player to FACE the mouse/cursor without clicking the screen all the time.

Any Help?

答:
```<code>_, angle = (pg.mouse.get_pos()-self.pos).as_polar()
</code>```

This line first calculates a vector to the mouse position (self.pos has to be a pygame.math.Vector2) and .as_polar() returns the polar coordinates of the vector which consist of the radial distance and the angle. Finally use the negative angle (because pygame's y-axis is flipped) to rotate the image of the sprite and recalculate the rect.

```<code>import pygame as pg

class Player(pg.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((50, 30), pg.SRCALPHA)
        pg.draw.polygon(
            self.image,
            pg.Color('dodgerblue1'),
            ((1, 1), (49, 15), (1, 29)))
        self.orig_img = self.image
        self.rect = self.image.get_rect(center=pos)
        self.pos = pg.math.Vector2(pos)
        self.vel = pg.math.Vector2(0, 0)

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.center = self.pos

    def rotate(self):
        _, angle = (pg.mouse.get_pos()-self.pos).as_polar()
        self.image = pg.transform.rotozoom(self.orig_img, -angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    all_sprites.add(Player((300, 200)))

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
</code>```

math.atan2 can be used as an alternative.

```<code>def rotate(self):
    rel_x, rel_y = pg.mouse.get_pos() - self.pos
    angle = -math.degrees(math.atan2(rel_y, rel_x))
    self.image = pg.transform.rotozoom(self.orig_img, angle, 1)
    self.rect = self.image.get_rect(center=self.pos)
</code>```

Title: Pygame Making A Sprite Face The Mouse

Body:
_, angle = (pg.mouse.get_pos()-self.pos).as_polar()

This line first calculates a vector to the mouse position (self.pos has to be a pygame.math.Vector2) and .as_polar() returns the polar coordinates of the vector which consist of the radial distance and the angle. Finally use the negative angle (because pygame's y-axis is flipped) to rotate the image of the sprite and recalculate the rect.

import pygame as pg

class Player(pg.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((50, 30), pg.SRCALPHA)
        pg.draw.polygon(
            self.image,
            pg.Color('dodgerblue1'),
            ((1, 1), (49, 15), (1, 29)))
        self.orig_img = self.image
        self.rect = self.image.get_rect(center=pos)
        self.pos = pg.math.Vector2(pos)
        self.vel = pg.math.Vector2(0, 0)

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.center = self.pos

    def rotate(self):
        _, angle = (pg.mouse.get_pos()-self.pos).as_polar()
        self.image = pg.transform.rotozoom(self.orig_img, -angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    all_sprites.add(Player((300, 200)))

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

math.atan2 can be used as an alternative.

def rotate(self):
    rel_x, rel_y = pg.mouse.get_pos() - self.pos
    angle = -math.degrees(math.atan2(rel_y, rel_x))
    self.image = pg.transform.rotozoom(self.orig_img, angle, 1)
    self.rect = self.image.get_rect(center=self.pos)


问:
Bootstrap table not working good with ng-repeat
```<code><div ng-controller="reportCtrl">
      <table class="table table-hover">
          <thead class="row col-md-3">
              <tr class="row">
                  <th class="col-md-6">Key </th>
                  <th class="col-md-6"> Value</th>
              </tr>
          </thead>
          <tbody ng-repeat="param in params" class="row col-md-3">
              <tr class="row">
                  <td class="col-md-6 info">{{param.key}}</td>
                  <td class="col-md-6 info">{{param.val}}</td>
              </tr>
          </tbody>
      </table>
</div>
</code>```

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

答:
```<code><div ng-controller="reportCtrl">
  <table class="table table-hover">
     <div class="row col-md-3">
      <thead class="row">
          <tr>
              <th class="col-md-6">Key </th>
              <th class="col-md-6"> Value</th>
          </tr>
      </thead>
      <tbody ng-repeat="param in params">
          <tr class="row">
              <td class="col-md-6 info">{{param.key}}</td>
              <td class="col-md-6 info">{{param.val}}</td>
          </tr>
      </tbody>
    </div>
  </table>
</code>```

I have made few changes, like covered the entire table into 3 divisions and then

dividing them further into 6-6 for ths and tds. Just see if it works.

Body:
                  Key
                   Value

                  {{param.key}}
                  {{param.val}}

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

Body:
<div ng-controller="reportCtrl">
  <table class="table table-hover">
     <div class="row col-md-3">
      <thead class="row">
          <tr>
              <th class="col-md-6">Key </th>
              <th class="col-md-6"> Value</th>
          </tr>
      </thead>
      <tbody ng-repeat="param in params">
          <tr class="row">
              <td class="col-md-6 info">{{param.key}}</td>
              <td class="col-md-6 info">{{param.val}}</td>
          </tr>
      </tbody>
    </div>
  </table>

I have made few changes, like covered the entire table into 3 divisions and then

dividing them further into 6-6 for ths and tds. Just see if it works.


问:
Remove Custom button from Datatable

How can I remove the Copy, CSV, Excel, PDF and Print button on the top right corner. They are the default feature of datatables I suppose. I am trying to remove them but I did not find nay information on how can I remove or hide them.

Following is the code

```<code>oTable = $('#lenderList').dataTable(
        {
            bServerSide: true,
            bProcessing: true,
            searching: true,
            sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
            sServerMethod: 'POST',
            sPaginationType: "full_numbers",
            bPaginate: true,
            bLengthChange: true,
            bFilter: true,
            bSort: true,
            bInfo: true,
            bAutoWidth: true,

            aoColumns: [
                {
                    "sName": "loanApplicationNumber",
                    mData: "loanApplicationNumber"
                },
                {
                    "sName": "name",
                    mData: "name"
                },
                {
                    "sName": "submissionDate",
                    mData: "submissionDate"
                },
                {
                    "sName": "kycEmailId",
                    mData: "kycEmailId"
                },
                {
                    "sName": "appVersion",
                    mData: "appVersion"
                },
                {
                    "sName": "documentStatus",
                    mData: "documentStatus"
                },
                {
                    "sName": "latestRemark",
                    mData: "latestRemark"
                },
                {
                    "sName": "appName",
                    mData: "appName"
                }

            ],
            "dom": 'T<"clear"><"button">lfrtip'

        }
    );
</code>```

答: Well, if you cant remove them in normal way, you can inspect them in browser, then use their classes, ids to remove them by jquery</p>

Title: Remove Custom button from Datatable

Body:
How can I remove the Copy, CSV, Excel, PDF and Print button on the top right corner. They are the default feature of datatables I suppose. I am trying to remove them but I did not find nay information on how can I remove or hide them.

Following is the code

oTable = $('#lenderList').dataTable(
        {
            bServerSide: true,
            bProcessing: true,
            searching: true,
            sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
            sServerMethod: 'POST',
            sPaginationType: "full_numbers",
            bPaginate: true,
            bLengthChange: true,
            bFilter: true,
            bSort: true,
            bInfo: true,
            bAutoWidth: true,

            aoColumns: [
                {
                    "sName": "loanApplicationNumber",
                    mData: "loanApplicationNumber"
                },
                {
                    "sName": "name",
                    mData: "name"
                },
                {
                    "sName": "submissionDate",
                    mData: "submissionDate"
                },
                {
                    "sName": "kycEmailId",
                    mData: "kycEmailId"
                },
                {
                    "sName": "appVersion",
                    mData: "appVersion"
                },
                {
                    "sName": "documentStatus",
                    mData: "documentStatus"
                },
                {
                    "sName": "latestRemark",
                    mData: "latestRemark"
                },
                {
                    "sName": "appName",
                    mData: "appName"
                }

            ],
            "dom": 'T<"clear"><"button">lfrtip'

        }
    );


问:
excel pivot table - multiple label filters
Is there a way to exclude multiple labels in a pivot table?

I would like to exclude 3 channels from the channel column in the pivot table below. I thought Label Filter would do the trick but no luck so far...

Any suggestions?

答: As per my comment, you can build a slicer to select/deselect multiple items by holding ctrl whilst selecting with the mouse.


问:
Threading In VB 6 !
How can we achieve threading in VB 6?  Can someone illustrate with easy example?
Thankx in advance!</p>

答: You can use a timer to emulate threading. Not as efficient as actual threading, but I once designed a few applications (from VB 3.0 to VB 6.0) where I used that trick.</p>

Title: Threading In VB 6 !


问:
Angular 2 FormBuilder disable fields on checkbox select
I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows:

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

```<code><form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">
            </div>

        </div>

    </div>
</form>
</code>```

ts code

```<code>this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})
</code>```

Form has built inside the constructor.
How can I disable/enable the above fields on check box select.

答:
You need to write a callBack on click of checkbox like (click)="checkBoxClicked()" and in component define callback function as follows

```<code>checkBoxClicked() {
 if(!this.userProfileForm.controls.isResetPassword.value) {
   this.userProfileForm.controls.password.disable();
   this.userProfileForm.controls.newPassword.disable();
   this.userProfileForm.controls.reTypePassword.disable();
 }else {
   this.userProfileForm.controls.password.enable();
   this.userProfileForm.controls.newPassword.enable();
   this.userProfileForm.controls.reTypePassword.enable();
 }
}
</code>```

Body:
I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows:

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

<form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

                 {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">

                {{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">

                {{ 'USER_PROFILE_MODEL.EMAIL' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">

                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}

                {{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">

                {{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">

                {{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">

</form>

ts code

this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})

Form has built inside the constructor.
How can I disable/enable the above fields on check box select.

Body:
You need to write a callBack on click of checkbox like (click)="checkBoxClicked()" and in component define callback function as follows

checkBoxClicked() {
 if(!this.userProfileForm.controls.isResetPassword.value) {
   this.userProfileForm.controls.password.disable();
   this.userProfileForm.controls.newPassword.disable();
   this.userProfileForm.controls.reTypePassword.disable();
 }else {
   this.userProfileForm.controls.password.enable();
   this.userProfileForm.controls.newPassword.enable();
   this.userProfileForm.controls.reTypePassword.enable();
 }
}


问:
Redirecting output to file in batch file requires closing? (batch script)
In a batch script redirecting the output to a file like so

```<code>set "output=C:\output.txt"
echo Blah blah blah. >> %output%
</code>```

Is it required that the file is closed after the redirection of writing stuff to it is completed (similar to the approach in other programming languages)?

I have tried searching for related information online but could not find something on it; I assume the fact that most scripts are closed after they finish their tasks (commands) is maybe the reason why.

But if say a script is to run in an endless loop where a different output file is written (e.g. by appending the time to the output file name) or if new output is constantly being redirected to the same output file, could the "not closing of the file" potentially lead to problems, memory or other?

答:
No, you don't have to close any file handles in batch scripts. You don't know the file handle value so you could not even close it if you wanted to.

On Windows, all open kernel handles are closed when a process ends/crashes but since a batch file is interpreted by cmd.exe without starting a new cmd.exe process in most cases, it cannot take advantage of the automatic handle cleanup and will manually close the file handle after each redirected operation.

Body:
In a batch script redirecting the output to a file like so

set "output=C:\output.txt"
echo Blah blah blah. >> %output%

Is it required that the file is closed after the redirection of writing stuff to it is completed (similar to the approach in other programming languages)?

I have tried searching for related information online but could not find something on it; I assume the fact that most scripts are closed after they finish their tasks (commands) is maybe the reason why.

But if say a script is to run in an endless loop where a different output file is written (e.g. by appending the time to the output file name) or if new output is constantly being redirected to the same output file, could the "not closing of the file" potentially lead to problems, memory or other?


问:
Extract details from dir output in Windows XP using for loop (batch script)
I am trying to understand the for loop in batch scripting; in particular with skip and tokens parameters. I have found a great example in this answer followed by this nice read.

I would like to see how I can extract the date and time from a dir in Windows XP which has a slightly different dir output (see below example outputs) compared to Windows 7. In other words, how to extract creation date of a specific folder in Windows XP.

The following modified code from the above mentioned links correctly extracts the date and time of a DIR in Windows 7 but fails (i.e. extracts other characters) in Windows XP:

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set dirdate=%%a
  set dirtime=%%b
  echo !dirdate!, !dirtime!
  set dirday=!dirdate:~0,2!
  echo !dirday!
)
</code>```

In Windows 7 the dir command in the command prompt outputs something similar to:

```<code>   Directory of C:\Windows
12/21/2016  12:56    <DIR>          .
12/21/2016  12:56    <DIR>          ..
09/18/2017  07.42            678    config
</code>```

In Windows XP the dir command in the command prompt outputs something similar to:

```<code>   Directory of C:\WINDOWS

12/21/2016  12:56 PM    <DIR>          .
12/21/2016  12:56 PM    <DIR>          ..
09/18/2017  07.42 PM            678    config
</code>```

The only difference (as far as I can notice) is the PM column(?) which does not exist in Windows 7 but does exist in Windows XP.

I know this is probably a trivial question but I am new in batch scripting and seeing a specific example using a complex for loop would help my understanding. Assume use of delayed expansion.

答:
The different OS is not your problem, unfortunately the output of the DIR command is not consistent, it can differ between users. The simplest fix is to use an alternative method of retrieving the data you wish to capture, npocmaka's answer uses JScript and the following answer uses another built-in tool, WMIC.exe.

@Echo Off

Set "_dp=C:\folderA\folderB"

Echo  Directory of %_dp% & Echo(
For %%A In ("%_dp%\*") Do (Set "_pf=%%~fA"
    SetLocal EnableDelayedExpansion
    For /F "UseBackQ Skip=1 Delims=" %%B In (`WMIC DataFile Where^
        "Drive='%%~dA' And Name='!_pf:\=\\!'" Get CreationDate^,FileSize`
    ) Do For /F "Tokens=1-2*" %%C In ("%%~B") Do (Set "_dt=%%~nxC"
        Set "_d=!_dt:~4,2!/!_dt:~6,2!/!_dt:~,4!"
        Set "_t=!_dt:~8,2!:!_dt:~10,2!" & Echo !_d! !_t!    %%D "%%~nxA")
        EndLocal)
Pause
```

<p><hr><strong>Edit</strong></p>

<p>It seems, you were looking for data from a <code>dir</code>ectory. <em>(I was mistaken in believing you meant the <code>dir</code> command)</em>.</p>

<p>Here is some updated code to reflect that fully:</p>

<pre class="lang-bat prettyprint-override"><code>@Echo Off

Set "_dp=C:\folderA\folderB"

Echo  Directory of %_dp% & Echo(
For /D %%A In ("%_dp%\*") Do (Set "_pf=%%~fA"
    SetLocal EnableDelayedExpansion
    For /F "Skip=1 Delims=" %%B In ('
        "WMIC FSDir Where (Drive='%%~dA' And Name='!_pf:\=\\!') Get CreationDate"
    ') Do For /F %%C In ("%%~B") Do (Set "_dt=%%~nxC"
        Set "_d=!_dt:~4,2!/!_dt:~6,2!/!_dt:~,4!"
        Set "_t=!_dt:~8,2!:!_dt:~10,2!" & Echo !_d! !_t!    "%%~nxA")
        EndLocal)
Pause
</code>```

From memory, the very first time you run WMIC in XP there may be an initialisation delay

The output layout can be manipulated, as I have done…

Body:
I am trying to understand the for loop in batch scripting; in particular with skip and tokens parameters. I have found a great example in this answer followed by this nice read.

I would like to see how I can extract the date and time from a dir in Windows XP which has a slightly different dir output (see below example outputs) compared to Windows 7. In other words, how to extract creation date of a specific folder in Windows XP.

The following modified code from the above mentioned links correctly extracts the date and time of a DIR in Windows 7 but fails (i.e. extracts other characters) in Windows XP:

SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set dirdate=%%a
  set dirtime=%%b
  echo !dirdate!, !dirtime!
  set dirday=!dirdate:~0,2!
  echo !dirday!
)

In Windows 7 the dir command in the command prompt outputs something similar to:

   Directory of C:\Windows
12/21/2016  12:56    <DIR>          .
12/21/2016  12:56    <DIR>          ..
09/18/2017  07.42            678    config

In Windows XP the dir command in the command prompt outputs something similar to:

   Directory of C:\WINDOWS

12/21/2016  12:56 PM    <DIR>          .
12/21/2016  12:56 PM    <DIR>          ..
09/18/2017  07.42 PM            678    config

The only difference (as far as I can notice) is the PM column(?) which does not exist in Windows 7 but does exist in Windows XP.

I know this is probably a trivial question but I am new in batch scripting and seeing a specific example using a complex for loop would help my understanding. Assume use of delayed expansion.

Body:
The different OS is not your problem, unfortunately the output of the DIR command is not consistent, it can differ between users. The simplest fix is to use an alternative method of retrieving the data you wish to capture, npocmaka's answer uses JScript and the following answer uses another built-in tool, WMIC.exe.

@Echo Off

Set "_dp=C:\folderA\folderB"

Echo  Directory of %_dp% & Echo(
For %%A In ("%_dp%\*") Do (Set "_pf=%%~fA"
    SetLocal EnableDelayedExpansion
    For /F "UseBackQ Skip=1 Delims=" %%B In (`WMIC DataFile Where^
        "Drive='%%~dA' And Name='!_pf:\=\\!'" Get CreationDate^,FileSize`
    ) Do For /F "Tokens=1-2*" %%C In ("%%~B") Do (Set "_dt=%%~nxC"
        Set "_d=!_dt:~4,2!/!_dt:~6,2!/!_dt:~,4!"
        Set "_t=!_dt:~8,2!:!_dt:~10,2!" & Echo !_d! !_t!    %%D "%%~nxA")
        EndLocal)
Pause

Edit

It seems, you were looking for data from a directory. (I was mistaken in believing you meant the dir command).

Here is some updated code to reflect that fully:

@Echo Off

Set "_dp=C:\folderA\folderB"

Echo  Directory of %_dp% & Echo(
For /D %%A In ("%_dp%\*") Do (Set "_pf=%%~fA"
    SetLocal EnableDelayedExpansion
    For /F "Skip=1 Delims=" %%B In ('
        "WMIC FSDir Where (Drive='%%~dA' And Name='!_pf:\=\\!') Get CreationDate"
    ') Do For /F %%C In ("%%~B") Do (Set "_dt=%%~nxC"
        Set "_d=!_dt:~4,2!/!_dt:~6,2!/!_dt:~,4!"
        Set "_t=!_dt:~8,2!:!_dt:~10,2!" & Echo !_d! !_t!    "%%~nxA")
        EndLocal)
Pause

From memory, the very first time you run WMIC in XP there may be an initialisation delay

The output layout can be manipulated, as I have done…