问:
ModelState.IsValid is always true
As is typical in MVC, I have a View, a Model, and a Controller.

The View contains a form:

```<code>@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.Id)
    <ul class="fieldlist">
        <li>
            @Html.LabelFor(m =>m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)
        </li>
        <li>
            <div class="row">
                <div class="col-md-6">
                    @Html.LabelFor(m => m.FirstName)
                    @Html.TextBoxFor(m => m.FirstName)
                    @Html.ValidationMessageFor(m => m.FirstName)
                </div>
                <div class="col-md-6">
                    @Html.LabelFor(m => m.LastName)
                    @Html.TextBoxFor(m => m.LastName)
                    @Html.ValidationMessageFor(m => m.LastName)
                </div>
            </div>
        </li>
        <li>
            @Html.LabelFor(m => m.PhoneNumber)
            @Html.TextBoxFor(m => m.PhoneNumber)
            @Html.ValidationMessageFor(m => m.PhoneNumber)
        </li>
        <li>
            <div Class="row">
                <div Class="col-md-2">
                    <input type="submit" value="Save" />
                </div>
            </div>
        </li>
    </ul>
}
</code>```

The model looks like this:

```<code>public class UserAdminUserViewModel
{
    [Display(Name = "User Database ID"), DataType(DataType.Text)]
    public string Id { get; set; }
    [Display(Name = "Full Name")]
    public string Name { get { return FirstName + " " + LastName; } }
    [Required()]
    [Display(Name = "First Name"), DataType(DataType.Text)]
    public string FirstName { get; set; }
    [Required()]
    [Display(Name = "Last Name"), DataType(DataType.Text)]
    public string LastName { get; set; }
    [Required()]
    [Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Display(Name = "Telephone Number"), DataType(DataType.Text)]
    public string PhoneNumber { get; set; }
}
</code>```

And the controller to receive the updates:

```<code>[HttpPost,ValidateAntiForgeryToken]
public ActionResult User(UserAdminUserViewModel model)
{
    if (ModelState.IsValid)
    {
        // do something, apply the updates to the database, presumably
    }
    return View(model);
}
</code>```

...but ModelState.IsValid is always true. The controller is receiving the entered information, but it appears that no validation is taking place. I have tried:

```<code>TryUpdateModel<UserAdminUserViewModel>(model);
</code>```

and

```<code>UpdateModel<UserAdminUserViewModel>(model);
</code>```

I'm not sure I see how these would work, but they were the first suggestions I came across. No dice. Still valid regardless of the data in 'model'. I also tried:

```<code>System.ComponentModel.DataAnnotations.Validator.ValidateObject(model, new System.ComponentModel.DataAnnotations.ValidationContext(model));
</code>```

More promising, but still doesn't work. I also tried the more verbose approach:

```<code>System.ComponentModel.DataAnnotations.ValidationContext valContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
List<System.ComponentModel.DataAnnotations.ValidationResult> valResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, valContext, valResults, true);
foreach(System.ComponentModel.DataAnnotations.ValidationResult result in valResults)
{
    this.ModelState.AddModelError(result.MemberNames.FirstOrDefault() ?? string.Empty, result.ErrorMessage);
}
</code>```

...which also didn't work. 'valResults', which should contain any errors in the state of the model, is never filled; no validation is happening.

答:
I would use this for email validation:

```<code>@using using System.ComponentModel.DataAnnotations;

[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }
</code>```

Please see this StackOverflow post

However, EmailAddressAttribute adds server-side validation on top of
  that. I.e. there is no server-side validation if you only use
  DataTypeAttribute!

Title: ModelState.IsValid is always true

Body:
As is typical in MVC, I have a View, a Model, and a Controller.

The View contains a form:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.Id)

            @Html.LabelFor(m =>m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)

                    @Html.LabelFor(m => m.FirstName)
                    @Html.TextBoxFor(m => m.FirstName)
                    @Html.ValidationMessageFor(m => m.FirstName)

                    @Html.LabelFor(m => m.LastName)
                    @Html.TextBoxFor(m => m.LastName)
                    @Html.ValidationMessageFor(m => m.LastName)

            @Html.LabelFor(m => m.PhoneNumber)
            @Html.TextBoxFor(m => m.PhoneNumber)
            @Html.ValidationMessageFor(m => m.PhoneNumber)

                    <input type="submit" value="Save" />

}

The model looks like this:

public class UserAdminUserViewModel
{
    [Display(Name = "User Database ID"), DataType(DataType.Text)]
    public string Id { get; set; }
    [Display(Name = "Full Name")]
    public string Name { get { return FirstName + " " + LastName; } }
    [Required()]
    [Display(Name = "First Name"), DataType(DataType.Text)]
    public string FirstName { get; set; }
    [Required()]
    [Display(Name = "Last Name"), DataType(DataType.Text)]
    public string LastName { get; set; }
    [Required()]
    [Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Display(Name = "Telephone Number"), DataType(DataType.Text)]
    public string PhoneNumber { get; set; }
}

And the controller to receive the updates:

[HttpPost,ValidateAntiForgeryToken]
public ActionResult User(UserAdminUserViewModel model)
{
    if (ModelState.IsValid)
    {
        // do something, apply the updates to the database, presumably
    }
    return View(model);
}

...but ModelState.IsValid is always true. The controller is receiving the entered information, but it appears that no validation is taking place. I have tried:

TryUpdateModel<UserAdminUserViewModel>(model);

and

UpdateModel<UserAdminUserViewModel>(model);

I'm not sure I see how these would work, but they were the first suggestions I came across. No dice. Still valid regardless of the data in 'model'. I also tried:

System.ComponentModel.DataAnnotations.Validator.ValidateObject(model, new System.ComponentModel.DataAnnotations.ValidationContext(model));

More promising, but still doesn't work. I also tried the more verbose approach:

System.ComponentModel.DataAnnotations.ValidationContext valContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
List<System.ComponentModel.DataAnnotations.ValidationResult> valResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, valContext, valResults, true);
foreach(System.ComponentModel.DataAnnotations.ValidationResult result in valResults)
{
    this.ModelState.AddModelError(result.MemberNames.FirstOrDefault() ?? string.Empty, result.ErrorMessage);
}

...which also didn't work. 'valResults', which should contain any errors in the state of the model, is never filled; no validation is happening.

Body:
I would use this for email validation:

@using using System.ComponentModel.DataAnnotations;

[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

Please see this StackOverflow post

However, EmailAddressAttribute adds server-side validation on top of
  that. I.e. there is no server-side validation if you only use
  DataTypeAttribute!


来源: stackexchange

问:
ReactJS - Can I open open a Modal from different component
I am trying to call a model in "model.js" by onClick a button from another component (list.js) , just wonder if I have missed any step please see below:

model.js

```<code>import React from 'react';

class Model extends React.Component{

 render(){
  return(
   <div>
    //code inside the Model etc...
    <Button onClick={this.submit.bind(this)}>Submit</Button>
   </div>
  )
 }
}

export default Model;
</code>```

list.js

```<code>import Model from './model';
class List extends React.Component{
 render(){

  constructor() {
  super();

   this.toggleModal = this.toggleModal.bind(this);
   this.state = {
     open: false
   }
  }

  toggleModal() {
   this.setState({
   open: this.state.open
   });
  }

return(
 <div>
  <Button onClick={this.toggleModal}>Add</Button>
 </div>
 <div>
  <Model open={this.state.open} toggleModal={this.toggleModal}/>
 </div>
  )
 }
}

export default List;
</code>```

I have tried many ways to change the event handler code in List , but it still doesnt work.

That would be much appreciate if you guys could give me a hand and point out where the problems are, so that i can move forward.

答:
You definetely miss the exclamation mark, because as for now, you will always assign false value when clicking the button - modal won't show up.

```<code>this.setState({
  open: !this.state.open
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to call a model in "model.js" by onClick a button from another component (list.js) , just wonder if I have missed any step please see below:

model.js

import React from 'react';

class Model extends React.Component{

 render(){
  return(

    //code inside the Model etc...
    <Button onClick={this.submit.bind(this)}>Submit</Button>

  )
 }
}

export default Model;

list.js

import Model from './model';
class List extends React.Component{
 render(){

  constructor() {
  super();

   this.toggleModal = this.toggleModal.bind(this);
   this.state = {
     open: false
   }
  }

  toggleModal() {
   this.setState({
   open: this.state.open
   });
  }

return(

  <Button onClick={this.toggleModal}>Add</Button>

  <Model open={this.state.open} toggleModal={this.toggleModal}/>

  )
 }
}

export default List;

I have tried many ways to change the event handler code in List , but it still doesnt work.

That would be much appreciate if you guys could give me a hand and point out where the problems are, so that i can move forward.

Body:
You definetely miss the exclamation mark, because as for now, you will always assign false value when clicking the button - modal won't show up.

this.setState({
  open: !this.state.open
});


问:
send mysql result to an email with php mail function
i have a php page that i used to get info from a data base , what i need is to send it in an email but for each result a new email and not all info i one same email. here is my mysql php scrtip

```<code>   <?php
include 'myDB.php';

 $sql = "this query is working perfectly ";
 $result = mysqli_query($conn, $sql);

//var_dump($result);
 if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    echo "nombre del paquete: " . $row["nombre_del_paquete"]."
     <srtong>precio total:</strong> " . $row["precio_total"]. "
    " . $row["nombre"]. "
    " . $row["apellido"]. "
    " . $row["email"]. "

    " . $row["submitted"]. "<br><br>";

        $header ="From: no-reply@test.com" . "\r\n";
    $para    = 'web2@myemail.com';
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $titulo  = 'Newsletter';

    $message = '<html><body>';
    $message .= '<img src="https://world.bookinghello.com/PromoFB/img/hello_logo.png" alt="HELLO" />';
    $message .= '<br/> <p>El siguiente usuario abandono el la compra de un paquete en booking hello </p><br/>';
    $message .= '<table rules="all" style="border-color: #666;" cellpadding="2">';
    $message .= "<tr><td><strong>Nombre del paquete:</strong> </td><td>" . $row["nombre_del_paquete"]."</td></tr>";
    $message .= "<tr><td><strong>Nombre del paquete:</strong> </td><td>" . $row["precio_total"]."</td></tr>";
    $message .= "<tr><td><strong>Nombre del paquete:</strong> </td><td>" . $row["nombre"]."</td></tr>";
    $message .= "<tr><td><strong>Nombre del paquete:</strong> </td><td>" . $row["apellido"]."</td></tr>";
    $message .= "<tr><td><strong>Nombre del paquete:</strong> </td><td>" . $row["email"]."</td></tr>";

    $message .= "</table>";
    $message .= "</body></html>";

    if(mail($para, $titulo, $message, $header)){
     echo "successful";
                die();
    }else{
        echo "false";
    }
}
 } else {
echo "0 results";
}

?>
</code>```

when i remove the mail option i get 5 results in echo, when i add the mail option i only get 1 result(first one) and email is sent as well with 1 info, will like to get 5 different emails

答:
Create a method called sendMail and pass required value, which will be used when sending mail.

Then, call sendMail for each iteration of

```<code>while($row = mysqli_fetch_assoc($result)) {
    //your code
   // Call sendMail
   // some code
}
</code>```

Body:
i have a php page that i used to get info from a data base , what i need is to send it in an email but for each result a new email and not all info i one same email. here is my mysql php scrtip

   <?php
include 'myDB.php';

 $sql = "this query is working perfectly ";
 $result = mysqli_query($conn, $sql);

//var_dump($result);
 if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    echo "nombre del paquete: " . $row["nombre_del_paquete"]."
     <srtong>precio total: " . $row["precio_total"]. "
    " . $row["nombre"]. "
    " . $row["apellido"]. "
    " . $row["email"]. "

    " . $row["submitted"]. "

";

        $header ="From: no-reply@test.com" . "\r\n";
    $para    = 'web2@myemail.com';
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $titulo  = 'Newsletter';

    $message = '';
    $message .= '';
    $message .= '

El siguiente usuario abandono el la compra de un paquete en booking hello

';
    $message .= '
';
    $message .= "
Nombre del paquete: 	" . $row["nombre_del_paquete"]."
";
    $message .= "
Nombre del paquete: 	" . $row["precio_total"]."
";
    $message .= "
Nombre del paquete: 	" . $row["nombre"]."
";
    $message .= "
Nombre del paquete: 	" . $row["apellido"]."
";
    $message .= "
Nombre del paquete: 	" . $row["email"]."
";

    $message .= "
";
    $message .= "";

    if(mail($para, $titulo, $message, $header)){
     echo "successful";
                die();
    }else{
        echo "false";
    }
}
 } else {
echo "0 results";
}

?>

when i remove the mail option i get 5 results in echo, when i add the mail option i only get 1 result(first one) and email is sent as well with 1 info, will like to get 5 different emails

Body:
Create a method called sendMail and pass required value, which will be used when sending mail.

Then, call sendMail for each iteration of

while($row = mysqli_fetch_assoc($result)) {
    //your code
   // Call sendMail
   // some code
}


问:
Running mvn in background from Python Popen and thread function
I am implementing a gateway server automation using Py4j module.The gateway server needs to be initiated every-time the user invokes the function.The issue I am facing is that I am unable to run the function in background.
Here is the code:

```<code>def mvn():
logger = open("log.txt", 'w')
logger.seek(0)
thread1 = Thread(target=Popen, args=("./runJVM.sh"),kwargs=
                {"stdout":logger})
thread1.daemon = True
thread1.start()
# stdout, error = proc.communicate()
# logger.write(stdout)
logger.close()
</code>```

There are two issues I am facing here
1)If I specify the kwargs stdout to logger (a log file to check output),it throws me an error saying that stdout has multiple arguments specified.

2)If I dont specify the stdout option, the output of the thread is displayed onto ipython terminal which is not I wanted.

All i want is to invoke the server in the background so that other functions can access the java gateway server and access the methods from the same which can be used from ipython.

You can safely assume that the mvn functions are working fine when run through the terminal directly.

Thank you

答:
I found the answer to the question.

I have created a thread which will take the Popen command taking a small shell script as input and passing stdout params as kwargs so that the output is not displayed.
The server was invoked and could be used from other functions.

Hope that helps

Body:
I am implementing a gateway server automation using Py4j module.The gateway server needs to be initiated every-time the user invokes the function.The issue I am facing is that I am unable to run the function in background.
Here is the code:

def mvn():
logger = open("log.txt", 'w')
logger.seek(0)
thread1 = Thread(target=Popen, args=("./runJVM.sh"),kwargs=
                {"stdout":logger})
thread1.daemon = True
thread1.start()
# stdout, error = proc.communicate()
# logger.write(stdout)
logger.close()

There are two issues I am facing here
1)If I specify the kwargs stdout to logger (a log file to check output),it throws me an error saying that stdout has multiple arguments specified.

2)If I dont specify the stdout option, the output of the thread is displayed onto ipython terminal which is not I wanted.

All i want is to invoke the server in the background so that other functions can access the java gateway server and access the methods from the same which can be used from ipython.

You can safely assume that the mvn functions are working fine when run through the terminal directly.

Thank you


问:
Extracting contents of ConnectionStrings in web.config in Silverlight Business application
I am trying to read dataSource ad Catalog from <connectionStrings> in web.config in Silverlight business project. Unfortunately  when I used SqlConnectionStringBuilder, I could not read connection string the has

```<code>connectionString="metadata=res://*/MainDatabase.Main.csdl|res://*/MainDatabase.Main.ssdl|......."
</code>```

where as it work for

```<code>connectionString="Data Source=My-PC\SQL_2008;Initial Catalog =....
</code>```

I could get them using "Split" however, I don't like that solution. Is there any way to get my requirements?

Thanks

答: Your first connection string (that isn't working) is an Entity Framework connection string - it isn't in a format the SqlConnectionStringBuilder can understand.  However, EntityConnectionStringBuilder will understand that, and it has a property called ProviderConnectionString.  This property will have the actual SQL connection string in it, which you can pass to a SqlConnectionStringBuilder as in your second example.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to read dataSource ad Catalog from <connectionStrings> in web.config in Silverlight business project. Unfortunately  when I used SqlConnectionStringBuilder, I could not read connection string the has

connectionString="metadata=res://*/MainDatabase.Main.csdl|res://*/MainDatabase.Main.ssdl|......."

where as it work for

connectionString="Data Source=My-PC\SQL_2008;Initial Catalog =....

I could get them using "Split" however, I don't like that solution. Is there any way to get my requirements?

Thanks


问:
Can I modify values as I classify a Perl 6 list?
The List.classify method can transform a list into a hash by some mapping that I define. The result of that mapping is the hash key and the original value

```<code>my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0];

say %hash;
</code>```

The hash values are lists of lists because the original thinygs it classified were lists:

```<code>{
Amelia => [(Amelia 1) (Amelia 2) (Amelia 3)],
Camelia => [(Camelia 5) (Camelia 6) (Camelia 7)]
}
</code>```

But, I'd really want this:

```<code>{
Amelia => ( 1 2 3 ),
Camelia => ( 5 6 7 )
}
</code>```

I could do some extra work, but that seems a bit too much work:

```<code>my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list
    .classify( *.[0] )
    .kv
    .map( {
        $^a => $^b.map: *.[*-1]
        } )
    ;

say %hash;
</code>```

答:
You can use the :as adverb:

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0], as => *.[1];

say %hash;  # {Amelia => [1 2 3], Camelia => [5 6 7]}
```

(Unfortunately, it doesn't seem to be documented yet.)

Body:
The List.classify method can transform a list into a hash by some mapping that I define. The result of that mapping is the hash key and the original value

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0];

say %hash;

The hash values are lists of lists because the original thinygs it classified were lists:

{
Amelia => [(Amelia 1) (Amelia 2) (Amelia 3)],
Camelia => [(Camelia 5) (Camelia 6) (Camelia 7)]
}

But, I'd really want this:

{
Amelia => ( 1 2 3 ),
Camelia => ( 5 6 7 )
}

I could do some extra work, but that seems a bit too much work:

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list
    .classify( *.[0] )
    .kv
    .map( {
        $^a => $^b.map: *.[*-1]
        } )
    ;

say %hash;

Body:
You can use the :as adverb:

my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0], as => *.[1];

say %hash;  # {Amelia => [1 2 3], Camelia => [5 6 7]}

(Unfortunately, it doesn't seem to be documented yet.)


问:
Expression For Last Day of January in Current Year
I want to know what expression what I use to find specifically the last day of the month of January for the current year. Can anybody help me with this specific expression in SSRS? Trying to use for a parameter value.

Thanks!

答:
We know that the last day of the January is the 31st day of the Year. I am not sure if you are specifically asking for the date or the weekday name. So below are the expressions you can use.

Date of the last day of January for current year: (01/31/2017)

```<code>=DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+31,Today)
</code>```

Weekday of the last day of January for current year: (3)

```<code>=Weekday(DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+31,Today))
</code>```

WeekdayName of the last day of January for current year: (Tuesday)

```<code>=WeekdayName(Weekday(DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+31,Today)))
</code>```

Body:
We know that the last day of the January is the 31st day of the Year. I am not sure if you are specifically asking for the date or the weekday name. So below are the expressions you can use.

Date of the last day of January for current year: (01/31/2017)

=DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+31,Today)

Weekday of the last day of January for current year: (3)

=Weekday(DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+31,Today))

WeekdayName of the last day of January for current year: (Tuesday)

=WeekdayName(Weekday(DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+31,Today)))


问:
Gosu library incompatibility with windows 8.1 (ruby 2.3)
I recently installed Ruby 2.3 and the Gosu 2d game development library on Windows OS 8.1 (Surface Pro 2). The installation of both was quick and successful. Using the library I wrote a basic program (using Sublime Text 3) meant to generate a blank window. The Console continued to return this error message despite my attempts at debugging:

```<code>C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- gosu.so (LoadError)
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/gosu-0.12.0-x64-mingw32/lib/gosu.rb:17:in `<top (required)>'
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:133:in `require'
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:133:in `rescue in require'
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:40:in `require'
    from C:/Users/Kevin/Desktop/Clone/clone.rb:1:in `<main>'
[Finished in 0.7s with exit code 1]
[shell_cmd: ruby "C:\Users\Kevin\Desktop\Clone\clone.rb"]
[dir: C:\Users\Kevin\Desktop\Clone]
[path: C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Ruby24-x64\bin]
</code>```

Here is the basic program I wrote: >>>

```<code>require "gosu"

class GameWindow < Gosu::Window
    def initialize width=500, height=500, fullscreen=false
        super
        self.caption = "Clone"
    end

    def update
    end

    def draw
    end
end

GameWindow.new.show
</code>```

<<<

I am very new to programming in general, so my attempts to interpret this error message have been futile. I installed and used Gosu on my MacBook with OSX Sierra and everything worked like it should, leading me to believe the problem is OS related. I know there have been multiple problems with the Gosu library on Windows OS in the past because of system dependency issues, but resolutions to those issues have proven unhelpful. Could someone please explain to me this error message? Is it possible that the Gosu library is incompatible with Windows OS 8.1 or is there just a step for setting up Gosu on Windows that I skipped?

I would appreciate any help I can get.

答: The question title mentions Ruby 2.3, but from the error message it seems you are using Ruby 2.4. Gosu 0.12.0 wasn't compatible with Ruby 2.4, but Gosu 0.12.1 is. Please run gem update gosu and try again, that should fix the issue.

Body:
I recently installed Ruby 2.3 and the Gosu 2d game development library on Windows OS 8.1 (Surface Pro 2). The installation of both was quick and successful. Using the library I wrote a basic program (using Sublime Text 3) meant to generate a blank window. The Console continued to return this error message despite my attempts at debugging:

C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- gosu.so (LoadError)
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/gosu-0.12.0-x64-mingw32/lib/gosu.rb:17:in `<top (required)>'
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:133:in `require'
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:133:in `rescue in require'
    from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:40:in `require'
    from C:/Users/Kevin/Desktop/Clone/clone.rb:1:in `'
[Finished in 0.7s with exit code 1]
[shell_cmd: ruby "C:\Users\Kevin\Desktop\Clone\clone.rb"]
[dir: C:\Users\Kevin\Desktop\Clone]
[path: C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Ruby24-x64\bin]

Here is the basic program I wrote: >>>

require "gosu"

class GameWindow < Gosu::Window
    def initialize width=500, height=500, fullscreen=false
        super
        self.caption = "Clone"
    end

    def update
    end

    def draw
    end
end

GameWindow.new.show

<<<

I am very new to programming in general, so my attempts to interpret this error message have been futile. I installed and used Gosu on my MacBook with OSX Sierra and everything worked like it should, leading me to believe the problem is OS related. I know there have been multiple problems with the Gosu library on Windows OS in the past because of system dependency issues, but resolutions to those issues have proven unhelpful. Could someone please explain to me this error message? Is it possible that the Gosu library is incompatible with Windows OS 8.1 or is there just a step for setting up Gosu on Windows that I skipped?

I would appreciate any help I can get.


问:
Run script at 12 am at every time zone
I'm trying to run a .php script on at 12 am (midnight) for every timezone.

My goal: I have a field in my database called time_zone. i need to send an email to that user in that "time zone" at 12 am.

i looked into cron jobs but i don't think it works well with timezones. is there any other way to achieve this?

EDIT: I did think about running the script every 30 min because some timezones are 30 min apart but that doesn't seem like a good solution because i wouldn't know how to calculate in which time zone it is 12:00 am.

答: You could make an array of all time-zones and compare from that. If that exists in the array you can send the email. It's not perfect, but it should do the job. </p>

Title: Run script at 12 am at every time zone


问:
Injecting service into controller throws error
I am unable to inject service into controller. I was able to execute a similar code a year ago and it worked but this time I am having a hard luck.

app.js

```<code>'use strict';
var app = angular.module('product', [
  "ngRoute",
]);
</code>```

main.ctrl.js

```<code>'use strict';
app.controller('mainCtrl', ['$scope','$http','srv', function ($scope,$http,srv) {
    var srvUrl = srv.getSrvUrl;
    var data = srv.getData(1,2);
}]);
</code>```

srv.js

```<code>app.service("srv", function ($http,$scope) {
    this.getSrvUrl = "http://127.0.0.1/api/";
    this.getData = function(a,b) { return a*b; }
});
</code>```

index.html

```<code><!--JS-->
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<!--APP-->
<script type="text/javascript" src="app/app.js"></script>
<!-- ROUTE -->
<script type="text/javascript" src="bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="app/routes/app.route.js"></script>
<!-- SERVICE -->
<script type="text/javascript" src="app/services/srv.js"></script>
<!--CONTROLLER-->
<script type="text/javascript" src="app/controllers/main.ctrl.js"></script>
</code>```

console error

```<code>angular.js:14362
Error: [$injector:unpr] http://errors.angularjs.org/1.6.2/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20srv
at angular.js:38
at angular.js:4650
at Object.d [as get] (angular.js:4803)
at angular.js:4655
at d (angular.js:4803)
at e (angular.js:4828)
at Object.instantiate (angular.js:4874)
at Object.<anonymous> (angular.js:4712)
at Object.invoke (angular.js:4862)
at Object.$get (angular.js:4696)
</code>```

Please help.

答:
You can not inject $scope in service.

Service are singleton object used to share data and some reusable methods.

It should be like this

```<code>app.service("srv", function ($http, $scope) {
    return {
        getSrvUrl: "http://127.0.0.1/api/",
        getData: function (a, b) { return a * b; }
    }
});
</code>```

Body:
I am unable to inject service into controller. I was able to execute a similar code a year ago and it worked but this time I am having a hard luck.

app.js

'use strict';
var app = angular.module('product', [
  "ngRoute",
]);

main.ctrl.js

'use strict';
app.controller('mainCtrl', ['$scope','$http','srv', function ($scope,$http,srv) {
    var srvUrl = srv.getSrvUrl;
    var data = srv.getData(1,2);
}]);

srv.js

app.service("srv", function ($http,$scope) {
    this.getSrvUrl = "http://127.0.0.1/api/";
    this.getData = function(a,b) { return a*b; }
});

index.html

console error

angular.js:14362
Error: [$injector:unpr] http://errors.angularjs.org/1.6.2/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20srv
at angular.js:38
at angular.js:4650
at Object.d [as get] (angular.js:4803)
at angular.js:4655
at d (angular.js:4803)
at e (angular.js:4828)
at Object.instantiate (angular.js:4874)
at Object.<anonymous> (angular.js:4712)
at Object.invoke (angular.js:4862)
at Object.$get (angular.js:4696)

Please help.

Body:
You can not inject $scope in service.

Service are singleton object used to share data and some reusable methods.

It should be like this

app.service("srv", function ($http, $scope) {
    return {
        getSrvUrl: "http://127.0.0.1/api/",
        getData: function (a, b) { return a * b; }
    }
});


问:
Delete function always selects same ID - blog - Codeigniter
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

```<code><div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
    <div class="col-md-3">
        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
    </div>
    <div class="col-md-9">
        <small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
    <?php echo word_limiter($post['body'], 60); ?>
    <br><br>
    <p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
    </div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>
</code>```

Controller

```<code>public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}
</code>```

Model

```<code>public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}
</code>```

EDIT:
get_posts in model

```<code>public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}
</code>```

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

答: Thanks to everyone, your answers helped me a lot and I learned a few new things about PHP. I tried implementing your Ideas and they solved the area of the problem I was asking about. In the end I decided to use a simple mysqli query to get the data I needed from the database. mysqli_query($con, "SELECT id,category_id,user_id,title,body,created_at FROM posts Order By id DESC");

Body:
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

<?php foreach($posts as $post) : ?>

<?php echo $post['title']; ?>

        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">

        Posted on: <?php echo $post['created_at']; ?> in <?php echo $post['name']; ?>

    <?php echo word_limiter($post['body'], 60); ?>

<a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More

<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>

Controller

public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}

Model

public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}

EDIT:
get_posts in model

public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.


问:
Python Selenium unable to find table element by xpath
Here is what the table looks like on the web page (it's just one column):

Here is the HTML of the table I am trying to scrape:

If it matters, that table is nested within another table.

Here is my code:

```<code>    def filter_changed_records():
        # Scrape webpage for addresses from table of changed properties
        row_number = 0
        results_frame = locate_element(
            '//*[@id="oGridFrame"]'
        )
        driver.switch_to.frame(results_frame)
        while True:
            try:
                address = locate_element("id('row" + str(row_number) +
                                         "FC')/x:td")
                print(address)
                changed_addresses.append(address)
                row_number += 1
            except:
                print("No more addresses to add.")
                break
</code>```

As you can see, there is a
 tag with an id of row0FC. This table is dynamically generated, and each new
 gets an id with a increasing number: row0FC, row1FC, row2FC etc. That is how I planned on iterating through all the entries and adding them to a list.

My locate_element function is the following:

```<code>    def locate_element(path):
        element = WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.XPATH, path)))
        return element
</code>```

It always times out after 50 seconds from not finding the element. Unsure of how to proceed. Is there a better way of locating the element?

SOLUTION BY ANDERSSON

```<code>address = locate_element("//tr[@id='row%sFC']/td" % row_number).text
</code>```

答:
Parsing html with selenium is slow. I would use BeautifulSoup for that.

Suppose you have loaded the page in driver it would be something like:

```<code>from bs4 import BeautifulSoup
....

soup = BeautifulSoup(driver.page_source, "html.parser")
td_list = soup.findAll('td')
for td in td_list:
    try:
        addr = td['title']
        print(addr)
    except:
        pass
</code>```

Body:
Here is what the table looks like on the web page (it's just one column):

Here is the HTML of the table I am trying to scrape:

If it matters, that table is nested within another table.

Here is my code:

    def filter_changed_records():
        # Scrape webpage for addresses from table of changed properties
        row_number = 0
        results_frame = locate_element(
            '//*[@id="oGridFrame"]'
        )
        driver.switch_to.frame(results_frame)
        while True:
            try:
                address = locate_element("id('row" + str(row_number) +
                                         "FC')/x:td")
                print(address)
                changed_addresses.append(address)
                row_number += 1
            except:
                print("No more addresses to add.")
                break

As you can see, there is a
 tag with an id of row0FC. This table is dynamically generated, and each new
 gets an id with a increasing number: row0FC, row1FC, row2FC etc. That is how I planned on iterating through all the entries and adding them to a list.

My locate_element function is the following:

    def locate_element(path):
        element = WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.XPATH, path)))
        return element

It always times out after 50 seconds from not finding the element. Unsure of how to proceed. Is there a better way of locating the element?

SOLUTION BY ANDERSSON

address = locate_element("//tr[@id='row%sFC']/td" % row_number).text

Body:
Parsing html with selenium is slow. I would use BeautifulSoup for that.

Suppose you have loaded the page in driver it would be something like:

from bs4 import BeautifulSoup
....

soup = BeautifulSoup(driver.page_source, "html.parser")
td_list = soup.findAll('td')
for td in td_list:
    try:
        addr = td['title']
        print(addr)
    except:
        pass


问:
Embed image into a textbox
I have a Windows Forms (.Net 2.0) app and I have a request to embed some custom images into some textboxes(like the new version of Tortoise does). </p>

答: Hmm. Why don't you create a new userControl which has the BackColor of the TextBox. Hide TextBox's Border. Then subscribe to Paint event of the UC and draw the borders to resemble the textbox one. In the Paint Handler you can also draw an image. In the UserControl you can easily set the bounds of any child control such as textbox, or write a custom layout and place the textbox wherever you want. I hope this helps.</p>

OwnerDisplayName: nobody

LastEditorDisplayName: nobody

Title: Embed image into a textbox


问:
Cancel queued builds and aborting executing builds using Groovy for Jenkins
For Jenkins using a Groovy System Script, is there a way to easily search the build queue and list of executing builds for some criteria (specifically a parameter that matches some condition) and then kill/cancel them?

I cannot seem to find any way to do this, but it seems like it should be possible.

答:
I've expanded upon the snippet by Igor Zilberman so that it also aborts running jobs when there is a job in the queue with the same cause (what you see when you hover over the job in the build queue, only looking at the first line). I’m running this as a job with build step “Execute System Groovy Script”.</p>

```<code>
import hudson.model.Result
import jenkins.model.CauseOfInterruption
import jenkins.model.*;

[ // setup job names here
'my-jobname-here'
].each {jobName ->
  def queue = Jenkins.instance.queue
  def q = queue.items.findAll { it.task.name.equals(jobName) }
  def r = [:]
  def projs = jenkins.model.Jenkins.instance.items.findAll { it.name.equals(jobName) }

  projs.each{p ->
    x = p._getRuns()
    x.each{id, y ->
      r.put(id, y)
    }
  }

  TreeMap queuedMap = [:]
  TreeMap executingMap = [:]

  q.each{i->
    queuedMap.put(i.getId(), i.getCauses()[0].getShortDescription()) //first line
  }
  r.each{id, run->
    def exec = run.getExecutor()
    if(exec != null){
      executingMap.put(id, run.getCauses()[0].getShortDescription()) //first line
    }
  }

  println("Queued:")
  queuedMap.each{ k, v -> println "${k}:${v}" }
  println("Executing:")
  executingMap.each{ k, v -> println "${k}:${v}" }

  // First, if there is more than one queued entry, cancel all but the highest one.
  // Afterwards, if there is a queued entry, cancel the running ones

  def queuedNames = queuedMap.values();
  queuedNames.each{n ->
    def idsForName = []
    queuedMap.each{ id, name ->
      if(name.equals(n)){
        idsForName.add(id)
      }
    }
    if (idsForName.size() > 1){
      println("Cancelling queued job: "+n)
    }
    // remove all but the latest from queue
    idsForName.sort().take(idsForName.size() - 1).each { queue.doCancelItem(it) }
  }
  executingMap.each{ id, name ->
    if(queuedMap.values().contains(name)){
      r.each{rid, run->
        if (id == rid){
          def exec = run.getExecutor()
          if(exec != null){
            println("Aborting running job: "+id+": "+name)
            exec.interrupt(Result.ABORTED)
          }
        }
      }
    }
  }
}
return "Done"
</code>```

Body:
I've expanded upon the snippet by Igor Zilberman so that it also aborts running jobs when there is a job in the queue with the same cause (what you see when you hover over the job in the build queue, only looking at the first line). I’m running this as a job with build step “Execute System Groovy Script”.

import hudson.model.Result
import jenkins.model.CauseOfInterruption
import jenkins.model.*;

[ // setup job names here
'my-jobname-here'
].each {jobName ->
  def queue = Jenkins.instance.queue
  def q = queue.items.findAll { it.task.name.equals(jobName) }
  def r = [:]
  def projs = jenkins.model.Jenkins.instance.items.findAll { it.name.equals(jobName) }

  projs.each{p ->
    x = p._getRuns()
    x.each{id, y ->
      r.put(id, y)
    }
  }

  TreeMap queuedMap = [:]
  TreeMap executingMap = [:]

  q.each{i->
    queuedMap.put(i.getId(), i.getCauses()[0].getShortDescription()) //first line
  }
  r.each{id, run->
    def exec = run.getExecutor()
    if(exec != null){
      executingMap.put(id, run.getCauses()[0].getShortDescription()) //first line
    }
  }

  println("Queued:")
  queuedMap.each{ k, v -> println "${k}:${v}" }
  println("Executing:")
  executingMap.each{ k, v -> println "${k}:${v}" }

  // First, if there is more than one queued entry, cancel all but the highest one.
  // Afterwards, if there is a queued entry, cancel the running ones

  def queuedNames = queuedMap.values();
  queuedNames.each{n ->
    def idsForName = []
    queuedMap.each{ id, name ->
      if(name.equals(n)){
        idsForName.add(id)
      }
    }
    if (idsForName.size() > 1){
      println("Cancelling queued job: "+n)
    }
    // remove all but the latest from queue
    idsForName.sort().take(idsForName.size() - 1).each { queue.doCancelItem(it) }
  }
  executingMap.each{ id, name ->
    if(queuedMap.values().contains(name)){
      r.each{rid, run->
        if (id == rid){
          def exec = run.getExecutor()
          if(exec != null){
            println("Aborting running job: "+id+": "+name)
            exec.interrupt(Result.ABORTED)
          }
        }
      }
    }
  }
}
return "Done"


问:
Render map not displaying data on screen
I can't seem to get my renderJob mapping to render out properly.  I have no errors in the console and can't figure out while nothing is showing up.  Is there a problem with the way I'm mapping the object to the index?</p>

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'

const jbSampleData = [
    {
        name: 'A place',
        location: 'USA',
        engineer: "Contact Engineer",
        service: "Last install"
    },
]

class Job extends Component {
    render() {

        const renderJob = this.props.data.map((obj, idx) => {
            return (
                <div key={idx}>
                    <div>
                        <p>
                            <span>Name:</span> {obj.name} < br/>
                            <span>Location:</span> {obj.location} <br />
                            <span>Engineer Contact:</span> {obj.engineer} <br />
                            <span>Service:</span> {obj.service} <br />
                        </p>
                    </div>
                </div>
            );
        });

        return (
            <div>
                <renderJob />
                Hello
            </div>
        )
    }
}

Job.propTypes = {
    data: PropTypes.arrayOf(
        PropTypes.object
    )
}

Job.defaultProps = {
    data: jbSampleData
}
export default Job;
</code>```

答: Instead of <renderJob /> change to {renderJob}

Body:
I can't seem to get my renderJob mapping to render out properly.  I have no errors in the console and can't figure out while nothing is showing up.  Is there a problem with the way I'm mapping the object to the index?

import React, { Component } from 'react'
import PropTypes from 'prop-types'

const jbSampleData = [
    {
        name: 'A place',
        location: 'USA',
        engineer: "Contact Engineer",
        service: "Last install"
    },
]

class Job extends Component {
    render() {

        const renderJob = this.props.data.map((obj, idx) => {
            return (

                            Name: {obj.name}

                            Location: {obj.location}

                            Engineer Contact: {obj.engineer}

                            Service: {obj.service}

            );
        });

        return (

                <renderJob />
                Hello

        )
    }
}

Job.propTypes = {
    data: PropTypes.arrayOf(
        PropTypes.object
    )
}

Job.defaultProps = {
    data: jbSampleData
}
export default Job;


问:
Unit-testing of private method and possible refactoring
I am currently testing private method this way (using nunit):

```<code>class Foo
{
    private int Identity(int n) => n;
}

[TestFixture]
class MyTests
{
    [Test]
    public void TestFoo()
    {
        var myFoo = new Foo();
        var identityMethod = myFoo.GetType().GetMethod("Identity", BindingFlags.NonPublic | BindingFlags.Instance);
        Assert.That(identityMethod.Invoke(myFoo, new []{ (object)42 }), Is.EqualTo(42));
    }
}
</code>```

My team does not like this, because put the method name as a string prevent this method to be renamed, if we want to do refactoring through automatic tools.

I tried to replace the name with nameof, but:

Foo.Indentity(int) is inaccessible due to its protection level

(By the way, this is strange in my opinion that such an operator respects the privacy protections).

So, can I test private methods without sacrificing possible refactoring?

I was proposed to make the private methods protected and inherit the class with the class test, but this does not satisfy me.

Disclaimer: I know that some people think that private method should not be tested, but this is not the point here. Please do not transform this question into a debate about this.

答:
Putting on my coach hat on top of my testing software hat...

The warning to not test private methods is often misunderstood. I like to say consider the difficulty of testing private methods as a warning that something is wrong with the overall design.

Information hiding and testability are both characteristics of a good design. They are, unfortunately, sometimes in conflict and as with many other things you have to use your judgement to strike a balance. Since they are both goals of the design, there is no absolute answer like "Don't test the private methods" or "Don't make any methods private." You have to decide for yourself.

Often, a private method that we feel a strong need to test is a sign of a problem with the design. Maybe it should be protected. Maybe it actually represents a need for a new class, which you can test separately. I don't know, of course, since I don't know the actual code.

All this assumes that you have control over the design. If not - if you are only responsible for the tests - then you can either not test those methods or the responsible people can do something to make it possible for you to test them. Using InternalsVisibleTo with an internal method is a pretty good compromise a lot of the time.

Body:
I am currently testing private method this way (using nunit):

class Foo
{
    private int Identity(int n) => n;
}

[TestFixture]
class MyTests
{
    [Test]
    public void TestFoo()
    {
        var myFoo = new Foo();
        var identityMethod = myFoo.GetType().GetMethod("Identity", BindingFlags.NonPublic | BindingFlags.Instance);
        Assert.That(identityMethod.Invoke(myFoo, new []{ (object)42 }), Is.EqualTo(42));
    }
}

My team does not like this, because put the method name as a string prevent this method to be renamed, if we want to do refactoring through automatic tools.

I tried to replace the name with nameof, but:

Foo.Indentity(int) is inaccessible due to its protection level

(By the way, this is strange in my opinion that such an operator respects the privacy protections).

So, can I test private methods without sacrificing possible refactoring?

I was proposed to make the private methods protected and inherit the class with the class test, but this does not satisfy me.

Disclaimer: I know that some people think that private method should not be tested, but this is not the point here. Please do not transform this question into a debate about this.


问:
python regax search
I have to find the last occurrence of an ip address in a string using regex.
I found this

```<code>addr = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', program[line])
</code>```

which finds the first occurrence. How can I change it to find the last one?

Title: python regax search

Body:
I have to find the last occurrence of an ip address in a string using regex.
I found this

addr = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', program[line])

which finds the first occurrence. How can I change it to find the last one?

Body: re.findall(pattern, string)[-1]


问:
:before with an image and content:" " place the content in the bottom right corner
I have a pseudo class :before with a background image 300x200px and the css content:" " is the name of the background and should be positioned in the bottom right corner

I used

```<code>text-align:right;
</code>```

and used padding the bring the text down but that blows up the height of the element so I need an other solution for this. And no, I can't use a separate element for the text.

Edit: I can't show the code because it's for a subreddit stylesheet and there is much more css then that what I could show

```<code>#header [name='uh']~a:before, body>.side:before {
position: absolute;

width: 298px;
content: '';
text-align: right;
padding-top: 375px;
padding-right: 2px;
color: rgba(64, 92, 120, 0.7);
top: -207px;
right: -300px;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}

body>.side:before {
top: 70px;
z-index: 100;
top:-200px;
right:0;
}
#header [name='uh'][value$='0'] ~ a:before { background-image: url(%%1%%); content: '/u/Hisfantor';}
</code>```

答:
You can make use of the line-height property

See the snippet below, with the CSS and then HTML.

.test {
  position: relative;
  height: 300px;
}

.test::before {
  content: "image";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  margin: auto;
  height: 300px;
  width: 300px;
  text-align: right;
  line-height: 600px;
  background-image: url("https://hub.91mobiles.com/wp-content/uploads/2016/09/Google-Now-launcher.png");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test"></div></code>```

Link for reference

I hope this helps..

Body:
I have a pseudo class :before with a background image 300x200px and the css content:" " is the name of the background and should be positioned in the bottom right corner

I used

text-align:right;

and used padding the bring the text down but that blows up the height of the element so I need an other solution for this. And no, I can't use a separate element for the text.

Edit: I can't show the code because it's for a subreddit stylesheet and there is much more css then that what I could show

#header [name='uh']~a:before, body>.side:before {
position: absolute;

width: 298px;
content: '';
text-align: right;
padding-top: 375px;
padding-right: 2px;
color: rgba(64, 92, 120, 0.7);
top: -207px;
right: -300px;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}

body>.side:before {
top: 70px;
z-index: 100;
top:-200px;
right:0;
}
#header [name='uh'][value$='0'] ~ a:before { background-image: url(%%1%%); content: '/u/Hisfantor';}

Body:
You can make use of the line-height property

See the snippet below, with the CSS and then HTML.

.test {
  position: relative;
  height: 300px;
}

.test::before {
  content: "image";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  margin: auto;
  height: 300px;
  width: 300px;
  text-align: right;
  line-height: 600px;
  background-image: url("https://hub.91mobiles.com/wp-content/uploads/2016/09/Google-Now-launcher.png");
}

<div class="test"></div>

Link for reference

I hope this helps..


问:
Command /usr/bin/codesign failed with exit code 1

Possible Duplicate:

  /usr/bin/codesign failed with exit code 1

I am getting this error after sending 7-8 builds to QA of my company.
Thing tried :

Reinstalled the appstore distribution provisioning profiles .

Restated the xcode device.

changed the bundle identifier in info.plist.

And moreover this error is coming alternately and when i am trying to do the clean build.
alternately means first time this error is coming and next time it is gone and then again it is coming and then next time is gone.
Can someone tell me what the hell is happening, i have nailed my head for hours.

答:
There is some good advice on a related question /usr/bin/codesign failed with exit code 1:

...you can right click the error
  message in Xcode and choose expand to
  get more details, including a
  description of the problem.


问:
CSS - positioning images centrally within a container
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="welcome">
  <div class="container">
    <div class="row">
      <div class="twelve columns">
        <h4>WELCOME TO FEATURE MEDIA</h4>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.</p>
      </div>
    </div>
    <hr class="hrindeximages">
    <div class="images row">
      <div class="four columns">
        <div id="video">
          <h3>VIDEO</h3>
          <img src="images/VIDEO.jpg" alt="Video" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="blog">
          <h3>BLOG</h3>
          <img src="images/blog.jpg" alt="blog" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="faq">
          <h3>FAQ</h3>
          <img src="images/faq.jpg" alt="FAQ" style="width:300px;height:150px;">
        </div>
      </div>
    </div>
  </div>
</section></code>```

答:
This may be help you.

.images { text-align: center; width: 100%; }

Body:
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}

WELCOME TO FEATURE MEDIA

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.

VIDEO

BLOG

FAQ


问:
Must an object's ctor and dtor be on the same thread?
With C++ RAII, the dtor gets called when the object goes out of scope. The mechanisms for multithreading always involve passing a callback to be run on a new thread. Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes. </p>

<p>Am I right about this? Or are there some cases where an objects ctor and dtor can be called in different threads? </p>

答:
Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes.

Am I right about this?

No. These functions can be called completely independent of any threading.

Or are there some cases where an objects ctor and dtor can be called in different threads?

Sure there are cases (just daily bread and butter). Think about a simple producer / consumer model and message instances exchanged between threads through a queue.

The producer thread creates the message instance and pushes it into the queue. The consumer takes it off from the queue and the messages destructor will be called after it was processed.

Body:
With C++ RAII, the dtor gets called when the object goes out of scope. The mechanisms for multithreading always involve passing a callback to be run on a new thread. Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes.

Am I right about this? Or are there some cases where an objects ctor and dtor can be called in different threads?


问:
Rails error while trying to load a Service in a controller
My controller is defined as follows with a create method.

```<code>class AtestController < BaseController
def create
    result = create_something(params)
    @connection = Bunny.new
    @connection.start
    @channel = @connection.create_channel
    bunny = RabbitPublisherService::RabbitPublisher.new(@channel,@connection)
    render :json => trigger, :status => :created
  end
end
</code>```

My Rabbit Publisher Service is defined as follows

```<code>module RabbitPublisherService
  class RabbitPublisher

    private
    attr_accessor :channel, :connection

    def initialize(channel, connection)
      puts "I reached here"
      @channel = channel
      @connection = connection
    end

    def publish(message)
      q    = @channel.queue("task_queue", :durable => true)
      q.publish(message, :persistent => true)
      puts "Message is Published..."
      sleep 1.0
      @connection.close
    end
  end
end
</code>```

When I try calling this service from the controllers create method, RabbitPublisherService::RabbitPublisher.new, I get an uninitialized constant error saying
:error_message=>"uninitialized constant AtestController::RabbitPublisherService"

Can someone please help me find out what I am doing wrong?

答:
Generally, this is probably a problem with where you've put your files and where Rails expect them. An in-depth guide can be found here: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html.

To solve it, there are three options:

put the module and class where Rails autoloading expects them (IMO this is the preferred solution)

require the file where the class is defined

add the folder where the file containing the class is located to the autoload paths

1: You need to make sure that RabbitPublisherService and RabbitPublisher are in a location that Rails can autoload them, for instance app/services/rabbit_publisher_service.rb and app/services/rabbit_publisher_service/rabbit_publisher.rb.

2: Use require or (probably better) require_relative.

3: Alternatively you can explicitly add the path to the autoload/eager load paths.

In my opinion, you should stick with option 1 unless you have a very good reason not to. Using Rails' defaults keeps the code to a minimum and prevents surprises for fellow developers who expect Rails defaults. Number 2 is OK as well since it's explicit. I'd definitely avoid option 3 because it sooner or later always creates a mess when you put loads of files in unexpected locations and it makes it harder for other developers who are used to Rails defaults and expect them.

Body:
My controller is defined as follows with a create method.

class AtestController < BaseController
def create
    result = create_something(params)
    @connection = Bunny.new
    @connection.start
    @channel = @connection.create_channel
    bunny = RabbitPublisherService::RabbitPublisher.new(@channel,@connection)
    render :json => trigger, :status => :created
  end
end

My Rabbit Publisher Service is defined as follows

module RabbitPublisherService
  class RabbitPublisher

    private
    attr_accessor :channel, :connection

    def initialize(channel, connection)
      puts "I reached here"
      @channel = channel
      @connection = connection
    end

    def publish(message)
      q    = @channel.queue("task_queue", :durable => true)
      q.publish(message, :persistent => true)
      puts "Message is Published..."
      sleep 1.0
      @connection.close
    end
  end
end

When I try calling this service from the controllers create method, RabbitPublisherService::RabbitPublisher.new, I get an uninitialized constant error saying
:error_message=>"uninitialized constant AtestController::RabbitPublisherService"

Can someone please help me find out what I am doing wrong?


问:
Cascading Style Sheets (CSS) - Creating Posts above the image in a scroll
I want to ask how to display the text above the image and the file is located inside a scrollbar like the picture below.
I've searched on google and used position but it did not work. I hope you can help me to find a solution.

Pictures and texts contained in scroll

答:
Add a parent div and set the background to an image. Then you can add a child/nested div or a heading tag with your text in it.

See the below pseudo code. I did not test the code but it should be enough to get you on the right track.

CSS

```<code>#container-img{
   height: 500px; /* set the height you want the image to be */
   width: 500px; /* set the width of the image */
   background: url('your-img-src-here.png') no-repeat center center;
         /* you can add whatever sizing and alignment after the url*/
}
#child-txt{
   font-size: 14px;
   font-weight: bold;
   text-align: left;
   padding: 5px;
}
</code>```

HTML

```<code><div id="container-img">
   <div id="child-txt"> Cool Text Here! </div>
 </div>
</code>```

If it answers your question, please be sure to mark it as the answer. =)

Body:
Add a parent div and set the background to an image. Then you can add a child/nested div or a heading tag with your text in it.

See the below pseudo code. I did not test the code but it should be enough to get you on the right track.

CSS

#container-img{
   height: 500px; /* set the height you want the image to be */
   width: 500px; /* set the width of the image */
   background: url('your-img-src-here.png') no-repeat center center;
         /* you can add whatever sizing and alignment after the url*/
}
#child-txt{
   font-size: 14px;
   font-weight: bold;
   text-align: left;
   padding: 5px;
}

HTML

<div id="container-img">
   <div id="child-txt"> Cool Text Here! </div>
 </div>

If it answers your question, please be sure to mark it as the answer. =)


问:
Is there compile-time access to line numbers in C#?
I'm writing a C# program using Visual Studio 2010 where I want to write out certain events to a log file and include the line number the code was on when that happened.

I've only found two ways of capturing line numbers - CallerLineNumber, which requires .Net 4.5/C#5  (I'm targeting .Net 4) and StackFrame.GetFileLineNumber, which apparently requires a debug build and pdb file to work properly, and I'm producing a release build and no pdb file.

But here's what I don't get -  both of the above are run-time solutions, but line numbers are compile-time entities.   Why is a runtime solution necessary?

I could type in the correct line number as a literal constant by just looking at the bottom of the screen where it says something like "ln 175" . . .

```<code>LogEvent("It happened at line 175");
</code>```

but the problem with that is that if I edit any code before line 175 my literal might no longer be correct.    But the compiler knows the correct line number and I've used programming languages in the past that could just pop in the correct line number as a compile time constant. (e.g., ANSI C and Microsoft C++ support a predefined macro called
_LINE_)  Is there any way to get C# to do that?   If not are there any solutions to my problem?

答:
CAVEATS: This is NOT an answer to the OP. I know that. But people looking for something similar may find this page.

This is not about .NET 4.

This is still ultimately a run-time solution.

But VS 2015, C#, .NET Core or .NET 4.5 allow:

```<code>using System.Runtime.CompilerServices;
using System.Diagnostics;

public static String CurrentLocation(
  [CallerFilePath] string file = null,
  [CallerLineNumber] int lineNumber = 0,
  [CallerMemberName] string method = null)
{
  String location = file;
  if (lineNumber != 0)
  {
    location += "(" + lineNumber.ToString() + ")";
  }
  if (!String.IsNullOrWhiteSpace(method))
  {
    location += ": " + method;
  }
  if (!String.IsNullOrWhiteSpace(location))
  {
    location += ": ";
  }
  return location;
}
</code>```

[UPDATED USAGE]

With usage something like:

```<code>Console.Error.WriteLine(CurrentLocation() + "some message");
</code>```

or

```<code>Debug.WriteLine(CurrentLocation() + "some message");
</code>```

Body:
I'm writing a C# program using Visual Studio 2010 where I want to write out certain events to a log file and include the line number the code was on when that happened.

I've only found two ways of capturing line numbers - CallerLineNumber, which requires .Net 4.5/C#5  (I'm targeting .Net 4) and StackFrame.GetFileLineNumber, which apparently requires a debug build and pdb file to work properly, and I'm producing a release build and no pdb file.

But here's what I don't get -  both of the above are run-time solutions, but line numbers are compile-time entities.   Why is a runtime solution necessary?

I could type in the correct line number as a literal constant by just looking at the bottom of the screen where it says something like "ln 175" . . .

LogEvent("It happened at line 175");

but the problem with that is that if I edit any code before line 175 my literal might no longer be correct.    But the compiler knows the correct line number and I've used programming languages in the past that could just pop in the correct line number as a compile time constant. (e.g., ANSI C and Microsoft C++ support a predefined macro called
_LINE_)  Is there any way to get C# to do that?   If not are there any solutions to my problem?

Body:
CAVEATS: This is NOT an answer to the OP. I know that. But people looking for something similar may find this page.

This is not about .NET 4.

This is still ultimately a run-time solution.

But VS 2015, C#, .NET Core or .NET 4.5 allow:

using System.Runtime.CompilerServices;
using System.Diagnostics;

public static String CurrentLocation(
  [CallerFilePath] string file = null,
  [CallerLineNumber] int lineNumber = 0,
  [CallerMemberName] string method = null)
{
  String location = file;
  if (lineNumber != 0)
  {
    location += "(" + lineNumber.ToString() + ")";
  }
  if (!String.IsNullOrWhiteSpace(method))
  {
    location += ": " + method;
  }
  if (!String.IsNullOrWhiteSpace(location))
  {
    location += ": ";
  }
  return location;
}

[UPDATED USAGE]

With usage something like:

Console.Error.WriteLine(CurrentLocation() + "some message");

or

Debug.WriteLine(CurrentLocation() + "some message");


问:
Redirect from an asp.net mvc application to a .aspx file?
I have a button in an asp.net MVC 5 web application and I'm trying to redirect the user to an .aspx file.
So that when the user clicks on a button from asp.net MVC (the code of that button is in HTML), he will be redirected to a web form (.apsx).
I tried this code but it doesn't work.

```<code><button id="Login" runat="server" OnClientClick="window.open('Login.aspx', 'Login');">Login </button>
</code>```

答:
Your code does not look like a Razor View Code.
You can do it multiple ways

1.<button onclick="window.open('Login.aspx')">Login</button>
 2. Using Razor

```<code><button onclick="location.href='@Url.Action("Login","Login")'">Login</button>
</code>```

Thanks
Partha

Body:
I have a button in an asp.net MVC 5 web application and I'm trying to redirect the user to an .aspx file.
So that when the user clicks on a button from asp.net MVC (the code of that button is in HTML), he will be redirected to a web form (.apsx).
I tried this code but it doesn't work.

<button id="Login" runat="server" OnClientClick="window.open('Login.aspx', 'Login');">Login </button>

Body:
Your code does not look like a Razor View Code.
You can do it multiple ways

1.<button onclick="window.open('Login.aspx')">Login</button>
 2. Using Razor

<button onclick="location.href='@Url.Action("Login","Login")'">Login</button>

Thanks
Partha


问:
Ansible loop over range of letters in template
I'm trying to generate an Ansible template that increments on letters alphabetically rather than numbers.  Is there a function similar to range(x) that could help me?

pseudo code example

```<code>{% for letter in range(a, d) %}
{{ letter }}
{% endfor %}
</code>```

expected output

```<code>a
b
c
d
</code>```

Alternatively is there a way to convert a number into it's alphabetical equivalent in Ansible?

```<code>{% for i in range(6) %}
{{ convert(i) }}
{% endfor %}
</code>```

UPDATE

For those who are curious, here's how I ended up applying @zigam's solution.  The goal was to create xml tags with every host from a hostgroup.

In my role defaults:

```<code>ids: "ABCDEFGHIGJKLMNPQRSTUVWXYZ"
</code>```

In my template:

```<code>{% for host in groups['some_group'] %}
<host-id="{{ ids[loop.index] }}" hostName="{{ host }}" port="8888" />
{% endfor %}
</code>```

答:
you can use a custom filter plugin to do what you want

in filter_plugins/scratch_filter.py:

```<code>def scratch_filter(n):
    return chr(n)

class FilterModule(object):
    ''' Number to Character filter '''
    def filters(self):
        return {
            'scratch_filter': scratch_filter
        }
</code>```

in scratch-template.j2:

```<code>{% for x in range(101, 113) %}
    {{ x|scratch_filter }}
{% endfor %}
</code>```

in scratch_playbook.yml

```<code>---
- hosts: localhost
  tasks:

  - name: test loop
    template:
      src: "{{ playbook_dir }}/scratch-template.j2"
      dest: "{{ playbook_dir }}/scratch-template-output.txt"
</code>```

Body:
I'm trying to generate an Ansible template that increments on letters alphabetically rather than numbers.  Is there a function similar to range(x) that could help me?

pseudo code example

{% for letter in range(a, d) %}
{{ letter }}
{% endfor %}

expected output

a
b
c
d

Alternatively is there a way to convert a number into it's alphabetical equivalent in Ansible?

{% for i in range(6) %}
{{ convert(i) }}
{% endfor %}

UPDATE

For those who are curious, here's how I ended up applying @zigam's solution.  The goal was to create xml tags with every host from a hostgroup.

In my role defaults:

ids: "ABCDEFGHIGJKLMNPQRSTUVWXYZ"

In my template:

{% for host in groups['some_group'] %}
<host-id="{{ ids[loop.index] }}" hostName="{{ host }}" port="8888" />
{% endfor %}

Body:
you can use a custom filter plugin to do what you want

in filter_plugins/scratch_filter.py:

def scratch_filter(n):
    return chr(n)

class FilterModule(object):
    ''' Number to Character filter '''
    def filters(self):
        return {
            'scratch_filter': scratch_filter
        }

in scratch-template.j2:

{% for x in range(101, 113) %}
    {{ x|scratch_filter }}
{% endfor %}

in scratch_playbook.yml

---
- hosts: localhost
  tasks:

  - name: test loop
    template:
      src: "{{ playbook_dir }}/scratch-template.j2"
      dest: "{{ playbook_dir }}/scratch-template-output.txt"


问:
How to remove the external css from wordpress
How to remove external css (maxcdn.bootstrapcdn.com/font-awesome/) from wordpress code?

I used "remove_action('wp_head', 'ut-fontawesome-css'). But it's not working.

答:
remove_action() takes a function name as second argument to remove/unhook, and also the priority as third argument. In PHP a function cannot have a hyphen it its name. 'ut-fontawesome-css' looks like it is a style handle. Styles are added with wp_enqueue_style()  and removed with wp_dequeue_style(). Without looking at your parent theme code I would assume that what you should do is to dequeue this style using something like below

```<code>function remove_font_awesome() {
  wp_dequeue_style('ut-fontawesome-css');
}
add_action ('wp_enqueue_scripts', 'remove_font_awesome', 100);
</code>```

Please note, that I only assumed that ut-fontawesome-css is a correct handle to use here and i used priority as high as 100 just to 'try' to dequeue the style after it has been enqueued. A better approach would be for you to search the parent theme for where the style is being enqueued and either unhook the function if it is only enqueuing the font awesome, or hook in a function as above that would dequeue the style.

Body:
remove_action() takes a function name as second argument to remove/unhook, and also the priority as third argument. In PHP a function cannot have a hyphen it its name. 'ut-fontawesome-css' looks like it is a style handle. Styles are added with wp_enqueue_style()  and removed with wp_dequeue_style(). Without looking at your parent theme code I would assume that what you should do is to dequeue this style using something like below

function remove_font_awesome() {
  wp_dequeue_style('ut-fontawesome-css');
}
add_action ('wp_enqueue_scripts', 'remove_font_awesome', 100);

Please note, that I only assumed that ut-fontawesome-css is a correct handle to use here and i used priority as high as 100 just to 'try' to dequeue the style after it has been enqueued. A better approach would be for you to search the parent theme for where the style is being enqueued and either unhook the function if it is only enqueuing the font awesome, or hook in a function as above that would dequeue the style.


问:
Mocha using for loop for data driven test always runs last iteration
Using three scripts. Trying to read data from excel, assign it to global variable which can be accessed by all the test scripts. Want to run test for each iteration of for loop but it always goes to last iteration.

Trial.js

```<code>var mocha = require('mocha');
var other_script = require('./MyTest.js');
var global_var = require('./Global_Setup').Setup;

describe ('Test Suite', function() {

for (var i = 0; i < 2; i++) {
    global_var.testRow = i;
    //read data for row 1 and set it in global_var variables
    Call_Test(i);
}
});

function Call_Test (i) {

            console.log('i = ' + i);
            other_script.Form.FormLogin();
}
</code>```

MyTest.js

```<code>var mocha = require('mocha');
var global_var = require('./Global_Setup').Setup;

var Form = {

FormLogin: function () {

   describe ('Loop Suite', function() {
        it('Loop', function () {
            console.log('row index!!' + global_var.testRow);
            //done();
        });
    });

}

};

module.exports.Form = Form;
</code>```

Global_Setup.js

```<code>var Setup =
 {
   testRow: '',

};
module.exports.Setup = Setup;
</code>```

Output for Loop Suite is:

row index!!1

row index!!1

答:
Mocha will execute your entire loop before it starts running any test. So when your loop is over, global_var.testRow has the latest value set by the loop, and then your tests start and they all read the same value. (I have a general explanation of the order in which Mocha executes test code.)

Instead of relying on global variables, pass the value you want each test to use. Here's an example:

New Trial.js:

```<code>var other_script = require('./MyTest.js');

describe ('Test Suite', function() {
    for (var i = 0; i < 2; i++) {
        //read data for row 1 and set it in global_var variables
        Call_Test(i);
    }
});

function Call_Test (i) {
    console.log('i = ' + i);
    // Pass the value here.
    other_script.Form.FormLogin(i);
}
</code>```

New MyTest.js:

```<code>var Form = {
    // Accept a parameter here.
    FormLogin: function (i) {
        describe ('Loop Suite', function() {
            it('Loop', function () {
                console.log('row index!! ' + i);
                //done();
            });
        });
    }
};

exports.Form = Form;
</code>```

Note that you don't need to import mocha into your test files. And the Global_Setup.js file is no longer necessary with the code above.

I've modified FormLogin to accept a parameter, and Call_Test now calls FormLogin with this parameter.

Here is the output I get:

```<code>i = 0
i = 1

  Test Suite
    Loop Suite
row index!! 0
      ✓ Loop
    Loop Suite
row index!! 1
      ✓ Loop

  2 passing (19ms)
</code>```

Body:
Using three scripts. Trying to read data from excel, assign it to global variable which can be accessed by all the test scripts. Want to run test for each iteration of for loop but it always goes to last iteration.

Trial.js

var mocha = require('mocha');
var other_script = require('./MyTest.js');
var global_var = require('./Global_Setup').Setup;

describe ('Test Suite', function() {

for (var i = 0; i < 2; i++) {
    global_var.testRow = i;
    //read data for row 1 and set it in global_var variables
    Call_Test(i);
}
});

function Call_Test (i) {

            console.log('i = ' + i);
            other_script.Form.FormLogin();
}

MyTest.js

var mocha = require('mocha');
var global_var = require('./Global_Setup').Setup;

var Form = {

FormLogin: function () {

   describe ('Loop Suite', function() {
        it('Loop', function () {
            console.log('row index!!' + global_var.testRow);
            //done();
        });
    });

}

};

module.exports.Form = Form;

Global_Setup.js

var Setup =
 {
   testRow: '',

};
module.exports.Setup = Setup;

Output for Loop Suite is:

row index!!1

row index!!1

Body:
Mocha will execute your entire loop before it starts running any test. So when your loop is over, global_var.testRow has the latest value set by the loop, and then your tests start and they all read the same value. (I have a general explanation of the order in which Mocha executes test code.)

Instead of relying on global variables, pass the value you want each test to use. Here's an example:

New Trial.js:

var other_script = require('./MyTest.js');

describe ('Test Suite', function() {
    for (var i = 0; i < 2; i++) {
        //read data for row 1 and set it in global_var variables
        Call_Test(i);
    }
});

function Call_Test (i) {
    console.log('i = ' + i);
    // Pass the value here.
    other_script.Form.FormLogin(i);
}

New MyTest.js:

var Form = {
    // Accept a parameter here.
    FormLogin: function (i) {
        describe ('Loop Suite', function() {
            it('Loop', function () {
                console.log('row index!! ' + i);
                //done();
            });
        });
    }
};

exports.Form = Form;

Note that you don't need to import mocha into your test files. And the Global_Setup.js file is no longer necessary with the code above.

I've modified FormLogin to accept a parameter, and Call_Test now calls FormLogin with this parameter.

Here is the output I get:

i = 0
i = 1

  Test Suite
    Loop Suite
row index!! 0
      ✓ Loop
    Loop Suite
row index!! 1
      ✓ Loop

  2 passing (19ms)


问:
Fastest way to bcrypt 3 million records
We've inherited a system which has 3 million user logins, in a CSV broken into chunks of 500k, with unhashed passwords.

The client against advice, has decided he wants to keep the same passwords but just hash them for the new system, rather then forcing users to set new passwords, so please no replies saying "just dont do it".

We're currently using PHP to process the file to normalise the data and bcrypt the existing strings.

However running a test on 200 records, the moment we add bcrypt into the loop the process takes around 7 seconds longer.

Over time this will obviously stack up considerably.

Does anybody have other suggestions how we can convert the strings to bcrypt with more speed? I was thinking maybe there was a command line tool which we could pass the CSV into and it "knew column 4" was the password, and hash it, then save back to the file or something.

Any suggestions at this point are welcome.

It would be worth saying we need to repeat this process on the launch day so it needs to be appropriate to do with minimal downtime?

Many thanks

Update

For those who are interested, on a 2012 MBP with 2.6Ghz i7 and 8GB ram it took 9 hours to complete the initial round running 6 instances of the script each instance processing 500k users.

答:
Well, the fact that bcrypt is slow is kind of the point - it's supposed to be slow to make it more resistant to brute-force cracking.

Only a couple options I can think of:

Divvy up the task and use more threads/processors/computers.

Use a lower "complexity" factor.  This will make the hashing faster, but decrease the security of the hashes somewhat, so not a very good option.

As for making the process run quicker on launch day to avoid downtime, here's what I would suggest:

Bcrypt all 2.5 million accounts now and store the bcrypt hashes in your new system with the user accounts.

Additionally, compute a simple SHA hash of the passwords and store that in a file offline with the associated user ID.

On go live day, get all the accounts again from the legacy system.  For new accounts created after step 1, create the accounts in the new system with the Bcrypt hash.  For other accounts, check if the SHA hash (quick to compute) matches the SHA hash in the file you created in step 2.  If not, re-bcrypt the password and update the new system.  If they match, then no need to bcrypt again.

Title: Fastest way to bcrypt 3 million records


问:
How to sync all branches of two repositories (one in github and one in gitlab) preventing merge conflicts?
Repository X.git is in gitlab with all development artifacts and respective branches
I create Y.git in github using the following approach
In a common server I do a mirror of gitlab

```<code>git clone --mirror http://gitlabserverdomain/user/X.git
cd X.git
git remote add githubrepoalias https://githubserverdomain/Y.git
git push -f --tags githubrepoalias refs/heads/*:refs/heads/*
</code>```

Now I want to enable users to use either repositories for sometime and would like to sync either commits

These commits should not cause merge conflicts.

How do I do achieve the objective?

答: I see no way to prevent conflicts between changes done in GitHub and other changes done in GitLab.  Try using hooks on the servers directly to minimize it. </p>

Body:
Repository X.git is in gitlab with all development artifacts and respective branches
I create Y.git in github using the following approach
In a common server I do a mirror of gitlab

git clone --mirror http://gitlabserverdomain/user/X.git
cd X.git
git remote add githubrepoalias https://githubserverdomain/Y.git
git push -f --tags githubrepoalias refs/heads/*:refs/heads/*

Now I want to enable users to use either repositories for sometime and would like to sync either commits

These commits should not cause merge conflicts.

How do I do achieve the objective?


问:
Official Windows C/C++ Compiler and C Libraries
I've been coding C/C++ in a Linux environment, and that has been a breeze (Open terminal > Vim > code > gcc > done). I'm trying to get into doing the same in Windows, and it hasn't been nearly as easy. I've gotten Vim to run out of terminal, as I do not like IDEs, thus I'm looking for a Windows compiler that I can work with via command-line.

My problem is that I can't find the official Windows compiler for C/C++, Microsoft support was useless, and MSDN keeps pointing me to Visual Studio. There are a plethora of questions here on SO, and the web about compilers for C/C++ on Windows, with suggestions like Dev-C++, but that comes with GCC. Visual Studio supports C/C++, and I would assume that compiler is the official one, but I've had no luck in finding just the compiler. The closest I've gotten is either the Windows SDK or Visual Studio Express 2015.

Additionally, I was told in the Stackoverflow C chat room, that C is no longer a subset of C++, so does that mean I need to find 2 compilers, one for C and one for C++?

I'm also trying to figure out where C/C++ libraries are. On Linux, they're already there. Is that the case with Windows, if not where do I find their C/C++ libraries?

I didn't expect it to be so difficult to get started, nor did I expect to get lost so quickly.

答:
Interestingly enough, I found an answer to the OP's question which I believe warrants a post rather than a comment.

Microsoft does provide a stand-alone Visual C++ compiler in what they call 'build-tools'. You can get one here:

https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017-rc

(Look for Build Tools at the bottom of the page)


问:
Znc bouncer connection log
I'm trying to find connection logs to my znc server. I've reset my password and i am having trouble connecting to the server, but i cannot find the logs of the connection anywhere. I tried

systemctl status znc

and it gives me nothing, just info about znc starting.

Does anyone know if this kind of logging is supported? And if so how to activate it?

答: You can run znc --debug to get full output.

Title: Znc bouncer connection log


问:
:focus styling on custom radio input
I have a custom radio input style that is implemented more or less like this:

```<code><input type="radio" id="testradio" class="visuallyhidden custom-radio">
<label for="testradio">...</label>

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]
</code>```

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.

I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.

Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?

Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.

http://jsfiddle.net/7Ltcks3n/1/

答:
I believe this is what you are looking for, my friend. Ability to mimic default browser outlines. You should be able to use the below technique within your code to get the effect.

Demo code below, read more at source article: https://ghinda.net/article/mimic-native-focus-css/

```<code>.unreal-focus {
  outline-width: 2px;
  outline-style: solid;
  outline-color: Highlight;
}

/* WebKit gets its native focus styles.
 */
@media (-webkit-min-device-pixel-ratio:0) {
  .unreal-focus {
    outline-color: -webkit-focus-ring-color;
    outline-style: auto;
  }
}
</code>```

Title: :focus styling on custom radio input

Body:
I have a custom radio input style that is implemented more or less like this:

<input type="radio" id="testradio" class="visuallyhidden custom-radio">
...

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.

I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.

Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?

Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.

http://jsfiddle.net/7Ltcks3n/1/

Body:
I believe this is what you are looking for, my friend. Ability to mimic default browser outlines. You should be able to use the below technique within your code to get the effect.

Demo code below, read more at source article: https://ghinda.net/article/mimic-native-focus-css/

.unreal-focus {
  outline-width: 2px;
  outline-style: solid;
  outline-color: Highlight;
}

/* WebKit gets its native focus styles.
 */
@media (-webkit-min-device-pixel-ratio:0) {
  .unreal-focus {
    outline-color: -webkit-focus-ring-color;
    outline-style: auto;
  }
}