问:
Change iframe src with regex
I'm trying to change the src attribute of an iframe from http to https. For example, my string is:

```<code><p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>
</code>```

What I need is to change it to

```<code><p>Some random text <iframe src="https://some-random-link.com" width="425" height="350" frameborder="0" ></iframe></p>
</code>```

By far, I've been trying with preg_replace but no results:

```<code>$res = preg_replace( '/<iframe\s+.*?\s+src="http(.*?)".*?<\/iframe>/', '<iframe\s+.*?\s+src="https$1".</iframe>', $string);
</code>```

Thank you

答:
Why should you use a legitimate DOM parser instead of regex -- even for such a minor string manipulation?

Because regex is not "DOM-aware" -- it will treat a substring that isn't a tag as if it was a tag just because it resembles a tag.

Because your input may change slightly with or without your consent.

Because your required string manipulation may grow in complexity as your application matures.

Because using dedicated tools for the tasks they were designed to tackle, makes you appear to be a careful, considered, and professional IT craftsman/craftswoman.

First, a loop of iframe nodes using only DOM parser followed by a url parser, then substr_replace() to inject the 's' without removing any of the original characters.

Code: (Demo)

```<code>$html = <<<HTML
<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($dom->getElementsByTagName('iframe') as $iframe) {
    $src = $iframe->getAttribute('src');
    if (parse_url($src, PHP_URL_SCHEME) === 'http') {
        $iframe->setAttribute('src', substr_replace($src, 's', 4, 0));
    }
}
echo $dom->saveHTML();
</code>```

Alternatively, you can target the qualifying src attributes with XPath.

Code: (Demo)

```<code>$html = <<<HTML
<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe>
<iframe src="https://cant-touch-this.com" width="425" height="350" frameborder="0"></iframe>
</p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//iframe[starts-with(@src, 'http') and not(starts-with(@src, 'https'))]/@src") as $src) {
    $src->nodeValue = substr_replace($src->nodeValue, 's', 4, 0);
}
echo $dom->saveHTML();
</code>```

Not only will these techniques be more reliable than regex, the syntax to these parsers is far more readable by humans and will make your script much easier to manage over time.

Title: Change iframe src with regex

Body:
I'm trying to change the src attribute of an iframe from http to https. For example, my string is:

Some random text

What I need is to change it to

Some random text

By far, I've been trying with preg_replace but no results:

$res = preg_replace( '/<iframe\s+.*?\s+src="http(.*?)".*?<\/iframe>/', '<iframe\s+.*?\s+src="https$1".', $string);

Thank you

Body:
Why should you use a legitimate DOM parser instead of regex -- even for such a minor string manipulation?

Because regex is not "DOM-aware" -- it will treat a substring that isn't a tag as if it was a tag just because it resembles a tag.

Because your input may change slightly with or without your consent.

Because your required string manipulation may grow in complexity as your application matures.

Because using dedicated tools for the tasks they were designed to tackle, makes you appear to be a careful, considered, and professional IT craftsman/craftswoman.

First, a loop of iframe nodes using only DOM parser followed by a url parser, then substr_replace() to inject the 's' without removing any of the original characters.

Code: (Demo)

$html = <<<HTML
<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe></p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($dom->getElementsByTagName('iframe') as $iframe) {
    $src = $iframe->getAttribute('src');
    if (parse_url($src, PHP_URL_SCHEME) === 'http') {
        $iframe->setAttribute('src', substr_replace($src, 's', 4, 0));
    }
}
echo $dom->saveHTML();

Alternatively, you can target the qualifying src attributes with XPath.

Code: (Demo)

$html = <<<HTML
<p>Some random text <iframe src="http://some-random-link.com" width="425" height="350" frameborder="0"></iframe>
<iframe src="https://cant-touch-this.com" width="425" height="350" frameborder="0"></iframe>
</p>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//iframe[starts-with(@src, 'http') and not(starts-with(@src, 'https'))]/@src") as $src) {
    $src->nodeValue = substr_replace($src->nodeValue, 's', 4, 0);
}
echo $dom->saveHTML();

Not only will these techniques be more reliable than regex, the syntax to these parsers is far more readable by humans and will make your script much easier to manage over time.


来源: stackexchange

问:
How to replace/add lines from one file to another file
I have a one file like below example and I have requirement to grep the lines which are starting with system_props(cat file1 | grep ^system_props)..

```<code>JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi
</code>```

I have another file called say file2 which having dummy content like below.

```<code>JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi
</code>```

Now my requirement is to replace the content of cat file1 | grep ^system_props to cat file2 | grep ^system_props)

The expected output of the system_props lines should be added in the file2 which are in file1 under same sequence.

```<code>system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"
</code>```

答:
Could you please try following. Written and tested with samples.

```<code>awk '
FNR==NR{
  if(match($0,/system_props="/)){
    val=(val?val ORS:"")$0
  }
  next
}
/^system_props="/{
  if(++count==1){
    print val
  }
next
}
1
'  Input_file1   Input_file2
</code>```

Explanation: Adding detailed explanation for above code.

```<code>awk '                                ##Starting awk program from here.
FNR==NR{                             ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
  if(match($0,/system_props="/)){    ##Checking condition if match for string system_props=" is found in current line then do following.
    val=(val?val ORS:"")$0           ##Creating variable val and keep appending current line value to its value here.
  }
  next                               ##next will skip all further statements from here.
}
/^system_props="/{                   ##Checking condition if line is starting from sting system_props=" then do following.
  if(++count==1){                    ##Checking condition if variable count is 1 then do following.
    print val                        ##Printing val variable here.
  }
  next                               ##next will skip all further statements from here.
}
1                                    ##1 will print edited/non-edited line here.
'  file1  file2                      ##Mentioning Input_file names here.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a one file like below example and I have requirement to grep the lines which are starting with system_props(cat file1 | grep ^system_props)..

JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi

I have another file called say file2 which having dummy content like below.

JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`

system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"

if [ -z "$JAVA_HOME" ]; then
   if [ -d "/opt/middleware" ]; then
      JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
   fi
fi

Now my requirement is to replace the content of cat file1 | grep ^system_props to cat file2 | grep ^system_props)

The expected output of the system_props lines should be added in the file2 which are in file1 under same sequence.

system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"

Body:
Could you please try following. Written and tested with samples.

awk '
FNR==NR{
  if(match($0,/system_props="/)){
    val=(val?val ORS:"")$0
  }
  next
}
/^system_props="/{
  if(++count==1){
    print val
  }
next
}
1
'  Input_file1   Input_file2

Explanation: Adding detailed explanation for above code.

awk '                                ##Starting awk program from here.
FNR==NR{                             ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
  if(match($0,/system_props="/)){    ##Checking condition if match for string system_props=" is found in current line then do following.
    val=(val?val ORS:"")$0           ##Creating variable val and keep appending current line value to its value here.
  }
  next                               ##next will skip all further statements from here.
}
/^system_props="/{                   ##Checking condition if line is starting from sting system_props=" then do following.
  if(++count==1){                    ##Checking condition if variable count is 1 then do following.
    print val                        ##Printing val variable here.
  }
  next                               ##next will skip all further statements from here.
}
1                                    ##1 will print edited/non-edited line here.
'  file1  file2                      ##Mentioning Input_file names here.


问:
How do I populate a LiteDB database if some of my values are null
I am populating a dataGridView from an incomplete excel spreadsheet and generating the LiteDB from the dataGridView. Before the recent update, I wasn't having any issues. Now I am getting the error 'Objects cannot be cast from DBNull to other types'. I can work around this by including dummy values in the original spreadsheet. But ultimately we need to see what information we're missing. How can I accomplish this?

```<code>    public void CreateDatabase()
    {
        using (var db = new LiteDatabase(@"C:\Users\BThatcher\Documents\_Personal\Revit\MDL-Sheets\SheetDatabase04.db")) //< ----------------
        {
            var sheets = db.GetCollection<Sheet>("sheets");

            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                var sheet = new Sheet
                {
                    SheetSequence = Convert.ToInt32(row.Cells[0].Value),
                    SheetNumber = row.Cells[1].Value.ToString(),
                    SheetName = row.Cells[2].Value.ToString(),
                    AreaNumber = Convert.ToInt32(row.Cells[3].Value),
                    AreaName = row.Cells[4].Value.ToString(),
                    SheetDiscipline = row.Cells[5].Value.ToString(),
                    DisciplineSort = Convert.ToInt32(row.Cells[6].Value),
                    SheetSort = Convert.ToInt32(row.Cells[7].Value),
                    ModelName = row.Cells[8].Value.ToString(),
                    AppearsInSheetlist = row.Cells[9].Value.ToString(),
                    DesignedBy = row.Cells[10].Value.ToString(),
                    DrawnBy = row.Cells[11].Value.ToString(),
                    CheckedBy = row.Cells[12].Value.ToString(),
                    ApprovedBy = row.Cells[13].Value.ToString(),
                    SheetTotal = Convert.ToInt32(row.Cells[14].Value),
                    DesignSoftware = row.Cells[15].Value.ToString(),
                    HasPdf = row.Cells[16].Value.ToString(),
                    PdfPath = row.Cells[17].Value.ToString(),
                };
                sheets.Insert(sheet);

                this.Close();
            }
        }
    }
</code>```

答:
This error are not from LiteDB (there is no DBNull in LiteDB). It's possible this DBNull are getting from row.Cells[n].Value when you try to convert.

LiteDB support nulls and nullable values (like int?).

Body:
I am populating a dataGridView from an incomplete excel spreadsheet and generating the LiteDB from the dataGridView. Before the recent update, I wasn't having any issues. Now I am getting the error 'Objects cannot be cast from DBNull to other types'. I can work around this by including dummy values in the original spreadsheet. But ultimately we need to see what information we're missing. How can I accomplish this?

    public void CreateDatabase()
    {
        using (var db = new LiteDatabase(@"C:\Users\BThatcher\Documents\_Personal\Revit\MDL-Sheets\SheetDatabase04.db")) //< ----------------
        {
            var sheets = db.GetCollection<Sheet>("sheets");

            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                var sheet = new Sheet
                {
                    SheetSequence = Convert.ToInt32(row.Cells[0].Value),
                    SheetNumber = row.Cells[1].Value.ToString(),
                    SheetName = row.Cells[2].Value.ToString(),
                    AreaNumber = Convert.ToInt32(row.Cells[3].Value),
                    AreaName = row.Cells[4].Value.ToString(),
                    SheetDiscipline = row.Cells[5].Value.ToString(),
                    DisciplineSort = Convert.ToInt32(row.Cells[6].Value),
                    SheetSort = Convert.ToInt32(row.Cells[7].Value),
                    ModelName = row.Cells[8].Value.ToString(),
                    AppearsInSheetlist = row.Cells[9].Value.ToString(),
                    DesignedBy = row.Cells[10].Value.ToString(),
                    DrawnBy = row.Cells[11].Value.ToString(),
                    CheckedBy = row.Cells[12].Value.ToString(),
                    ApprovedBy = row.Cells[13].Value.ToString(),
                    SheetTotal = Convert.ToInt32(row.Cells[14].Value),
                    DesignSoftware = row.Cells[15].Value.ToString(),
                    HasPdf = row.Cells[16].Value.ToString(),
                    PdfPath = row.Cells[17].Value.ToString(),
                };
                sheets.Insert(sheet);

                this.Close();
            }
        }
    }


问:
Change User Role After Certain Number of Days | Laravel
I am two types of User

Reader: Can Read Books

Subscriber: Cannot Reed Books

In my user table, I have trialto column, which adds 7days to the date which the email is verified.

So my problem is to fire an event or a function that checks the trialto column when the trialto column equals to now().

I am building a Laravel Application where when the user signup and verifies his email, he is given a Reader Role as trial by Default, but after 7 days it reverts back to Subscriber if the User didn't subscribe.

I don't have the idea of how to go about this, I am thinking Laravel Scheduling can help in fixing this.

Thanks for your help.

答: You can use Task Scheduling, and save in the model the suscripted_date. With this task, you can make Laravel check for condition after certain lapse of time.


问:
Error while trying to convert string into date and format it
I'm trying to convert the string into date and format it using the below command in Webi report.

Sample field value = 20200223150301

Below is the formula being used.

```<code>= FormatDate(ToDate([Kn Credit Status].[Credit Check Date];"yyyyMMddhhmmss");"yyyymmdd")
</code>```

答:
Try "HH" for the hours since they are in 24-hour format and "MM" for the month; "mm" is the minutes.

```<code>=FormatDate(ToDate([Credit Check Date]; "yyyyMMddHHmmss"); "yyyyMMdd")
</code>```

Here's how you can find all of the FormatDate options...

Navigate to the FormatDate() function in the center function list
in the Variable Editor.

Click on the "More on this function." link in
the lower right corner.

Click on the "Custom formats" link in the
Related Information section at the bottom of the page.

You can also click on this link, but that link could go dead.

Body:
I'm trying to convert the string into date and format it using the below command in Webi report.

Sample field value = 20200223150301

Below is the formula being used.

= FormatDate(ToDate([Kn Credit Status].[Credit Check Date];"yyyyMMddhhmmss");"yyyymmdd")

Body:
Try "HH" for the hours since they are in 24-hour format and "MM" for the month; "mm" is the minutes.

=FormatDate(ToDate([Credit Check Date]; "yyyyMMddHHmmss"); "yyyyMMdd")

Here's how you can find all of the FormatDate options...

Navigate to the FormatDate() function in the center function list
in the Variable Editor.

Click on the "More on this function." link in
the lower right corner.

Click on the "Custom formats" link in the
Related Information section at the bottom of the page.

You can also click on this link, but that link could go dead.


问:
Select a specific format date
I want to select a date column in specific format - suppose my date format is MM/dd/yyyy.  I want to select it as dd/MMM/yyyy

I can do this by:

```<code>SELECT CONVERT(VARCHAR(11), myDateColumn, 106)
</code>```

The problem is that I want to select it as type DATETIME, not VARCHAR because I want to sort my grid on this column.

答:
I change the formt of date in grid_ColumnAdded event

e.Column.DefaultCellStyle.Format =
  "dd' 'MMM' 'yyyy";

ContentLicense: CC BY-SA 3.0

Title: Select a specific format date

Body:
I want to select a date column in specific format - suppose my date format is MM/dd/yyyy.  I want to select it as dd/MMM/yyyy

I can do this by:

SELECT CONVERT(VARCHAR(11), myDateColumn, 106)

The problem is that I want to select it as type DATETIME, not VARCHAR because I want to sort my grid on this column.


问:
Pass two variable to method in Laravel
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

```<code>public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}
</code>```

Route

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

答:
You can use Route Model Binding to ensure that routes will find your model based on the provided key.

Your Post model will require that you add the following method:

```<code>public function getRouteKeyName()
{
    return 'slug';
}
</code>```

Then, in your routes, you can just refer the model directly, and binding will happen automatically:

```<code>public function post(App\Post $post)
{
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}
</code>```

This enables you to to use the following route:

```<code>Route::get('post/{post}', 'PagesController@post')->name('post.show');
</code>```

Now, additionally, to ease up your reference of the comments, add them as relations to your Post model:

```<code>public function comments()
{
    return $this->hasMany(Comment::class);
}
</code>```

and your Comment model:

```<code>public function post()
{
    return $this->belongsTo(Post::class);
}
</code>```

This will allow you to shorten your controller method even more:

```<code>public function post(App\Post $post)
{
    return view('content.post',compact('post'));
}
</code>```

and in your Blade view do the following instead:

```<code>@foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
@endforeach
</code>```

Title: Pass two variable to method in Laravel

Body:
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}

Route

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

Body:
You can use Route Model Binding to ensure that routes will find your model based on the provided key.

Your Post model will require that you add the following method:

public function getRouteKeyName()
{
    return 'slug';
}

Then, in your routes, you can just refer the model directly, and binding will happen automatically:

public function post(App\Post $post)
{
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}

This enables you to to use the following route:

Route::get('post/{post}', 'PagesController@post')->name('post.show');

Now, additionally, to ease up your reference of the comments, add them as relations to your Post model:

public function comments()
{
    return $this->hasMany(Comment::class);
}

and your Comment model:

public function post()
{
    return $this->belongsTo(Post::class);
}

This will allow you to shorten your controller method even more:

public function post(App\Post $post)
{
    return view('content.post',compact('post'));
}

and in your Blade view do the following instead:

@foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
@endforeach


问:
Flutter - FutureBuilder - Search
I am using a FuturBuilder for a List of Users. I get the users through the futur: fetchpost() via API. At the start at column I implemented a Searchbar. So how can I implement that my Searchbar is searching?</p>

```<code>Container(
        child: FutureBuilder(
          future: fetchPost(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if(snapshot.connectionState == ConnectionState.waiting) {
              return Container(
                child: ...CircularPro..(),
                ),

            } else {
              return Container(
                child: Column(
                  children: <Widget>[
                    Padding(
                      child: TextField(
                        onChanged: (value) {

                        },
                        controller: searchController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                        ),

                      ),
                    ),
                    Expanded(
                      child: ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return ListTile(
                            title: Text(
                              "[" +
                              snapshot.data[index].id + "] " +
                              snapshot.data[index].firstname + " " +
                              snapshot.data[index].lastname
                            ),
                            subtitle: Text(snapshot.data[index].email),

</code>```

答:
You need to take some variable for condition on ListView and set that variable's values on search bar's submit event then setState() of widget.

```<code>String searchString = "";

</code>```

```<code>TextField(
                        onChanged: (value) {
                          setState((){
                             searchString = value;
                          });

                        },
                        controller: searchController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                        ),

                      ),
</code>```

```<code> ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return snapshot.data[index].firstname.contains(searchString)? ListTile(
                            title: Text(
                              "[" +
                              snapshot.data[index].id + "] " +
                              snapshot.data[index].firstname + " " +
                              snapshot.data[index].lastname
                            ),
                            subtitle: Text(snapshot.data[index].email),
...

:Container(),
</code>```

Title: Flutter - FutureBuilder - Search

Body:
I am using a FuturBuilder for a List of Users. I get the users through the futur: fetchpost() via API. At the start at column I implemented a Searchbar. So how can I implement that my Searchbar is searching?

Container(
        child: FutureBuilder(
          future: fetchPost(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if(snapshot.connectionState == ConnectionState.waiting) {
              return Container(
                child: ...CircularPro..(),
                ),

            } else {
              return Container(
                child: Column(
                  children: <Widget>[
                    Padding(
                      child: TextField(
                        onChanged: (value) {

                        },
                        controller: searchController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                        ),

                      ),
                    ),
                    Expanded(
                      child: ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return ListTile(
                            title: Text(
                              "[" +
                              snapshot.data[index].id + "] " +
                              snapshot.data[index].firstname + " " +
                              snapshot.data[index].lastname
                            ),
                            subtitle: Text(snapshot.data[index].email),

Body:
You need to take some variable for condition on ListView and set that variable's values on search bar's submit event then setState() of widget.

String searchString = "";

TextField(
                        onChanged: (value) {
                          setState((){
                             searchString = value;
                          });

                        },
                        controller: searchController,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.search),
                        ),

                      ),

 ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return snapshot.data[index].firstname.contains(searchString)? ListTile(
                            title: Text(
                              "[" +
                              snapshot.data[index].id + "] " +
                              snapshot.data[index].firstname + " " +
                              snapshot.data[index].lastname
                            ),
                            subtitle: Text(snapshot.data[index].email),
...

:Container(),


问:
How to correctly add a labor transaction record in a Maximo automation script
Hi I'm trying to add a labor transaction from an action automation script with the object being ASSIGNMENT in Maximo. I am currently trying the code below.

```<code>labTransSet = MXServer.getMXServer().getMboSet("LABTRANS",ui);
labTrans = labTransSet.add();
labTrans.setValue("laborcode", userLabor);
labTrans.setValue("wonum", assignWonum);
sds1=SimpleDateFormat("hh.mm aa").format(firstDate);
sds2=SimpleDateFormat("hh.mm aa").format(Date());
labTrans.setValue("STARTTIME", sds1);
labTrans.setValue("FINISHTIME", sds2);
labTransSet.save();
labTransSet.close();
</code>```

userLabor is the username of the current user

assignWonum is the assignment work order number

firstDate is the scheduled date field from the assignment

The labor record is being added correctly with the right data, but when I go to route my workflow after the script is called from a button, I am given the warning BMXAA8229W WOACTIVITY has been updated by another user and the work order does not route. I am under the impression that this is happening because the assignment object for the script is being queried at the same time I try to add and save a labor record. Does anyone know if my guess is correct or what else the problem is and how I can fix this? Thanks

答:
That error occurs because Maximo already has one version of the record loaded into memory when the record in the database is modified independently. Maximo then tries to work with the in-memory object and sees it doesn't match what is in the database and throws that error. Timing doesn't really have anything to do with it (other than that an edit happened at some point after the record was loaded into memory).

What you need to do is make sure you are modifying the exact same task/assignment/labtrans record that has already been loaded into memory. That "MXServer.getMXServer().getMboSet" stuff is guaranteed to use a new object. That is how you start a new transaction in Maximo; how you make sure you are not using anything already loaded into memory. I suspect you want to get your set off of the implicit "mbo" object the script will give to you.

Body:
Hi I'm trying to add a labor transaction from an action automation script with the object being ASSIGNMENT in Maximo. I am currently trying the code below.

labTransSet = MXServer.getMXServer().getMboSet("LABTRANS",ui);
labTrans = labTransSet.add();
labTrans.setValue("laborcode", userLabor);
labTrans.setValue("wonum", assignWonum);
sds1=SimpleDateFormat("hh.mm aa").format(firstDate);
sds2=SimpleDateFormat("hh.mm aa").format(Date());
labTrans.setValue("STARTTIME", sds1);
labTrans.setValue("FINISHTIME", sds2);
labTransSet.save();
labTransSet.close();

userLabor is the username of the current user

assignWonum is the assignment work order number

firstDate is the scheduled date field from the assignment

The labor record is being added correctly with the right data, but when I go to route my workflow after the script is called from a button, I am given the warning BMXAA8229W WOACTIVITY has been updated by another user and the work order does not route. I am under the impression that this is happening because the assignment object for the script is being queried at the same time I try to add and save a labor record. Does anyone know if my guess is correct or what else the problem is and how I can fix this? Thanks


问:
Questions about ReaderWriterLockSlim. I use readerwriterlockslim to read and write, but only show write at last in console. Why?
this is code:

```<code>class program
{
    static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
    static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            Task.Factory.StartNew(Read);
        }
        for (int i = 0; i < 1; i++)
        {
            Task.Factory.StartNew(Write);
        }
        Console.Read();
    }

    static void Read()
    {
        while (true)
        {
            rwLock.EnterReadLock();;
            Thread.Sleep(100);
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}  reading");
            rwLock.ExitReadLock();
        }
    }
    static void Write()
    {
        while (true)
        {
            rwLock.EnterWriteLock();
            Thread.Sleep(3000);
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} writing");
            rwLock.ExitWriteLock();
        }
    }
}
</code>```

I want to test the ReaderWriterLockSlim, the result what I expect is read and write alternately in console, but at last, there only write in console.

Here the result:

```<code>5 reading 2020/2/17 18:24:36
4 reading 2020/2/17 18:24:36
3 reading 2020/2/17 18:24:36
6 writing 2020/2/17 18:24:39
6 writing 2020/2/17 18:24:42
6 writing 2020/2/17 18:24:45
6 writing 2020/2/17 18:24:48
6 writing 2020/2/17 18:24:51
6 writing 2020/2/17 18:24:54
6 writing 2020/2/17 18:24:57
6 writing 2020/2/17 18:25:00
6 writing 2020/2/17 18:25:03
6 writing 2020/2/17 18:25:06
</code>```

but when use ReaderWriterLock, its alternate display. Here the result:

```<code>4 reading 2020/2/17 18:30:22
3 reading 2020/2/17 18:30:22
5 reading 2020/2/17 18:30:22
6 writing 2020/2/17 18:30:25
4 reading 2020/2/17 18:30:25
3 reading 2020/2/17 18:30:25
5 reading 2020/2/17 18:30:25
6 writing 2020/2/17 18:30:28
4 reading 2020/2/17 18:30:29
5 reading 2020/2/17 18:30:29
3 reading 2020/2/17 18:30:29
6 writing 2020/2/17 18:30:32
4 reading 2020/2/17 18:30:32
5 reading 2020/2/17 18:30:32
3 reading 2020/2/17 18:30:32
6 writing 2020/2/17 18:30:35
5 reading 2020/2/17 18:30:35
3 reading 2020/2/17 18:30:35
4 reading 2020/2/17 18:30:35
6 writing 2020/2/17 18:30:38
5 reading 2020/2/17 18:30:45
3 reading 2020/2/17 18:30:45
4 reading 2020/2/17 18:30:45
</code>```

Why does this happen, someone tell me the reason for this phenomenon？
Hope answer

答:
The problems here is that thread.Sleep() is called whilst inside the critical section.
this causes the writer thread to hold the lock for periods of 3 secs each time and releases it for a very small amount of time in which the writer thread re-acquires the lock as, in this case apparently, ReaderWriterLockSlim gives better priority to writers.

I tried calling Thread.Sleep() after releasing the lock and everything works as expected.

```<code>class LockProgram
{
    static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
    static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            Task.Factory.StartNew(Read);
        }
        for (int i = 0; i < 1; i++)
        {
            Task.Factory.StartNew(Write);
        }
        Console.Read();
    }

    static void Read()
    {
        while (true)
        {
            rwLock.EnterReadLock(); ;
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}  reading");
            rwLock.ExitReadLock();
            Thread.Sleep(100);
        }
    }
    static void Write()
    {
        while (true)
        {
            rwLock.EnterWriteLock();
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} writing");
            rwLock.ExitWriteLock();
            Thread.Sleep(3000);
        }
    }
}
</code>```

It's worth checking out the .Net reference source for ReaderWriterLockSlim and ReaderWriterLock

Body:
this is code:

class program
{
    static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
    static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            Task.Factory.StartNew(Read);
        }
        for (int i = 0; i < 1; i++)
        {
            Task.Factory.StartNew(Write);
        }
        Console.Read();
    }

    static void Read()
    {
        while (true)
        {
            rwLock.EnterReadLock();;
            Thread.Sleep(100);
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}  reading");
            rwLock.ExitReadLock();
        }
    }
    static void Write()
    {
        while (true)
        {
            rwLock.EnterWriteLock();
            Thread.Sleep(3000);
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} writing");
            rwLock.ExitWriteLock();
        }
    }
}

I want to test the ReaderWriterLockSlim, the result what I expect is read and write alternately in console, but at last, there only write in console.

Here the result:

5 reading 2020/2/17 18:24:36
4 reading 2020/2/17 18:24:36
3 reading 2020/2/17 18:24:36
6 writing 2020/2/17 18:24:39
6 writing 2020/2/17 18:24:42
6 writing 2020/2/17 18:24:45
6 writing 2020/2/17 18:24:48
6 writing 2020/2/17 18:24:51
6 writing 2020/2/17 18:24:54
6 writing 2020/2/17 18:24:57
6 writing 2020/2/17 18:25:00
6 writing 2020/2/17 18:25:03
6 writing 2020/2/17 18:25:06

but when use ReaderWriterLock, its alternate display. Here the result:

4 reading 2020/2/17 18:30:22
3 reading 2020/2/17 18:30:22
5 reading 2020/2/17 18:30:22
6 writing 2020/2/17 18:30:25
4 reading 2020/2/17 18:30:25
3 reading 2020/2/17 18:30:25
5 reading 2020/2/17 18:30:25
6 writing 2020/2/17 18:30:28
4 reading 2020/2/17 18:30:29
5 reading 2020/2/17 18:30:29
3 reading 2020/2/17 18:30:29
6 writing 2020/2/17 18:30:32
4 reading 2020/2/17 18:30:32
5 reading 2020/2/17 18:30:32
3 reading 2020/2/17 18:30:32
6 writing 2020/2/17 18:30:35
5 reading 2020/2/17 18:30:35
3 reading 2020/2/17 18:30:35
4 reading 2020/2/17 18:30:35
6 writing 2020/2/17 18:30:38
5 reading 2020/2/17 18:30:45
3 reading 2020/2/17 18:30:45
4 reading 2020/2/17 18:30:45

Why does this happen, someone tell me the reason for this phenomenon？
Hope answer

Body:
The problems here is that thread.Sleep() is called whilst inside the critical section.
this causes the writer thread to hold the lock for periods of 3 secs each time and releases it for a very small amount of time in which the writer thread re-acquires the lock as, in this case apparently, ReaderWriterLockSlim gives better priority to writers.

I tried calling Thread.Sleep() after releasing the lock and everything works as expected.

class LockProgram
{
    static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
    static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            Task.Factory.StartNew(Read);
        }
        for (int i = 0; i < 1; i++)
        {
            Task.Factory.StartNew(Write);
        }
        Console.Read();
    }

    static void Read()
    {
        while (true)
        {
            rwLock.EnterReadLock(); ;
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}  reading");
            rwLock.ExitReadLock();
            Thread.Sleep(100);
        }
    }
    static void Write()
    {
        while (true)
        {
            rwLock.EnterWriteLock();
            Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} writing");
            rwLock.ExitWriteLock();
            Thread.Sleep(3000);
        }
    }
}

It's worth checking out the .Net reference source for ReaderWriterLockSlim and ReaderWriterLock


问:
Add/remove form inputs dynamically
I have a form with one initial empty input field that I want to clone using a Add button and to remove with a Remove one.

As it's not recommended to use index for the keys with dynamic forms, I tried to use uniqid module. But each time the state is updating, keys are renewed and I don't have unique data to identify each input of the form. I can add some items, but can't remove.

input fields have no unique values, no id, how can I do ?

```<code>const Form = () => {
  const update = e => {};
  const items = [{ content: "", color: "" }];

  return (
    <Fragment>
      {items.map((item, idx) => (
        <input
          htmlFor={`item_${idx}`}
          value={item.content}
          onChange={update("item", idx)}
        />
      ))}
      <button onClick={e => dispatch(add(idx))}>Add</button>
      <button onClick={e => dispatch(remove(idx))}>Remove</button>
    </Fragment>
  );
</code>```

答:
You should create a variable that starts from 0 and adds 1 every time you add a button. That way you will keep track of everyone. Here's an example</p>

```<code>let i = 0
const add () => {
//your function to add
i++
//remember i will be the id now
}
</code>```

Title: Add/remove form inputs dynamically

Body:
I have a form with one initial empty input field that I want to clone using a Add button and to remove with a Remove one.

As it's not recommended to use index for the keys with dynamic forms, I tried to use uniqid module. But each time the state is updating, keys are renewed and I don't have unique data to identify each input of the form. I can add some items, but can't remove.

input fields have no unique values, no id, how can I do ?

const Form = () => {
  const update = e => {};
  const items = [{ content: "", color: "" }];

  return (
    <Fragment>
      {items.map((item, idx) => (
        <input
          htmlFor={`item_${idx}`}
          value={item.content}
          onChange={update("item", idx)}
        />
      ))}
      <button onClick={e => dispatch(add(idx))}>Add</button>
      <button onClick={e => dispatch(remove(idx))}>Remove</button>
    </Fragment>
  );

Body:
You should create a variable that starts from 0 and adds 1 every time you add a button. That way you will keep track of everyone. Here's an example

let i = 0
const add () => {
//your function to add
i++
//remember i will be the id now
}


问:
Calculate xy coordinates to annotate Stem Plot
Background:

I have created a bar chart as follows:

x axis: numbers (ndarray)

y axis: number frequencies (ndarray)

each frequency bar has the actual value annotated at the top of the
respective bar; to do this a have created a custom function annotations(), which makes use of plt.bar functions get_x, get_height, get_width to calculate the exact position where my label will be positioned

Using plt.bar(): - this works fine

```<code>numbers=np.array([1,2,3, 4, 5, 6, 7, 8, 9,10,11,12])
frequencies=np.array([233,266,261,220,245,231,235,263,246,169,159, 58])

x = np.arange(1,len(numbers)+1)
bars=plt.bar(x, frequencies, width=0.5)

plt.xticks(numbers)

def annotations():
    for bar in bars:
        height = bar.get_height()
        plt.annotate('{}'.format(height),
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 1),  # 1 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

annotations()

#plt.hist(frequencies, numbers)

plt.show()
</code>```

Bar Chart:

Goal:
Create a Stem Chart with annotated labels over each stem, similar to the bar chart above.

My plt.stem():

```<code>x = np.arange(1, len(numbers) + 1)  # the label locations; needs to start at 1, not 0
print(x)
stems = plt.stem(x, frequencies)
</code>```

Question:
How do I calculate the correct xy coordinates on a stem chart to place custom labels, in this case frequencies? The limitation here is that, unlike plt.bar(), plt.stem() does not have get_x, get_height() functions.

答:
You already have the height of the stems in your variable frequencies, so you don't need to try to extract them from the artists.

```<code>numbers=np.array([1,2,3, 4, 5, 6, 7, 8, 9,10,11,12])
frequencies=np.array([233,266,261,220,245,231,235,263,246,169,159, 58])

stems = plt.stem(numbers, frequencies)
plt.xticks(numbers, numbers)
for x,y in zip(numbers, frequencies):
    plt.annotate('{:.0f}'.format(y), xy=(x,y), xytext=(0,5), textcoords='offset points',ha='center')
</code>```

PS: as @ImportanceOfBeingErnest commented, this is also the case for your barplot, you could use the exact same code to annotate the bar plot.

Body:
Background:

I have created a bar chart as follows:

x axis: numbers (ndarray)

y axis: number frequencies (ndarray)

each frequency bar has the actual value annotated at the top of the
respective bar; to do this a have created a custom function annotations(), which makes use of plt.bar functions get_x, get_height, get_width to calculate the exact position where my label will be positioned

Using plt.bar(): - this works fine

numbers=np.array([1,2,3, 4, 5, 6, 7, 8, 9,10,11,12])
frequencies=np.array([233,266,261,220,245,231,235,263,246,169,159, 58])

x = np.arange(1,len(numbers)+1)
bars=plt.bar(x, frequencies, width=0.5)

plt.xticks(numbers)

def annotations():
    for bar in bars:
        height = bar.get_height()
        plt.annotate('{}'.format(height),
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 1),  # 1 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

annotations()

#plt.hist(frequencies, numbers)

plt.show()

Bar Chart:

Goal:
Create a Stem Chart with annotated labels over each stem, similar to the bar chart above.

My plt.stem():

x = np.arange(1, len(numbers) + 1)  # the label locations; needs to start at 1, not 0
print(x)
stems = plt.stem(x, frequencies)

Question:
How do I calculate the correct xy coordinates on a stem chart to place custom labels, in this case frequencies? The limitation here is that, unlike plt.bar(), plt.stem() does not have get_x, get_height() functions.

Body:
You already have the height of the stems in your variable frequencies, so you don't need to try to extract them from the artists.

numbers=np.array([1,2,3, 4, 5, 6, 7, 8, 9,10,11,12])
frequencies=np.array([233,266,261,220,245,231,235,263,246,169,159, 58])

stems = plt.stem(numbers, frequencies)
plt.xticks(numbers, numbers)
for x,y in zip(numbers, frequencies):
    plt.annotate('{:.0f}'.format(y), xy=(x,y), xytext=(0,5), textcoords='offset points',ha='center')

PS: as @ImportanceOfBeingErnest commented, this is also the case for your barplot, you could use the exact same code to annotate the bar plot.


问:
Can you use helper functions inside R6 objects?
I'm trying to avoid repetition inside an R6 object. There are calculated/derived values that must be updated each time one of the inputs is updated.

The Cube object below demonstrates the problem. If I update any of width, height or depth, it follows that volume must be updated.

In this case, the formula is trivial, but in real-world cases that won't always be the case.  It is possible to store the knowledge of volCalc someplace, and to allow set_width to use that function to update volume when they are updated?

Right now, i can create the object using the object code below:

```<code>R> cc <- Cube$new(width = 5, height = 6, depth = 7)
</code>```

but it breaks on update

```<code>R> cc$set_width(10)
Error in volCalc(self$width, self$height, self$depth) :
  could not find function "volCalc"
</code>```

As you can see, I put the knowledge of how to calculate the volume of a cube (volCalc) in two places; but alas cc$set_width and friends cannot find it...

```<code>Cube <- R6Class("Cube",
  public = list(
    width = NULL,
    height = NULL,
    depth = NULL,
    volume = NULL,

    initialize = function(width, height, depth) {
      self$width <- width
      self$height <- height
      self$depth <- depth

      volCalc = function(W, H, D) W * H * D

      self$volume <- volCalc(width, height, depth)
    },

    volCalc = function(W, H, D) {
      self$volume <- W * H * D
      invisible(self)
    },

    set_width = function(nWidth) {
      self$width <- nWidth
      volCalc(self$width, self$height, self$depth)
      invisible(self)
    },

    set_height = function(nHeight) {
      self$height <- nHeight
      volCalc(self$height, self$height, self$depth)
      invisible(self)
    },

    set_depth = function(nDepth) {
      self$depth <- nDepth
      volCalc(self$depth, self$depth, self$depth)
      invisible(self)
    }
  )
)
</code>```

答:
You need to tell your class where to find volCalc. It will find it in self. So all you need to do is make the internal calls to volCalc be self$volCalc. Then you can do this:

```<code>cc <- Cube$new(width = 5, height = 6, depth = 7)
cc
#> <Cube>
#>   Public:
#>     clone: function (deep = FALSE)
#>     depth: 7
#>     height: 6
#>     initialize: function (width, height, depth)
#>     set_depth: function (nDepth)
#>     set_height: function (nHeight)
#>     set_width: function (nWidth)
#>     volCalc: function (W, H, D)
#>     volume: 210
#>     width: 5

cc$set_width(10)
cc
#> <Cube>
#>   Public:
#>     clone: function (deep = FALSE)
#>     depth: 7
#>     height: 6
#>     initialize: function (width, height, depth)
#>     set_depth: function (nDepth)
#>     set_height: function (nHeight)
#>     set_width: function (nWidth)
#>     volCalc: function (W, H, D)
#>     volume: 420
#>     width: 10
</code>```

Body:
I'm trying to avoid repetition inside an R6 object. There are calculated/derived values that must be updated each time one of the inputs is updated.

The Cube object below demonstrates the problem. If I update any of width, height or depth, it follows that volume must be updated.

In this case, the formula is trivial, but in real-world cases that won't always be the case.  It is possible to store the knowledge of volCalc someplace, and to allow set_width to use that function to update volume when they are updated?

Right now, i can create the object using the object code below:

R> cc <- Cube$new(width = 5, height = 6, depth = 7)

but it breaks on update

R> cc$set_width(10)
Error in volCalc(self$width, self$height, self$depth) :
  could not find function "volCalc"

As you can see, I put the knowledge of how to calculate the volume of a cube (volCalc) in two places; but alas cc$set_width and friends cannot find it...

Cube <- R6Class("Cube",
  public = list(
    width = NULL,
    height = NULL,
    depth = NULL,
    volume = NULL,

    initialize = function(width, height, depth) {
      self$width <- width
      self$height <- height
      self$depth <- depth

      volCalc = function(W, H, D) W * H * D

      self$volume <- volCalc(width, height, depth)
    },

    volCalc = function(W, H, D) {
      self$volume <- W * H * D
      invisible(self)
    },

    set_width = function(nWidth) {
      self$width <- nWidth
      volCalc(self$width, self$height, self$depth)
      invisible(self)
    },

    set_height = function(nHeight) {
      self$height <- nHeight
      volCalc(self$height, self$height, self$depth)
      invisible(self)
    },

    set_depth = function(nDepth) {
      self$depth <- nDepth
      volCalc(self$depth, self$depth, self$depth)
      invisible(self)
    }
  )
)

Body:
You need to tell your class where to find volCalc. It will find it in self. So all you need to do is make the internal calls to volCalc be self$volCalc. Then you can do this:

cc <- Cube$new(width = 5, height = 6, depth = 7)
cc
#> <Cube>
#>   Public:
#>     clone: function (deep = FALSE)
#>     depth: 7
#>     height: 6
#>     initialize: function (width, height, depth)
#>     set_depth: function (nDepth)
#>     set_height: function (nHeight)
#>     set_width: function (nWidth)
#>     volCalc: function (W, H, D)
#>     volume: 210
#>     width: 5

cc$set_width(10)
cc
#> <Cube>
#>   Public:
#>     clone: function (deep = FALSE)
#>     depth: 7
#>     height: 6
#>     initialize: function (width, height, depth)
#>     set_depth: function (nDepth)
#>     set_height: function (nHeight)
#>     set_width: function (nWidth)
#>     volCalc: function (W, H, D)
#>     volume: 420
#>     width: 10


问:
How to catch error from a forked child process?
Node.js v8.11.1

There are two files: parent.js and child.js.

Parent

```<code>const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
  forked.kill();
});

forked.on('error', (err) => {
  console.log('Error from child', err);
});

forked.send({ hello: 'world' });
</code>```

Child

```<code>process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  throw new Error('not good: ' + err);
}
</code>```

There is an intentional typo in the child script - seTimeout. When I execute parent node parent.js, I get:

```<code>/media/trex/safe/Development/child.js:12
  throw new Error('not good: ' + err);
  ^

Error: not good: ReferenceError: seTimeout is not defined
    at Object.<anonymous> (/media/trex/safe/Development/siren/sentinl-private/server/lib/actions/report/child.js:12:9)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
</code>```

The error was not caught by the parent. How to catch the error by the parent?

Update 1

As I see here https://github.com/nodejs/node/issues/15734 this is working as intended. Maybe there is another event to catch errors or something else?

Update 2

Now I can catch an error the following way. But I'm not sure it is the best way to do it.

Parent

```<code>const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  if (msg.error) {
    console.error(msg.error);
  } else {
    console.log('Message from child', msg);
  }
  forked.kill();
});

forked.send({ hello: 'world' });
</code>```

Child

```<code>process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  process.send({error: err.message});
}
</code>```

答:
Why not to use the array of the option.stdio? This array has three elements [subprocess.stdin, subprocess.stdout, subprocess.stderr], thus you just want to console the errors and not anything else.

Therefore you'd use stdio: ['ignore', 'ignore', 'inherit']

Parent

const { execSync } = require('child_process')

try {
  execSync('node myNodeChildScript.js', { stdio: ['ignore', 'ignore', 'inherit'] })
} catch (err) {
  console.error(Error(err))
  process.exit(1)
}
```
<h1>Child</h1>
<pre class="lang-js prettyprint-override"><code>console.log('Some log') // this will not be output to parent
if (someError()) {
  console.error('There was an error') // this will be output to parent console
  process.exit(1) // exit with error
}
</code>```

Body:
Node.js v8.11.1

There are two files: parent.js and child.js.

Parent

const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
  forked.kill();
});

forked.on('error', (err) => {
  console.log('Error from child', err);
});

forked.send({ hello: 'world' });

Child

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  throw new Error('not good: ' + err);
}

There is an intentional typo in the child script - seTimeout. When I execute parent node parent.js, I get:

/media/trex/safe/Development/child.js:12
  throw new Error('not good: ' + err);
  ^

Error: not good: ReferenceError: seTimeout is not defined
    at Object.<anonymous> (/media/trex/safe/Development/siren/sentinl-private/server/lib/actions/report/child.js:12:9)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

The error was not caught by the parent. How to catch the error by the parent?

Update 1

As I see here https://github.com/nodejs/node/issues/15734 this is working as intended. Maybe there is another event to catch errors or something else?

Update 2

Now I can catch an error the following way. But I'm not sure it is the best way to do it.

Parent

const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  if (msg.error) {
    console.error(msg.error);
  } else {
    console.log('Message from child', msg);
  }
  forked.kill();
});

forked.send({ hello: 'world' });

Child

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  process.send({error: err.message});
}

Body:
Why not to use the array of the option.stdio? This array has three elements [subprocess.stdin, subprocess.stdout, subprocess.stderr], thus you just want to console the errors and not anything else.

Therefore you'd use stdio: ['ignore', 'ignore', 'inherit']

Parent

const { execSync } = require('child_process')

try {
  execSync('node myNodeChildScript.js', { stdio: ['ignore', 'ignore', 'inherit'] })
} catch (err) {
  console.error(Error(err))
  process.exit(1)
}

Child

console.log('Some log') // this will not be output to parent
if (someError()) {
  console.error('There was an error') // this will be output to parent console
  process.exit(1) // exit with error
}


问:
how to set next page rule with CrawlSpider?
I am tring scrape email adress from a website. in order to do that i have to extract in every single link which is  in a list then on that extract page i will extract the email address.the problem is the nextpage button conatins upto 50. but if i change the url with a slash and input 51. it also go a new page.i want use for loop for next page link. as example i will use for loop from 1 to 999 it will update the next page url. below is my code.it's working fine as long as the next_page button is available.

```<code>   # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class BestMoviesSpider(CrawlSpider):
    name = 'best_movies'
    allowed_domains = ['dastelefonbuch.de']

    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'

    def start_requests(self):
        yield scrapy.Request(url='https://www.dastelefonbuch.de/Suche/Textilien%20Gmbh',
                             headers={
                                 'User-Agent': self.user_agent
                             })

    rules = (
        Rule(LinkExtractor(
            restrict_xpaths="//a[@class=' name']"),
            callback='parse_item', follow=True,
            process_request='set_user_agent'),
        Rule(LinkExtractor(

            restrict_xpaths="//a[@class='nextLink next'][2]"), follow=True,
            process_request='set_user_agent')
    )

    def set_user_agent(self, request):
        request.headers['User-Agent'] = self.user_agent
        return request

    def parse_item(self, response):
        yield {
            'email': response.xpath(
                "//a[starts-with(@href,'mailto')]/@href").get(),

        }
</code>```

答: Check your url in the start_requests function. It is not correct. I think you meant: "https://www.dastelefonbuch.de/Suche/Textilien"</p>

Body:
I am tring scrape email adress from a website. in order to do that i have to extract in every single link which is  in a list then on that extract page i will extract the email address.the problem is the nextpage button conatins upto 50. but if i change the url with a slash and input 51. it also go a new page.i want use for loop for next page link. as example i will use for loop from 1 to 999 it will update the next page url. below is my code.it's working fine as long as the next_page button is available.

   # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class BestMoviesSpider(CrawlSpider):
    name = 'best_movies'
    allowed_domains = ['dastelefonbuch.de']

    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'

    def start_requests(self):
        yield scrapy.Request(url='https://www.dastelefonbuch.de/Suche/Textilien%20Gmbh',
                             headers={
                                 'User-Agent': self.user_agent
                             })

    rules = (
        Rule(LinkExtractor(
            restrict_xpaths="//a[@class=' name']"),
            callback='parse_item', follow=True,
            process_request='set_user_agent'),
        Rule(LinkExtractor(

            restrict_xpaths="//a[@class='nextLink next'][2]"), follow=True,
            process_request='set_user_agent')
    )

    def set_user_agent(self, request):
        request.headers['User-Agent'] = self.user_agent
        return request

    def parse_item(self, response):
        yield {
            'email': response.xpath(
                "//a[starts-with(@href,'mailto')]/@href").get(),

        }


问:
convert all times to 0:00
How would I convert all dates which are currently YYYY-MM-DD Time, where the Time is 00:00.

Below is my code and I attach a pic

```<code>    select* from(SELECT
    Date,
    Depot,
     Vehicle,
     Quantity as [Ltrs],
     OdoReadingMiles,
     LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage
     ,OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles]
     ,(OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG]
     ,case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10 then 1 else 0 end as [Anomaly]
     FROM [Fleet].[DwhTriscanChargeouts] )as x
     WHERE x.Anomaly=0
     ORDER BY 2,1
</code>```

答:
In SQL Server, you can just convert to a date:

```<code>select convert(date, datetimecol) as datecol
</code>```

It is unclear what columns you are talking about, so the above generically answers your question.

Title: convert all times to 0:00

Body:
How would I convert all dates which are currently YYYY-MM-DD Time, where the Time is 00:00.

Below is my code and I attach a pic

    select* from(SELECT
    Date,
    Depot,
     Vehicle,
     Quantity as [Ltrs],
     OdoReadingMiles,
     LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage
     ,OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles]
     ,(OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG]
     ,case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10 then 1 else 0 end as [Anomaly]
     FROM [Fleet].[DwhTriscanChargeouts] )as x
     WHERE x.Anomaly=0
     ORDER BY 2,1

Body:
In SQL Server, you can just convert to a date:

select convert(date, datetimecol) as datecol

It is unclear what columns you are talking about, so the above generically answers your question.


问:
SQL error Column count doesn't match value count at row 1
Am I missing an error with the following to insert into a table with four columns, message_id (auto-incremented) message_sender, message_reciever, message_body. I have checked similar questions and haven't found the solution.
'''</p>

```<code>        <% String sender_id = request.getParameter("message_sender");
        String reciever_id = request.getParameter("message_reciever");
        String message = request.getParameter("message_body");

        try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/fyp", "root", "Kmd116352323!");
        Statement st = con.createStatement();

        st.executeUpdate("INSERT INTO messages(message_sender,message_reciever,message_body) VALUES('"+sender_id+", "+reciever_id+" , "+message+" ')");

        out.println("Your request has been noted."
                + " Please return to your user profile or log out");

        } catch(Exception e){
        out.println(e);
                }
        %>
</code>```

答:
You should not concatenate values into a query string. It makes your code vulnerable to SQL injection, or mistakes like forgetting quotes around values. The specific problem in your case is that you have a quote before the first value and a quote after the last value, which makes it a single value instead of three separate values.

However, instead of fixing the immediate problem by adding those missing quotes, you should switch to using a prepared statement:

try (PreparedStatement pstmt = connection.prepareStatement(
        "INSERT INTO messages(message_sender,message_reciever,message_body) VALUES(?, ?, ?)") {
    pstmt.setString(1, sender_id);
    pstmt.setString(2, reciever_id);
    pstmt.setString(3, message);

    pstmt.executeUpdate();
}
```

As an aside, you really should not put data access in a JSP. It belongs in a DAO or service class.

Body:
Am I missing an error with the following to insert into a table with four columns, message_id (auto-incremented) message_sender, message_reciever, message_body. I have checked similar questions and haven't found the solution.
'''

        <% String sender_id = request.getParameter("message_sender");
        String reciever_id = request.getParameter("message_reciever");
        String message = request.getParameter("message_body");

        try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/fyp", "root", "Kmd116352323!");
        Statement st = con.createStatement();

        st.executeUpdate("INSERT INTO messages(message_sender,message_reciever,message_body) VALUES('"+sender_id+", "+reciever_id+" , "+message+" ')");

        out.println("Your request has been noted."
                + " Please return to your user profile or log out");

        } catch(Exception e){
        out.println(e);
                }
        %>

Body:
You should not concatenate values into a query string. It makes your code vulnerable to SQL injection, or mistakes like forgetting quotes around values. The specific problem in your case is that you have a quote before the first value and a quote after the last value, which makes it a single value instead of three separate values.

However, instead of fixing the immediate problem by adding those missing quotes, you should switch to using a prepared statement:

try (PreparedStatement pstmt = connection.prepareStatement(
        "INSERT INTO messages(message_sender,message_reciever,message_body) VALUES(?, ?, ?)") {
    pstmt.setString(1, sender_id);
    pstmt.setString(2, reciever_id);
    pstmt.setString(3, message);

    pstmt.executeUpdate();
}

As an aside, you really should not put data access in a JSP. It belongs in a DAO or service class.


问:
Hadoop mysql limiting the reducers
I'm using hadoop to update some records in a mysql db...
The issue that I'm seeing is that in certain cases, multiple reducers are launched for the same key set.
I've seen up to 2 reducers running on different slaves for the same key.
This leads to the issue of both reducers updating the same record in the db.

I was thinking of turning off the autocommit mode to alleviate this issue....
but and doing the commit as part of the "cleanup" operation in the reducer, but was wondering what to do with the reducer(s) that lag behind...would the cleanup operation still be called for that...if so....is there a way to tell if the reducer finished normally or not, since I'd like to call "rollback" on the reducer(s) that didn't finish processing the data entirely?

答:
Two things:

I really doubt that two (EQUAL) keys inside a reduce get partitioned to different slaves. Since HashPartitioner is used. You should override hashCode on your key class.

You have the option to set the number of reduce tasks. It can be done with an API call to Job.setNumReduceTasks(X). Obviously you can set this to 1.

Title: Hadoop mysql limiting the reducers


问:
Does copy of asio::strand create a new executor?
I have a copy of asio::io_service::strand.
Are the copied strand and its source different executors? In other words is it possible that a function passed to the copied strand and another function passed to the source strand will be executed in the same time by two different threads?

Or are both such strands logically "one strand" meaning no work passed to any of them will be executed together with other work passed to them?

See example

```<code>asio::io_service ioService;

asio::io_service::strand strandFromIoService{ioService};
asio::io_service::strand strandFromStrand{strandFromIoService};

strandFromIoService.post(boost::bind(&firstFunction));
strandFromStrand.post(boost::bind(&secondFunction));

// then use a pool of threads to service io_service ...
// can firstFunction and secondFunction be executed in one time?
</code>```

答:
The answer is no.

strand class has two attributes only

```<code>class io_service::strand
{
public:
  // ...
private:
  asio::detail::strand_service& service_;
  asio::detail::strand_service::implementation_type impl_;
};
</code>```

impl_ is a pointer to strand_impl:

```<code>typedef strand_impl* implementation_type;
</code>```

There is also no user-defined copy constructor in strand class.
It is strand_impl, which contains que, mutex, counter and all stuff related to multithreading. And this stuff is not changed on strand copy since strand has only a pointer to it and only pointer is copied (saying nothing about io_service reference, but this reference has obviously no impact on strand copy)

Therefore a copy and a source strands are logically the same strand. They represent the same executor.

This also matches my experiments. firstFunction and secondFunction in question's example were executed indeed sequentially by 2 threads.

Body:
I have a copy of asio::io_service::strand.
Are the copied strand and its source different executors? In other words is it possible that a function passed to the copied strand and another function passed to the source strand will be executed in the same time by two different threads?

Or are both such strands logically "one strand" meaning no work passed to any of them will be executed together with other work passed to them?

See example

asio::io_service ioService;

asio::io_service::strand strandFromIoService{ioService};
asio::io_service::strand strandFromStrand{strandFromIoService};

strandFromIoService.post(boost::bind(&firstFunction));
strandFromStrand.post(boost::bind(&secondFunction));

// then use a pool of threads to service io_service ...
// can firstFunction and secondFunction be executed in one time?

Body:
The answer is no.

strand class has two attributes only

class io_service::strand
{
public:
  // ...
private:
  asio::detail::strand_service& service_;
  asio::detail::strand_service::implementation_type impl_;
};

impl_ is a pointer to strand_impl:

typedef strand_impl* implementation_type;

There is also no user-defined copy constructor in strand class.
It is strand_impl, which contains que, mutex, counter and all stuff related to multithreading. And this stuff is not changed on strand copy since strand has only a pointer to it and only pointer is copied (saying nothing about io_service reference, but this reference has obviously no impact on strand copy)

Therefore a copy and a source strands are logically the same strand. They represent the same executor.

This also matches my experiments. firstFunction and secondFunction in question's example were executed indeed sequentially by 2 threads.


问:
Is it possible to assign a pod of StatefulSet to a specific node of a Kubernetes cluster?
I have a 5 node cluster(1-master/4-worker). Is it possible to configure a StatefulSet where I can make a pod(s) to run on a given node knowing it has sufficient capacity rather Kubernetes Scheduler making this decision?

Lets say, my StatefulSet create 4 pods(replicas: 4) as myapp-0,myapp-1,myapp-2 and myapp-3. Now what I am looking for is:

myapp-0 pod-- get scheduled over---> worker-1

myapp-1 pod-- get scheduled over---> worker-2

myapp-2 pod-- get scheduled over---> worker-3

myapp-3 pod-- get scheduled over---> worker-4

Please let me know if it can be achieved somehow? Because if I add a toleration to pods of a StatefulSet, it will be same for all the pods and all of them will get scheduled over a single node matching the taint.

Thanks, J

答:
You can delegate responsibility for scheduling arbitrary subsets of pods to your own custom scheduler(s) that run(s) alongside, or instead of, the default Kubernetes scheduler.

You can write your own custom  scheduler. A custom scheduler can be written in any language and can be as simple or complex as you need. Below is a very simple example of a custom scheduler written in Bash that assigns a node randomly. Note that you need to run this along with kubectl proxy for it to work.

SERVER='localhost:8001'

while true;

do

    for PODNAME in $(kubectl --server $SERVER get pods -o json | jq '.items[] | select(.spec.schedulerName == "my-scheduler") | select(.spec.nodeName == null) | .metadata.name' | tr -d '"')

;

    do

        NODES=($(kubectl --server $SERVER get nodes -o json | jq '.items[].metadata.name' | tr -d '"'))

        NUMNODES=${#NODES[@]}

        CHOSEN=${NODES[$[$RANDOM % $NUMNODES]]}

        curl --header "Content-Type:application/json" --request POST --data '{"apiVersion":"v1", "kind": "Binding", "metadata": {"name": "'$PODNAME'"}, "target": {"apiVersion": "v1", "kind"

: "Node", "name": "'$CHOSEN'"}}' http://$SERVER/api/v1/namespaces/default/pods/$PODNAME/binding/

        echo "Assigned $PODNAME to $CHOSEN"

    done

    sleep 1

done
```

<p>Then just in your StatefulSet configuration file under specification section you will have to add <code>schedulerName: your-scheduler</code> line. </p>

<p>You can also use pod affinity:.</p>

<p>Example:</p>

```apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis-cache
spec:
  selector:
    matchLabels:
      app: store
  replicas: 3
  template:
    metadata:
      labels:
        app: store
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - store
            topologyKey: "kubernetes.io/hostname"
      containers:
      - name: redis-server
        image: redis:3.2-alpine
```

<p>The below yaml snippet of the webserver statefuset has podAntiAffinity and podAffinity configured. This informs the scheduler that all its replicas are to be co-located with pods that have selector label <strong>app=store</strong>. This will also ensure that each web-server replica does not co-locate on a single node.</p>

```apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web-server
spec:
  selector:
    matchLabels:
      app: web-store
  replicas: 3
  template:
    metadata:
      labels:
        app: web-store
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - web-store
            topologyKey: "kubernetes.io/hostname"
        podAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - store
            topologyKey: "kubernetes.io/hostname"
      containers:
      - name: web-app
        image: nginx:1.12-alpine
```

<p>If we create the above two deployments, our three node cluster should look like below.</p>

```node-1              node-2           node-3
webserver-1     webserver-2          webserver-3
cache-1             cache-2          cache-3
```

<p>The above example uses PodAntiAffinity rule with topologyKey: <code>"kubernetes.io/hostname"</code> to deploy the redis cluster so that no two instances are located on the same host</p>

<p>You can simply define three replicas of specific pod and define particular pod configuration file, egg.:
There is label: nodeName which is the simplest form of node selection constraint, but due to its limitations it is typically not used. nodeName is a field of PodSpec. If it is non-empty, the scheduler ignores the pod and the kubelet running on the named node tries to run the pod. Thus, if nodeName is provided in the PodSpec, it takes precedence over the above methods for node selection.</p>

<p>Here is an example of a pod config file using the nodeName field:</p>

```apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
  nodeName: kube-worker-1
```

More information about scheduler: custom-scheduler.

Take a look on this article: assigining-pods-kubernetes.

Body:
You can delegate responsibility for scheduling arbitrary subsets of pods to your own custom scheduler(s) that run(s) alongside, or instead of, the default Kubernetes scheduler.

You can write your own custom  scheduler. A custom scheduler can be written in any language and can be as simple or complex as you need. Below is a very simple example of a custom scheduler written in Bash that assigns a node randomly. Note that you need to run this along with kubectl proxy for it to work.

SERVER='localhost:8001'

while true;

do

    for PODNAME in $(kubectl --server $SERVER get pods -o json | jq '.items[] | select(.spec.schedulerName == "my-scheduler") | select(.spec.nodeName == null) | .metadata.name' | tr -d '"')

;

    do

        NODES=($(kubectl --server $SERVER get nodes -o json | jq '.items[].metadata.name' | tr -d '"'))

        NUMNODES=${#NODES[@]}

        CHOSEN=${NODES[$[$RANDOM % $NUMNODES]]}

        curl --header "Content-Type:application/json" --request POST --data '{"apiVersion":"v1", "kind": "Binding", "metadata": {"name": "'$PODNAME'"}, "target": {"apiVersion": "v1", "kind"

: "Node", "name": "'$CHOSEN'"}}' http://$SERVER/api/v1/namespaces/default/pods/$PODNAME/binding/

        echo "Assigned $PODNAME to $CHOSEN"

    done

    sleep 1

done

Then just in your StatefulSet configuration file under specification section you will have to add schedulerName: your-scheduler line.

You can also use pod affinity:.

Example:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis-cache
spec:
  selector:
    matchLabels:
      app: store
  replicas: 3
  template:
    metadata:
      labels:
        app: store
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - store
            topologyKey: "kubernetes.io/hostname"
      containers:
      - name: redis-server
        image: redis:3.2-alpine

The below yaml snippet of the webserver statefuset has podAntiAffinity and podAffinity configured. This informs the scheduler that all its replicas are to be co-located with pods that have selector label app=store. This will also ensure that each web-server replica does not co-locate on a single node.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web-server
spec:
  selector:
    matchLabels:
      app: web-store
  replicas: 3
  template:
    metadata:
      labels:
        app: web-store
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - web-store
            topologyKey: "kubernetes.io/hostname"
        podAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - store
            topologyKey: "kubernetes.io/hostname"
      containers:
      - name: web-app
        image: nginx:1.12-alpine

If we create the above two deployments, our three node cluster should look like below.

node-1              node-2           node-3
webserver-1     webserver-2          webserver-3
cache-1             cache-2          cache-3

The above example uses PodAntiAffinity rule with topologyKey: "kubernetes.io/hostname" to deploy the redis cluster so that no two instances are located on the same host

You can simply define three replicas of specific pod and define particular pod configuration file, egg.:
There is label: nodeName which is the simplest form of node selection constraint, but due to its limitations it is typically not used. nodeName is a field of PodSpec. If it is non-empty, the scheduler ignores the pod and the kubelet running on the named node tries to run the pod. Thus, if nodeName is provided in the PodSpec, it takes precedence over the above methods for node selection.

Here is an example of a pod config file using the nodeName field:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
  nodeName: kube-worker-1

More information about scheduler: custom-scheduler.

Take a look on this article: assigining-pods-kubernetes.


问:
How can I change the text "learn more" in video preroll
I m using google-ima SDK for iOS version 3.0.beta.4.

I try to change the text "Learn more" which appear at the sdk's UIViewController.

I'm looking for that for some time, and didn't find the answer.

Does someone achieve it?

Screenshot:

答:
You can only change the language:</p>

```<code>    let s = IMASettings()
    s.language = "it"
    adsLoader = IMAAdsLoader.init(settings: s)
    adsLoader?.delegate = self
</code>```

Body:
You can only change the language:

    let s = IMASettings()
    s.language = "it"
    adsLoader = IMAAdsLoader.init(settings: s)
    adsLoader?.delegate = self


问:
Pexpect - Read from constantly outputting shell
I'm attempting to have pexpect begin running a command which basically continually outputs some information every few milliseconds until cancelled with Ctrl + C.

I've attempted getting pexpect to log to a file, though these outputs are simply ignored and are never logged.

```<code>child = pexpect.spawn(command)
child.logfile = open('mylogfile.txt', 'w')
</code>```

This results in the command being logged with an empty output.

I have also attempted letting the process run for a few seconds, then sending an interrupt to see if that logs the data, but this again, results in an almost empty log.

```<code>child = pexpect.spawn(command)
child.logfile = open('mylogfile.txt', 'w')
time.sleep(5)
child.send('\003')
child.expect('$')
</code>```

This is the data in question:

image showing the data constantly printing to the terminal

I've attempted the solution described here: Parsing pexpect output though it hasn't worked for me and results in a timeout.

答:
Managed to get it working by using Python Subprocess for this, not sure of a way to do it with Pexpect, but this got what I described.</p>

```<code>def echo(self, n_lines):
    output = []
    if self.running is False:
        # start shell
        self.current_shell = Popen(cmd, stdout=PIPE, shell=True)
        self.running = True

        i = 0
        # Read the lines from stdout, break after reading the desired amount of lines.
        for line in iter(self.current_shell.stdout.readline, ''):
            output.append(line[0:].decode('utf-8').strip())
            if i == n_lines:
                break
            i += 1
    return output
</code>```

Body:
I'm attempting to have pexpect begin running a command which basically continually outputs some information every few milliseconds until cancelled with Ctrl + C.

I've attempted getting pexpect to log to a file, though these outputs are simply ignored and are never logged.

child = pexpect.spawn(command)
child.logfile = open('mylogfile.txt', 'w')

This results in the command being logged with an empty output.

I have also attempted letting the process run for a few seconds, then sending an interrupt to see if that logs the data, but this again, results in an almost empty log.

child = pexpect.spawn(command)
child.logfile = open('mylogfile.txt', 'w')
time.sleep(5)
child.send('\003')
child.expect('$')

This is the data in question:

image showing the data constantly printing to the terminal

I've attempted the solution described here: Parsing pexpect output though it hasn't worked for me and results in a timeout.

Body:
Managed to get it working by using Python Subprocess for this, not sure of a way to do it with Pexpect, but this got what I described.

def echo(self, n_lines):
    output = []
    if self.running is False:
        # start shell
        self.current_shell = Popen(cmd, stdout=PIPE, shell=True)
        self.running = True

        i = 0
        # Read the lines from stdout, break after reading the desired amount of lines.
        for line in iter(self.current_shell.stdout.readline, ''):
            output.append(line[0:].decode('utf-8').strip())
            if i == n_lines:
                break
            i += 1
    return output


问:
Epicor documentation on Erp, Erp.UI, Ice.Lib, and other higher level namespaces
Does anyone know if there is documentation available in Epicor on what methods/properties are accessible in the "higher level" namespaces like Erp, Erp.UI, Erp.UI.App, Ice.Lib, etc?
For Example

I know we have the object explorer which is incredibly useful in most cases, but it does not appear to show anything beyond UI objects, Adapters, and EpiDataViews. UI objects Data Objects Adapters

答: I posted this question to the EpiUsers forums as well (https://www.epiusers.help/t/erp-ui-app-namespace-documentation/64503) and it turns out this isn't officially documented anywhere. However, you can still get this information by de-compiling.</p>


问:
Weird PHP error: 'Can't use function return value in write context'
I'm getting this error and I can't make head or tail of it.

The exact error message is:

Fatal error: Can't use function return
  value in write context in
  /home/curricle/public_html/descarga/index.php
  on line 48

Line 48 is:

```<code>if (isset($_POST('sms_code') == TRUE ) {
</code>```

What could be going on here?

Here's the full function:

```<code>function validate_sms_code() {

    $state = NOTHING_SUBMITED;

    if (isset($_POST('sms_code') == TRUE ) {
        $sms_code = clean_up($_POST('sms_code'));
        $return_code = get_sepomo_code($sms_code);

        switch($return_code) {

          case 1:
            //no error
            $state = CORRECT_CODE;
            break;

          case 2:
            // code already used
            $state = CODE_ALREADY_USED;
            break;

          case 3:
            // wrong code
            $state = WRONG_CODE;
            break;

          case 4:
            // generic error
            $state = UNKNOWN_SEPOMO_CODE;
            break;

          default:
            // unknown error
            $state = UNKNOWN_SEPOMO_CODE;
            throw new Exception('Unknown sepomo code: ' . $return_code);
            break;
        }

    } else {
        $state = NOTHING_SUBMITED;
    }
    dispatch_on_state($state);
}
</code>```

答:
This error is quite right and highlights a contextual syntax issue. Can be reproduced by performing any kind "non-assignable" syntax. For instance:

function Syntax($hello) { .... then attempt to call the function as though a property and assign a value.... $this->Syntax('Hello') = 'World';

The above error will be thrown because syntactially the statement is wrong. The right assignment of 'World' cannot be written in the context you have used (i.e. syntactically incorrect for this context). 'Cannot use function return value' or it could read 'Cannot assign the right-hand value to the function because its read-only'

The specific error in the OPs code is as highlighted, using brackets instead of square brackets.

Body:
I'm getting this error and I can't make head or tail of it.

The exact error message is:

Fatal error: Can't use function return
  value in write context in
  /home/curricle/public_html/descarga/index.php
  on line 48

Line 48 is:

if (isset($_POST('sms_code') == TRUE ) {

What could be going on here?

Here's the full function:

function validate_sms_code() {

    $state = NOTHING_SUBMITED;

    if (isset($_POST('sms_code') == TRUE ) {
        $sms_code = clean_up($_POST('sms_code'));
        $return_code = get_sepomo_code($sms_code);

        switch($return_code) {

          case 1:
            //no error
            $state = CORRECT_CODE;
            break;

          case 2:
            // code already used
            $state = CODE_ALREADY_USED;
            break;

          case 3:
            // wrong code
            $state = WRONG_CODE;
            break;

          case 4:
            // generic error
            $state = UNKNOWN_SEPOMO_CODE;
            break;

          default:
            // unknown error
            $state = UNKNOWN_SEPOMO_CODE;
            throw new Exception('Unknown sepomo code: ' . $return_code);
            break;
        }

    } else {
        $state = NOTHING_SUBMITED;
    }
    dispatch_on_state($state);
}