问:
Iterator to iterate over a generator
I am parsing an XML file, one of xml tag has a structure like this:

```<code><product>
     <item seq="division-sec">Division</item>
     <item seq="dept-sec">Dept Info</item>
     <item seq="label01">Label 01</item>
     <item seq="label02">Label 02</item>
     ...
     <item seq="labelN">Label N</item>
     <item seq="date-mfg">27-11-2017</item>
     <item seq="date-exp">28-11-2019</item>
</product>
</code>```

I have written a generator function to access product labels in a sequence:

```<code>def product_labels(xmlpage):
    #... parsed xml here
    for item in xmlpage:
       #-- process item for validation such as case sensitivity, etc
       yield item # ("division-sec", "Division")
</code>```

Now I'm looking for a function or may be an iterator class, which would allow me to get first, last, prev, next and search methods on it:

```<code>class ProdcutReader(object):
     def __init__(self, product_labels):
       self.product_labels = product_labels

     def __iter__(self):
        return self

     def __prev__(self):
        return prev(self.product_labels ) #-- Dont know how to do this :(

     def __next__(self):
        current = self.current(next(self.product_labels))
        return current

     def current(self, obj=None):
         if not obj:
            return self.first()
         return obj

     def first(self):
         return list(self.product_labels)[0]

    # search by label seq
    def search(self, seq):
       # Not sure if this is the correct way
       for i in self.product_labels:
           if i[0] == seq:
              self.current(i)
              return i
    ... # With some more methods (if search works I can have some more methods)
</code>```

So assume I need to use that object, it should work like this:

```<code>from product_reader import ProdcutReader as Reader
>>>r = Reader(product_labels)
>>>r.first()
("division-sec", "Division")
>>>r.last()
("date-exp", "28-11-2019")
>>>r.current()  # Let us say current is ("label01", "Label 01")
("label01", "Label 01")
>>>r.next() # or next(r)
("label02", "Label 02")
>>>r.prev()
("dept-sec", "Dept Info")
>>r.search("date-mfg") # This should also set the searched as r.current()
("date-mfg", "27-11-2017")
</code>```

If I can get how to write for prev, next and search I will be able to write remaining methods like, first, last, current etc.

答:
You apparently need random access to any element at any time. To my eyes, I don't see why you don't simply use a list.

If you need the current/next/previous functionality without having to keep track of a counter variable, you could still base your construct on a list:

```<code>class ProductReader(object):
    def __init__(self, product_labels):
        self.generator = product_labels
        self.active_generator = self.generator()
        self.element = None
        self.cur = -1

    def at_n(self, index):
        if self.cur > index:
            self.active_generator = self.generator()
        while len(self.storage) < index+1:
            self.element = next(self.active_generator)
        self.cur = index
        return self.element

    def current(self):
        if self.cur > -1:
            return self.element

    def last(self):
        try:
            while True:
                self.element = next(self.generator)
                self.cur += 1
        except StopIteration:
            return self.element

    def first(self):
        return self.at_n(0)

    def next(self):
        return self.at_n(self.cur+1)

    __next__ = next

    def prev(self):
        return self.at_n(self.cur-1)

    def search(self, query):
        oldcur = self.cur
        self.active_generator = self.generator()
        for i, element in enumerate(self.generator()):
            if query in element:
                self.cur = i
                self.element = element
                return element
        self.at_n(self.cur)  # reset to old state
        return None
</code>```

Title: Iterator to iterate over a generator

Body:
I am parsing an XML file, one of xml tag has a structure like this:

<product>
     <item seq="division-sec">Division</item>
     <item seq="dept-sec">Dept Info</item>
     <item seq="label01">Label 01</item>
     <item seq="label02">Label 02</item>
     ...
     <item seq="labelN">Label N</item>
     <item seq="date-mfg">27-11-2017</item>
     <item seq="date-exp">28-11-2019</item>
</product>

I have written a generator function to access product labels in a sequence:

def product_labels(xmlpage):
    #... parsed xml here
    for item in xmlpage:
       #-- process item for validation such as case sensitivity, etc
       yield item # ("division-sec", "Division")

Now I'm looking for a function or may be an iterator class, which would allow me to get first, last, prev, next and search methods on it:

class ProdcutReader(object):
     def __init__(self, product_labels):
       self.product_labels = product_labels

     def __iter__(self):
        return self

     def __prev__(self):
        return prev(self.product_labels ) #-- Dont know how to do this :(

     def __next__(self):
        current = self.current(next(self.product_labels))
        return current

     def current(self, obj=None):
         if not obj:
            return self.first()
         return obj

     def first(self):
         return list(self.product_labels)[0]

    # search by label seq
    def search(self, seq):
       # Not sure if this is the correct way
       for i in self.product_labels:
           if i[0] == seq:
              self.current(i)
              return i
    ... # With some more methods (if search works I can have some more methods)

So assume I need to use that object, it should work like this:

from product_reader import ProdcutReader as Reader
>>>r = Reader(product_labels)
>>>r.first()
("division-sec", "Division")
>>>r.last()
("date-exp", "28-11-2019")
>>>r.current()  # Let us say current is ("label01", "Label 01")
("label01", "Label 01")
>>>r.next() # or next(r)
("label02", "Label 02")
>>>r.prev()
("dept-sec", "Dept Info")
>>r.search("date-mfg") # This should also set the searched as r.current()
("date-mfg", "27-11-2017")

If I can get how to write for prev, next and search I will be able to write remaining methods like, first, last, current etc.

Body:
You apparently need random access to any element at any time. To my eyes, I don't see why you don't simply use a list.

If you need the current/next/previous functionality without having to keep track of a counter variable, you could still base your construct on a list:

class ProductReader(object):
    def __init__(self, product_labels):
        self.generator = product_labels
        self.active_generator = self.generator()
        self.element = None
        self.cur = -1

    def at_n(self, index):
        if self.cur > index:
            self.active_generator = self.generator()
        while len(self.storage) < index+1:
            self.element = next(self.active_generator)
        self.cur = index
        return self.element

    def current(self):
        if self.cur > -1:
            return self.element

    def last(self):
        try:
            while True:
                self.element = next(self.generator)
                self.cur += 1
        except StopIteration:
            return self.element

    def first(self):
        return self.at_n(0)

    def next(self):
        return self.at_n(self.cur+1)

    __next__ = next

    def prev(self):
        return self.at_n(self.cur-1)

    def search(self, query):
        oldcur = self.cur
        self.active_generator = self.generator()
        for i, element in enumerate(self.generator()):
            if query in element:
                self.cur = i
                self.element = element
                return element
        self.at_n(self.cur)  # reset to old state
        return None


来源: stackexchange

问:
dplyr::mutate_at for changing prefixes?
I've got a data frame (df) with three variables, two of which have the prefix abc and one with the prefix def.

I'd like to use dplyr() to change the prefix of the variables starting with abc, so that they instead have the prefix new.

The problems that my current code's not working and I don't understand why.

Thanks!

Starting point (df):

```<code>df <- data.frame(abc_question1_F1_Q1=c(1,2,1,2),abc_question_F1_Q2=c(1,2,1,2),def_question1_F1_Q3=c(1,2,1,2))
</code>```

Desired outcome (dfgoal):

```<code>df <- data.frame(new_question1_F1_Q1=c(1,2,1,2),new_question_F1_Q2=c(1,2,1,2),def_question1_F1_Q3=c(1,2,1,2))
</code>```

Current code:

```<code>library(dplyr)
df <- df %>% mutate_at(vars(contains("abc_")), function(x){gsub("abc_", "new_", x)})
</code>```

答:
If we need to use dplyr

```<code>df %>%
   rename_all(funs(sub("^abc", "new", .)))
</code>```

Or with base R

```<code>names(df) <- sub("^abc", "new", names(df))
</code>```

ContentLicense: CC BY-SA 3.0

Title: dplyr::mutate_at for changing prefixes?

Body:
I've got a data frame (df) with three variables, two of which have the prefix abc and one with the prefix def.

I'd like to use dplyr() to change the prefix of the variables starting with abc, so that they instead have the prefix new.

The problems that my current code's not working and I don't understand why.

Thanks!

Starting point (df):

df <- data.frame(abc_question1_F1_Q1=c(1,2,1,2),abc_question_F1_Q2=c(1,2,1,2),def_question1_F1_Q3=c(1,2,1,2))

Desired outcome (dfgoal):

df <- data.frame(new_question1_F1_Q1=c(1,2,1,2),new_question_F1_Q2=c(1,2,1,2),def_question1_F1_Q3=c(1,2,1,2))

Current code:

library(dplyr)
df <- df %>% mutate_at(vars(contains("abc_")), function(x){gsub("abc_", "new_", x)})

Body:
If we need to use dplyr

df %>%
   rename_all(funs(sub("^abc", "new", .)))

Or with base R

names(df) <- sub("^abc", "new", names(df))


问:
What should be passed for BeginInvoke's @object parameter?
I have an event delegate that is defined as follows:

```<code>public delegate void CallbackDelegate(Data data);
public event CallbackDelegate OnDataComplete;
</code>```

I raise the event asynchronously:

```<code>// Raise the OnDataComplete event
OnDataComplete.BeginInvoke(new Data(), null, null);
</code>```

Subsequently, the signature of BeginInvoke looks like:

```<code>IAsyncResult CallbackDelegate.BeginInvoke(Data data, AsyncCallback callback, object @object)
</code>```

In most examples I've seen BeginInvoke is called with the @object parameter being null, but I can't find the documentation which explains what is the purpose of that parameter.

So what is the purpose of that parameter? What can we use it for?

答: That's just a state object that ends up in IAsyncResult.AsyncState that can be retrieved in your AsyncCallback code. Kinda like the ThreadPool.QueueWorkItem(WaitCallback, Object).</p>

ContentLicense: CC BY-SA 2.5

Body:
I have an event delegate that is defined as follows:

public delegate void CallbackDelegate(Data data);
public event CallbackDelegate OnDataComplete;

I raise the event asynchronously:

// Raise the OnDataComplete event
OnDataComplete.BeginInvoke(new Data(), null, null);

Subsequently, the signature of BeginInvoke looks like:

IAsyncResult CallbackDelegate.BeginInvoke(Data data, AsyncCallback callback, object @object)

In most examples I've seen BeginInvoke is called with the @object parameter being null, but I can't find the documentation which explains what is the purpose of that parameter.

So what is the purpose of that parameter? What can we use it for?


问:
Ajax doesn't post data
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

```<code>$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
</code>```

should have been that:

```<code>$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
</code>```

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

```<code>$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('<p>Success</p>');
                }
                else {
                    $('#errors'+bUID).append('<p>' + js_errors + '</p>');
                    $('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('<li>' + v + '</li>');
                        }
                    });
                }
            }
        }
    });
}
</code>```

here's the action in view.php:

```<code><?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?><br />
    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.
</code>```

and here's the controller.php:

```<code>public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}
</code>```

it gets all data and shows it in alert but then trows the following error in the console:

```<code>Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)
</code>```

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

答:
Your post_data variable was correct. As it is now your data attribute in your ajax is wrong - it's in GET format (a string), not POST. The correct way (json) is;

```<code>$.ajax({
   dataType: "json",
   type: "post",
   data: {
       name: nameVar,
       email: emailVar,
       message: messageVar
   },
   url: ...,
   success: function(data) {
       ...
   }
});
</code>```

I "renamed" your variables to try and avoid variables with the same names as keys (e.g. you want to post "name", setting a variable "name" might conflict).

Title: Ajax doesn't post data

Body:
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

$('#errors'+bUID).append('

');

should have been that:

$('#errors'+bUID).append('

');

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('
Success
');
                }
                else {
                    $('#errors'+bUID).append('
' + js_errors + '
');
                    $('#errors'+bUID).append('

');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('
' + v + '
');
                        }
                    });
                }
            }
        }
    });
}

here's the action in view.php:

<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?>

    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.

and here's the controller.php:

public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}

it gets all data and shows it in alert but then trows the following error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

Body:
Your post_data variable was correct. As it is now your data attribute in your ajax is wrong - it's in GET format (a string), not POST. The correct way (json) is;

$.ajax({
   dataType: "json",
   type: "post",
   data: {
       name: nameVar,
       email: emailVar,
       message: messageVar
   },
   url: ...,
   success: function(data) {
       ...
   }
});

I "renamed" your variables to try and avoid variables with the same names as keys (e.g. you want to post "name", setting a variable "name" might conflict).


问:
adding repeating sequence numbers to a column in SQLite database based on conditions
I added a column in my SQLite database, and I need to insert repeating sequence numbers, starting with 1...n BUT it's based on grouping by other columns. The sequence needs to start over at 1 again when there is a new grouping.

Here is my table:
CREATE TABLE "ProdRunResults" ("ID" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "SeqNumbr" INTEGER, "Shift" INTEGER, "ShiftSeqNumbr" INTEGER, "Date" DATETIME, "ProdRunID" INTEGER, "Result" VARCHAR)

ShiftSeqNumbr is the new column that I need to populate with sequence numbers, based on grouping of numbers in ProdRunID column then by numbers in the Shift column.

There could be up to 3 "shifts" (work shifts in a 24 hr period).

I scraped together some code to do this but it adds the sequence numbers to ShiftSeqNumbr column in reverse (descending) order:

```<code>UPDATE ProdRunResults
SET ShiftSeqNumbr = (SELECT COUNT (*)
FROM ProdRunResults AS N
WHERE N.ProdRunID = ProdRunResults.ProdRunID
    AND N.Shift = ProdRunResults.Shift
    AND N.ShiftSeqNumbr = ProdRunResults.ShiftSeqNumbr);
</code>```

How can I change the Update statement so the sequence numbers start at 1 and go up? Or is there a better way to do this?

答:
Your UPDATE statement counts how many rows there are that have the same values in the ProdRunID/Shift/ShiftSeqNumbr columns as the current row. The current row always has an empty value in ShiftSeqNumbr, so it is counting how many rows in the current group have not yet been updated.

You need to count how many rows come before the current row, i.e., how many rows have the same ProdRunID and Shift values, and the same or a smaller SeqNumbr value:

```<code>UPDATE ProdRunResults
SET ShiftSeqNumbr = (SELECT COUNT (*)
                     FROM ProdRunResults AS N
                     WHERE N.ProdRunID =  ProdRunResults.ProdRunID
                       AND N.Shift     =  ProdRunResults.Shift
                       AND N.SeqNumbr  <= ProdRunResults.SeqNumbr);
</code>```

Body:
I added a column in my SQLite database, and I need to insert repeating sequence numbers, starting with 1...n BUT it's based on grouping by other columns. The sequence needs to start over at 1 again when there is a new grouping.

Here is my table:
CREATE TABLE "ProdRunResults" ("ID" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "SeqNumbr" INTEGER, "Shift" INTEGER, "ShiftSeqNumbr" INTEGER, "Date" DATETIME, "ProdRunID" INTEGER, "Result" VARCHAR)

ShiftSeqNumbr is the new column that I need to populate with sequence numbers, based on grouping of numbers in ProdRunID column then by numbers in the Shift column.

There could be up to 3 "shifts" (work shifts in a 24 hr period).

I scraped together some code to do this but it adds the sequence numbers to ShiftSeqNumbr column in reverse (descending) order:

UPDATE ProdRunResults
SET ShiftSeqNumbr = (SELECT COUNT (*)
FROM ProdRunResults AS N
WHERE N.ProdRunID = ProdRunResults.ProdRunID
    AND N.Shift = ProdRunResults.Shift
    AND N.ShiftSeqNumbr = ProdRunResults.ShiftSeqNumbr);

How can I change the Update statement so the sequence numbers start at 1 and go up? Or is there a better way to do this?

Body:
Your UPDATE statement counts how many rows there are that have the same values in the ProdRunID/Shift/ShiftSeqNumbr columns as the current row. The current row always has an empty value in ShiftSeqNumbr, so it is counting how many rows in the current group have not yet been updated.

You need to count how many rows come before the current row, i.e., how many rows have the same ProdRunID and Shift values, and the same or a smaller SeqNumbr value:

UPDATE ProdRunResults
SET ShiftSeqNumbr = (SELECT COUNT (*)
                     FROM ProdRunResults AS N
                     WHERE N.ProdRunID =  ProdRunResults.ProdRunID
                       AND N.Shift     =  ProdRunResults.Shift
                       AND N.SeqNumbr  <= ProdRunResults.SeqNumbr);


问:
autoreconnect for aiohttp websocket
I am writing an app listening to websocket connections and making infrequent REST requests. aiohttp seems like a natural choice for this, but I'm flexible. The app is simple but needs to be reliable (gigabytes of data to collect daily while minimising data loss).

What is the best way to handle connection loss with aiohttp? I notice that other some other Python libraries have auto reconnect options available. With aiohttp, I could always manually implement this with a loop (start over again as soon as the connection is lost) but I wouldn't know what's the best practice (is it acceptable to keep making reconnection attempts without delay in a loop?).

答:
aiohtp is a relative low level library, autoreconnection should be built on top of it.

Websocket connection is non-blocking operation in aiohttp.

Reliable websocket reconnection is not trivial task. Maybe you need to know what data are received by peer or maybe not -- it depends. In first case you need some high level protocol on top of plain websockets to send acknowledges etc.

Title: autoreconnect for aiohttp websocket


问:
How to pass USER ID from template to function to get values in angular 5
i want to pass my user id to service when i click on edit.

```<code> <tr *ngFor="let visit of visits" style="border-top: 1px solid black">
          <td>{{ visit?.ID }}</td>
          <td>{{ visit?.username }}</td>
            <td>{{ visit?.height }}</td>
            <td>{{ visit?.weight }}</td>
            <td>{{ visit?.patientnote }}</td>
            <td>{{ visit?.doctornote }}</td>
            <td>{{ visit?.nursenote }}</td>
            <td><button mat-raised-button color="accent" (click)="edit()">EDIT</button></td>
            <td><button mat-raised-button color="warn" (click)="delete()">DEL</button></td>
</code>```

答:
You have to pass id as being parameter of the function: </p>

```<code><td><button mat-raised-button color="accent" (click)="edit(visit.ID)">EDIT</button></td>
</code>```

Body:
i want to pass my user id to service when i click on edit.

          {{ visit?.ID }}
          {{ visit?.username }}
            {{ visit?.height }}
            {{ visit?.weight }}
            {{ visit?.patientnote }}
            {{ visit?.doctornote }}
            {{ visit?.nursenote }}
            <button mat-raised-button color="accent" (click)="edit()">EDIT</button>
            <button mat-raised-button color="warn" (click)="delete()">DEL</button>

Body:
You have to pass id as being parameter of the function:

<td><button mat-raised-button color="accent" (click)="edit(visit.ID)">EDIT</button></td>


问:
Backup & restore DynamoDb tables
My aim is to back up and restore a dynamodb table to/from S3.
I'm aware about the Import/Export using data pipelines and DynamoDb streams.
My concern using Data Pipeline is that when the backup process is complete, I cannot be sure as to what 'point-in-time' the backup was performed. For e.g. if the backup process started at 11am and ended at 1130am, the items in my backup could be for anything that happened in the dynamodb table from 11am to 1130am.

How can I use DynamoDb streams to compliment the data pipeline ?

How can I restore the dynamodb table to a particular 'point-in-time' ?

答:
As Stu mentioned, On-Demand backups are a feature built into the DynamoDB service (Accessible via the API, AWS Management Console and CLI as usual), which allows you to take a full backup of a table at a point in time.

This task has no impact on performance or availability to your tables. All backups are automatically encrypted, cataloged, easily discoverable, and retained until you explicitly delete them.

Additionally, you can restore these backups to a new table at any point.

If you would like to schedule the backups, that is also possible using CloudWatch Events and a Lambda function.

A detailed walk through on backing up, restoring and scheduling can be found here:
https://www.abhayachauhan.com/category/aws/dynamodb/dynamodb-backups/

HTH

Title: Backup & restore DynamoDb tables


问:
Javascript scrollIntoView() middle alignment?
Javascript .scrollIntoView(boolean) provide only two alignment option.

top

bottom

What if I want to scroll the view such that. I want to bring particular element somewhere in middle of the page?

答:
Improving the answer of @Rohan Orton to work for vertical and horizontal scroll.

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

var ele = $x("//a[.='Ask Question']");
console.log( ele );

scrollIntoView( ele[0] );

function scrollIntoView( element ) {
    var innerHeight_Half = (window.innerHeight >> 1); // Int value
                        // = (window.innerHeight / 2); // Float value
    console.log('innerHeight_Half : '+ innerHeight_Half);

    var elementRect = element.getBoundingClientRect();

    window.scrollBy( (elementRect.left >> 1), elementRect.top - innerHeight_Half);
}
```

<p>Using <code>Bitwise operator</code> right shift to get int value after dividing.</p>

<pre class="lang-js prettyprint-override"><code>console.log( 25 / 2 ); // 12.5
console.log( 25 >> 1 ); // 12
</code>```

Body:
Improving the answer of @Rohan Orton to work for vertical and horizontal scroll.

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

var ele = $x("//a[.='Ask Question']");
console.log( ele );

scrollIntoView( ele[0] );

function scrollIntoView( element ) {
    var innerHeight_Half = (window.innerHeight >> 1); // Int value
                        // = (window.innerHeight / 2); // Float value
    console.log('innerHeight_Half : '+ innerHeight_Half);

    var elementRect = element.getBoundingClientRect();

    window.scrollBy( (elementRect.left >> 1), elementRect.top - innerHeight_Half);
}

Using Bitwise operator right shift to get int value after dividing.

console.log( 25 / 2 ); // 12.5
console.log( 25 >> 1 ); // 12


问:
Subscript out of range on VBA
I am writing my first VBA. I have a sheet named Sheet1. That sheet has a column E; I would like to delete all rows which have an empty field on column E.

Therefore, I wrote this code:

```<code>Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub
</code>```

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1. Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E"), instead of Columns("E:E") I get the same error

答:
I have tried this and it works:

```<code>Option Explicit
Sub TetsMe()
    MsgBox (Worksheets(1).Parent.Name & VbCrLf & Worksheets(1).Name)
    Worksheets(1).Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub
</code>```

The different syntax as the index may refer to a different sheet. In this case Worksheets(1) is the first worksheet in the workbook.

The MsgBox() will tell you which worksheet and which workbook you are changing. Once you know, what you are doing, you may remove it.

If the problem is in the workbook name, then it is easy to change it like this:

```<code>With Workbooks("NameYourWorkbook").Worksheets("NameYourWorksheet")
    .Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End With
</code>```

Title: Subscript out of range on VBA

Body:
I am writing my first VBA. I have a sheet named Sheet1. That sheet has a column E; I would like to delete all rows which have an empty field on column E.

Therefore, I wrote this code:

Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1. Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E"), instead of Columns("E:E") I get the same error

Body:
I have tried this and it works:

Option Explicit
Sub TetsMe()
    MsgBox (Worksheets(1).Parent.Name & VbCrLf & Worksheets(1).Name)
    Worksheets(1).Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

The different syntax as the index may refer to a different sheet. In this case Worksheets(1) is the first worksheet in the workbook.

The MsgBox() will tell you which worksheet and which workbook you are changing. Once you know, what you are doing, you may remove it.

If the problem is in the workbook name, then it is easy to change it like this:

With Workbooks("NameYourWorkbook").Worksheets("NameYourWorksheet")
    .Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End With


问:
How to Add Extra Tab Using Template Language Twig In OpenCart 3.x
I want an extra description tag termed "Overview" for the product page under the nav nav-tabs class.

This is the complete Twig template code:

```<code><ul class="nav nav-tabs">
        <li class="active"><a href="#tab-description" data-toggle="tab">{{ tab_description }}</a></li>
        {% if attribute_groups %}
        <li><a href="#tab-specification" data-toggle="tab">{{ tab_attribute }}</a></li>
        {% endif %}
        {% if review_status %}
        <li><a href="#tab-review" data-toggle="tab">{{ tab_review }}</a></li>
        {% endif %}
      </ul>
      <div class="tab-content">
        <div class="tab-pane active" id="tab-description">{{ description }}</div>
        {% if attribute_groups %}
        <div class="tab-pane" id="tab-specification">
          <table class="table table-bordered">
            {% for attribute_group in attribute_groups %}
            <thead>
              <tr>
                <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
              </tr>
            </thead>
            <tbody>
            {% for attribute in attribute_group.attribute %}
            <tr>
              <td>{{ attribute.name }}</td>
              <td>{{ attribute.text }}</td>
            </tr>
            {% endfor %}
              </tbody>
            {% endfor %}
          </table>
        </div>
        {% endif %}
        {% if review_status %}
        <div class="tab-pane" id="tab-review">
          <form class="form-horizontal" id="form-review">
            <div id="review"></div>
            <h2>{{ text_write }}</h2>
            {% if review_guest %}
            <div class="form-group required">
              <div class="col-sm-12">
                <label class="control-label" for="input-name">{{ entry_name }}</label>
                <input type="text" name="name" value="{{ customer_name }}" id="input-name" class="form-control" />
              </div>
            </div>
            <div class="form-group required">
              <div class="col-sm-12">
                <label class="control-label" for="input-review">{{ entry_review }}</label>
                <textarea name="text" rows="5" id="input-review" class="form-control"></textarea>
                <div class="help-block">{{ text_note }}</div>
              </div>
            </div>
            <div class="form-group required">
              <div class="col-sm-12">
                <label class="control-label">{{ entry_rating }}</label>
                    {{ entry_bad }}
                <input type="radio" name="rating" value="1" />

                <input type="radio" name="rating" value="2" />

                <input type="radio" name="rating" value="3" />

                <input type="radio" name="rating" value="4" />

                <input type="radio" name="rating" value="5" />
                 {{ entry_good }}</div>
            </div>
            {{ captcha }}
            <div class="buttons clearfix">
              <div class="pull-right">
                <button type="button" id="button-review" data-loading-text="{{ text_loading }}" class="btn btn-primary">{{ button_continue }}</button>
              </div>
            </div>
            {% else %}
            {{ text_login }}
            {% endif %}
          </form>
        </div>
        {% endif %}</div>
    </div>
</code>```

With this code, the page looks like this:

I want one more tab there saying OVERVIEW with different content.

Can anyone help me out here with this?

P.S: I did read this: how to add extra tab without any extension in product page in opencart
But, I'm not sure where to find this piece of code (I've tried looking product TPL files as well).

答:
You Should try this its will add new tab name Overview

```<code><ul class="nav nav-tabs">
    <li class="active"><a href="#tab-description" data-toggle="tab">{{ tab_description }}</a></li>
    {% if attribute_groups %}
    <li><a href="#tab-specification" data-toggle="tab">{{ tab_attribute }}</a></li>
    {% endif %}
    {% if review_status %}
    <li><a href="#tab-review" data-toggle="tab">{{ tab_review }}</a></li>
    {% endif %}
    <li><a href="#tab-overview" data-toggle="tab">Overview</a></li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="tab-description">{{ description }}</div>
    {% if attribute_groups %}
    <div class="tab-pane" id="tab-specification">
      <table class="table table-bordered">
        {% for attribute_group in attribute_groups %}
        <thead>
          <tr>
            <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
          </tr>
        </thead>
        <tbody>
        {% for attribute in attribute_group.attribute %}
        <tr>
          <td>{{ attribute.name }}</td>
          <td>{{ attribute.text }}</td>
        </tr>
        {% endfor %}
          </tbody>
        {% endfor %}
      </table>
    </div>
    {% endif %}
    {% if review_status %}
    <div class="tab-pane" id="tab-review">
      <form class="form-horizontal" id="form-review">
        <div id="review"></div>
        <h2>{{ text_write }}</h2>
        {% if review_guest %}
        <div class="form-group required">
          <div class="col-sm-12">
            <label class="control-label" for="input-name">{{ entry_name }}</label>
            <input type="text" name="name" value="{{ customer_name }}" id="input-name" class="form-control" />
          </div>
        </div>
        <div class="form-group required">
          <div class="col-sm-12">
            <label class="control-label" for="input-review">{{ entry_review }}</label>
            <textarea name="text" rows="5" id="input-review" class="form-control"></textarea>
            <div class="help-block">{{ text_note }}</div>
          </div>
        </div>
        <div class="form-group required">
          <div class="col-sm-12">
            <label class="control-label">{{ entry_rating }}</label>
                {{ entry_bad }}
            <input type="radio" name="rating" value="1" />

            <input type="radio" name="rating" value="2" />

            <input type="radio" name="rating" value="3" />

            <input type="radio" name="rating" value="4" />

            <input type="radio" name="rating" value="5" />
             {{ entry_good }}</div>
        </div>
        {{ captcha }}
        <div class="buttons clearfix">
          <div class="pull-right">
            <button type="button" id="button-review" data-loading-text="{{ text_loading }}" class="btn btn-primary">{{ button_continue }}</button>
          </div>
        </div>
        {% else %}
        {{ text_login }}
        {% endif %}
      </form>
    </div>
    {% endif %}
    <div class="tab-pane" id="tab-overview">
        <h1>Overview</h1>
        <!-- Your HTML and twig code here-->
    </div>
</div>
</code>```

Output Image

Body:
I want an extra description tag termed "Overview" for the product page under the nav nav-tabs class.

This is the complete Twig template code:

{{ tab_description }}

        {% if attribute_groups %}

{{ tab_attribute }}

        {% endif %}
        {% if review_status %}

{{ tab_review }}

        {% endif %}

{{ description }}

        {% if attribute_groups %}

            {% for attribute_group in attribute_groups %}

                {{ attribute_group.name }}

            {% for attribute in attribute_group.attribute %}

              {{ attribute.name }}
              {{ attribute.text }}

            {% endfor %}

            {% endfor %}

        {% endif %}
        {% if review_status %}

          <form class="form-horizontal" id="form-review">

{{ text_write }}

            {% if review_guest %}

                {{ entry_name }}
                <input type="text" name="name" value="{{ customer_name }}" id="input-name" class="form-control" />

                {{ entry_review }}
                <textarea name="text" rows="5" id="input-review" class="form-control"></textarea>

{{ text_note }}

                {{ entry_rating }}
                    {{ entry_bad }}
                <input type="radio" name="rating" value="1" />

                <input type="radio" name="rating" value="2" />

                <input type="radio" name="rating" value="3" />

                <input type="radio" name="rating" value="4" />

                <input type="radio" name="rating" value="5" />
                 {{ entry_good }}

            {{ captcha }}

                <button type="button" id="button-review" data-loading-text="{{ text_loading }}" class="btn btn-primary">{{ button_continue }}</button>

            {% else %}
            {{ text_login }}
            {% endif %}
          </form>

        {% endif %}

With this code, the page looks like this:

I want one more tab there saying OVERVIEW with different content.

Can anyone help me out here with this?

P.S: I did read this: how to add extra tab without any extension in product page in opencart
But, I'm not sure where to find this piece of code (I've tried looking product TPL files as well).

Body:
You Should try this its will add new tab name Overview

<ul class="nav nav-tabs">
    <li class="active"><a href="#tab-description" data-toggle="tab">{{ tab_description }}</a></li>
    {% if attribute_groups %}
    <li><a href="#tab-specification" data-toggle="tab">{{ tab_attribute }}</a></li>
    {% endif %}
    {% if review_status %}
    <li><a href="#tab-review" data-toggle="tab">{{ tab_review }}</a></li>
    {% endif %}
    <li><a href="#tab-overview" data-toggle="tab">Overview</a></li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="tab-description">{{ description }}</div>
    {% if attribute_groups %}
    <div class="tab-pane" id="tab-specification">
      <table class="table table-bordered">
        {% for attribute_group in attribute_groups %}
        <thead>
          <tr>
            <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
          </tr>
        </thead>
        <tbody>
        {% for attribute in attribute_group.attribute %}
        <tr>
          <td>{{ attribute.name }}</td>
          <td>{{ attribute.text }}</td>
        </tr>
        {% endfor %}
          </tbody>
        {% endfor %}
      </table>
    </div>
    {% endif %}
    {% if review_status %}
    <div class="tab-pane" id="tab-review">
      <form class="form-horizontal" id="form-review">
        <div id="review"></div>
        <h2>{{ text_write }}</h2>
        {% if review_guest %}
        <div class="form-group required">
          <div class="col-sm-12">
            <label class="control-label" for="input-name">{{ entry_name }}</label>
            <input type="text" name="name" value="{{ customer_name }}" id="input-name" class="form-control" />
          </div>
        </div>
        <div class="form-group required">
          <div class="col-sm-12">
            <label class="control-label" for="input-review">{{ entry_review }}</label>
            <textarea name="text" rows="5" id="input-review" class="form-control"></textarea>
            <div class="help-block">{{ text_note }}</div>
          </div>
        </div>
        <div class="form-group required">
          <div class="col-sm-12">
            <label class="control-label">{{ entry_rating }}</label>
            &nbsp;&nbsp;&nbsp; {{ entry_bad }}&nbsp;
            <input type="radio" name="rating" value="1" />
            &nbsp;
            <input type="radio" name="rating" value="2" />
            &nbsp;
            <input type="radio" name="rating" value="3" />
            &nbsp;
            <input type="radio" name="rating" value="4" />
            &nbsp;
            <input type="radio" name="rating" value="5" />
            &nbsp;{{ entry_good }}</div>
        </div>
        {{ captcha }}
        <div class="buttons clearfix">
          <div class="pull-right">
            <button type="button" id="button-review" data-loading-text="{{ text_loading }}" class="btn btn-primary">{{ button_continue }}</button>
          </div>
        </div>
        {% else %}
        {{ text_login }}
        {% endif %}
      </form>
    </div>
    {% endif %}
    <div class="tab-pane" id="tab-overview">
        <h1>Overview</h1>
        <!-- Your HTML and twig code here-->
    </div>
</div>

Output Image


问:
Consuming web services from Oracle PL/SQL
Our application is interfacing with a lot of web services these days. We have our own package that someone wrote a few years back using UTL_HTTP and it generally works, but needs some hard-coding of the SOAP envelope to work with certain systems. I would like to make it more generic, but lack experience to know how many scenarios I would have to deal with. The variations are in what namespaces need to be declared and the format of the elements. We have to handle both simple calls with a few parameters and those that pass a large amount of data in an encoded string.

I know that 10g has UTL_DBWS, but there are not a huge number of use-cases on-line. Is it stable and flexible enough for general use? Documentation

答:
I had this challenge and found and installed the 'SOAP API' package that Sten suggests on Oracle-Base.  It provides some good envelope-creation functionality on top of UTL_HTTP.

However there were some limitations that pertain to your question.  SOAP_API assumes all requests are simple XML- i.e. only one layer tag hierarchy.

I extended the SOAP_API package to allow the client code to arbitrarily insert an extra tag.  So you can insert a sub-level such as , continue to build the request, and remember to insert a closing  tag.

The namespace issue was a bear for the project- different levels of XML had different namespaces.

A nice debugging tool that I used is TCP Trace from Pocket Soap.
www.pocketsoap.com/tcptrace/
You set it up like a proxy and watch the HTTP request and response objects between client and server code.

Having said all that, we really like having a SOAP client in the database- we have full access to all data and existing PLSQL code, can easily loop through cursors and call the external app via SOAP when needed.  It was a lot quicker and easier than deploying a middle tier with lots of custom Java or .NET code.  Good luck and let me know if you'd like to see my enhanced SOAP API code.

OwnerDisplayName: steevc

LastEditorDisplayName: steevc

OwnerDisplayName: Rob McCauley


答:
It's so that you can pass any relevant information from your method to the callback. Since C# has lambda expressions and since delegates can have state, sometimes this is useless, and you can just pass null. But it's a bit similar to Control.Tag, and it lets you give information to the callback that it might find handy.

Update:

The origin of why it even exists goes back to languages that only had function pointers, with no closure. (You might want to look up the word "closure"... I can't explain it very concisely.) In C, there's only function pointers and not delegates; hence, function pointers can't hold state. So whenever you provided a callback, the callee helped you by passing an additional pointer for you, so you could pass data to your callback that it might need. In .NET, these are less necessary (because delegates have Target objects and can hold state), but sometimes they're handy and that's where they come from.

Title: What should be passed for BeginInvoke's @object parameter?


问:
Not able to mount azure file share into local RHEL7 VM
I want to mount(symlink) from  Azure file share to a local RHEL7 VM . I am using the following command

```<code>mount -t cifs //<storage-account-name>.file.core.windows.net/<share-name>  /mymountpoint -o vers=3.0,username=<storage-acc-name>,password=<pwd>,dir_mode=0777,file_mode=0777,sec=ntlmssp,mfsymlinks
</code>```

but getting the following error

mount error(13): Permission denied

Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

```<code>`The dmesg | tail gives the following log
[root@googleapps ~]# dmesg | tail
[98383.619149] fs/cifs/smb2misc.c: SMB2 data length 0 offset 0
[98383.619151] fs/cifs/smb2misc.c: SMB2 len 77
[98383.619163] fs/cifs/transport.c: cifs_sync_mid_result: cmd=1 mid=1 state=4
[98383.619168] Status code returned 0xc0000022 STATUS_ACCESS_DENIED
[98383.619175] fs/cifs/smb2maperror.c: Mapping SMB2 status code -1073741790 to POSIX err -13
[98383.619177] fs/cifs/misc.c: Null buffer passed to cifs_small_buf_release
[98383.619181] CIFS VFS: Send error in SessSetup = -13
[98383.619185] fs/cifs/connect.c: CIFS VFS: leaving cifs_get_smb_ses (xid = 59) rc = -13
[98383.619297] fs/cifs/connect.c: CIFS VFS: leaving cifs_mount (xid = 58) rc = -13
[98383.619300] CIFS VFS: cifs_mount failed w/return code = -13`
</code>```

答:
I had the similar problem. Read most of the forums tried all in the end found that password used by me was wrong and it has to be SSH key which is generated with storage account. I got hint to this by using trouble shooting script by Azure support.
You can find this script here :
https://gallery.technet.microsoft.com/Troubleshooting-tool-for-02184089

Bash script found here can be used to go through series of probable issues and will give you a fair idea of the problem.

Body:
I want to mount(symlink) from  Azure file share to a local RHEL7 VM . I am using the following command

mount -t cifs //<storage-account-name>.file.core.windows.net/<share-name>  /mymountpoint -o vers=3.0,username=<storage-acc-name>,password=<pwd>,dir_mode=0777,file_mode=0777,sec=ntlmssp,mfsymlinks

but getting the following error

mount error(13): Permission denied

Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

`The dmesg | tail gives the following log
[root@googleapps ~]# dmesg | tail
[98383.619149] fs/cifs/smb2misc.c: SMB2 data length 0 offset 0
[98383.619151] fs/cifs/smb2misc.c: SMB2 len 77
[98383.619163] fs/cifs/transport.c: cifs_sync_mid_result: cmd=1 mid=1 state=4
[98383.619168] Status code returned 0xc0000022 STATUS_ACCESS_DENIED
[98383.619175] fs/cifs/smb2maperror.c: Mapping SMB2 status code -1073741790 to POSIX err -13
[98383.619177] fs/cifs/misc.c: Null buffer passed to cifs_small_buf_release
[98383.619181] CIFS VFS: Send error in SessSetup = -13
[98383.619185] fs/cifs/connect.c: CIFS VFS: leaving cifs_get_smb_ses (xid = 59) rc = -13
[98383.619297] fs/cifs/connect.c: CIFS VFS: leaving cifs_mount (xid = 58) rc = -13
[98383.619300] CIFS VFS: cifs_mount failed w/return code = -13`


问:
Why does Traefik not proxy new services in a Docker Swarm?
I try to setup traefik with a Docker Swarm. I have to VMs - one manger-node and one worker-node.
In addition I have created a external network with:

```<code>docker network create --driver=overlay proxy-net
</code>```

I start traefik as a service within my manager-node with the following docker-compose.yml file:

```<code>version: '3'

services:
  traefik:
     image: traefik:v1.4.4
     volumes:
       - /var/run/docker.sock:/var/run/docker.sock
       - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
     ports:
       - 80:80
       - 8100:8080
     deploy:
       placement:
         constraints:
           - node.role == manager

networks:
   default:
    external:
      name:  proxy-net
</code>```

My traefik.toml file looks like this:

```<code>Debug : "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
    [entryPoints.http]
    address = ":80"

[web]
address = ":8080"

[docker]
watch = true
swarmmode = true
domain = "mydomain.com"
exposedbydefault = true
</code>```

When I now start a new service (e.g. emilevauge/whoami) with:

```<code>docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami
</code>```

The service is seen by the traefik web frontend. So at first every thing looks fine. I can access the service directly on my worker node on port 8002.
But traefik does not seem to be able to proxy this service. When I browse my endpoint URL (whomai.mydomain.com) I get the answer:

```<code>Bad Gateway
</code>```

The traefik logfile (logLevel=DEBUG) shown messages like this:

```<code>proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_app.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label proxy_traefik.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_db.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Validation of load balancer method for backend backend-whoami1-whoami1-whoami1 failed: invalid load-balancing method ''. Using default method wrr."
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-whoami1-whoami1-whoami1":{"servers":{"service-0":{"url":"http://10.0.1.5:8002","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-whoami1-whoami1-whoami1":{"entryPoints":["http"],"backend":"backend-whoami1-whoami1-whoami1","routes":{"service-whoami1":{"rule":"Host:whoami.mydomain.com"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"
</code>```

I played around several hours with different configurations. I also read the very concise documentation about traefik and docker-swarm. But I don't get any idea what I'm doing wrong.

Can any body help me with some tips how to better understand the problem?

答:
I think it is not working because you Træfik service is not on the same docker network as your whoami1 service.

You should try to add proxy-net network to your Træfik service in your compose file.

There is a warning in Træfik documentation at the end of this page https://docs.traefik.io/configuration/backends/docker/

```<code>when running inside a container, Træfik will need network access through:
docker network connect <network> <traefik-container>
</code>```

Body:
I try to setup traefik with a Docker Swarm. I have to VMs - one manger-node and one worker-node.
In addition I have created a external network with:

docker network create --driver=overlay proxy-net

I start traefik as a service within my manager-node with the following docker-compose.yml file:

version: '3'

services:
  traefik:
     image: traefik:v1.4.4
     volumes:
       - /var/run/docker.sock:/var/run/docker.sock
       - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
     ports:
       - 80:80
       - 8100:8080
     deploy:
       placement:
         constraints:
           - node.role == manager

networks:
   default:
    external:
      name:  proxy-net

My traefik.toml file looks like this:

Debug : "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
    [entryPoints.http]
    address = ":80"

[web]
address = ":8080"

[docker]
watch = true
swarmmode = true
domain = "mydomain.com"
exposedbydefault = true

When I now start a new service (e.g. emilevauge/whoami) with:

docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami

The service is seen by the traefik web frontend. So at first every thing looks fine. I can access the service directly on my worker node on port 8002.
But traefik does not seem to be able to proxy this service. When I browse my endpoint URL (whomai.mydomain.com) I get the answer:

Bad Gateway

The traefik logfile (logLevel=DEBUG) shown messages like this:

proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_app.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label proxy_traefik.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_db.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Validation of load balancer method for backend backend-whoami1-whoami1-whoami1 failed: invalid load-balancing method ''. Using default method wrr."
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-whoami1-whoami1-whoami1":{"servers":{"service-0":{"url":"http://10.0.1.5:8002","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-whoami1-whoami1-whoami1":{"entryPoints":["http"],"backend":"backend-whoami1-whoami1-whoami1","routes":{"service-whoami1":{"rule":"Host:whoami.mydomain.com"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"

I played around several hours with different configurations. I also read the very concise documentation about traefik and docker-swarm. But I don't get any idea what I'm doing wrong.

Can any body help me with some tips how to better understand the problem?

Body:
I think it is not working because you Træfik service is not on the same docker network as your whoami1 service.

You should try to add proxy-net network to your Træfik service in your compose file.

There is a warning in Træfik documentation at the end of this page https://docs.traefik.io/configuration/backends/docker/

when running inside a container, Træfik will need network access through:
docker network connect <network> <traefik-container>


问:
Is possible for Jenkins to auto start and stop slave nodes?
I have a Jenkins master in my network with a slave node.
I am planning to create another node in AWS EC2, a big expensive server.
I would like to have a single Jenkins build that:

Jenkins Master starts slave node.

Jenkins node runs the script.

Jenkins Master stops the slave node. (I can directly execute shutdown myself)

I know I can have three separate builds to do it. I was wondering if is possible to have this in one build only?
Is there any plugin(s) that can do this?

答:
Try Jenkins Plugin called as Slave SetupPlugin

https://plugins.jenkins.io/slave-setup

https://wiki.jenkins.io/download/attachments/58002132/68747470733a2f2f676f6c6466697368746970732e66696c65732e776f726470726573732e636f6d2f323031362f30362f746e63686a716e74766a2e706e67.png?version=1&modificationDate=1467444498000&api=v2


问:
How to check internet connection in alamofire?
I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code </p>

```<code>  let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)
      .responseJSON {

        let resstr = NSString(data: $0.data!, encoding: String.Encoding.utf8.rawValue)
        print("error is \(resstr)")

        if $0.result.isFailure {
          self.failure("Network")
          print("API FAILED 4")
          return
        }
        guard let result = $0.result.value else {
          self.unKnownError()
          self.failure("")
          print("API FAILED 3")

          return
        }
        self.handleSuccess(JSON(result))
    }
</code>```

答:
For Swift 3/4,

In Alamofire, there is a class called NetworkReachabilityManager which can be used to observer or check if internet is available or not.

```<code>let reachabilityManager = NetworkReachabilityManager()

reachabilityManager?.startListening()
reachabilityManager?.listener = { _ in
        if let isNetworkReachable = self.reachabilityManager?.isReachable,
            isNetworkReachable == true {
            //Internet Available
        } else {
            //Internet Not Available"
        }
    }
</code>```

Here, listener will get called every time when there is changes in state of internet. You can handle it as you would like.

ContentLicense: CC BY-SA 4.0

Body:
I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code

  let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)
      .responseJSON {

        let resstr = NSString(data: $0.data!, encoding: String.Encoding.utf8.rawValue)
        print("error is \(resstr)")

        if $0.result.isFailure {
          self.failure("Network")
          print("API FAILED 4")
          return
        }
        guard let result = $0.result.value else {
          self.unKnownError()
          self.failure("")
          print("API FAILED 3")

          return
        }
        self.handleSuccess(JSON(result))
    }

Body:
For Swift 3/4,

In Alamofire, there is a class called NetworkReachabilityManager which can be used to observer or check if internet is available or not.

let reachabilityManager = NetworkReachabilityManager()

reachabilityManager?.startListening()
reachabilityManager?.listener = { _ in
        if let isNetworkReachable = self.reachabilityManager?.isReachable,
            isNetworkReachable == true {
            //Internet Available
        } else {
            //Internet Not Available"
        }
    }

Here, listener will get called every time when there is changes in state of internet. You can handle it as you would like.


问:
using setValue in Zend-Form
I try to pass a value to an Zend-Form element. It shall be filled when the formclass is instantiated. Perhaps it is even the wrong idea?

What I gonna do:

I want to give a value to my formclass via my controller addAction:

```<code>$form = new PadForm(NULL, $test->UnitPartID);
</code>```

Here is the constructor of my form class:

```<code> public function __construct($name = null, $unitpartid)
</code>```

Now I thought it must be easy to give the value to an element:

add.phtml

```<code>$UnitPartID= $form->get('UnitPartID');
$UnitPartID->setAttribute('class', 'form-control');
$UnitPartID->setAttribute('placeholder', 'UnitPartID');

$UnitPartID->setValue($this->unitpartid);
</code>```

Unfortunately the form element doesn't get the value.

Where is the error? I think I'm quite close to the solution?? Any help appreciated.

答:
It's a bit of a shame, because it is so easy in the end. But for beginners in Zend, it is sometimes hard to understand, where to do things properly.
So I want to post the solution for others who have the same issues.

In my controller addaction I gave the form field a value, after instantiating the Form class.

```<code>$form->get('Formfield')->setValue(some variable);
</code>```

I had the hole topic, because I was searching for a possibility to do it in the view. There I could give a value of course, but I couldn't fetch a variable. If somebody has still a suggestion for this possibility, please post. I answer my question because I now have one working solution.

Title: using setValue in Zend-Form

Body:
I try to pass a value to an Zend-Form element. It shall be filled when the formclass is instantiated. Perhaps it is even the wrong idea?

What I gonna do:

I want to give a value to my formclass via my controller addAction:

$form = new PadForm(NULL, $test->UnitPartID);

Here is the constructor of my form class:

 public function __construct($name = null, $unitpartid)

Now I thought it must be easy to give the value to an element:

add.phtml

$UnitPartID= $form->get('UnitPartID');
$UnitPartID->setAttribute('class', 'form-control');
$UnitPartID->setAttribute('placeholder', 'UnitPartID');

$UnitPartID->setValue($this->unitpartid);

Unfortunately the form element doesn't get the value.

Where is the error? I think I'm quite close to the solution?? Any help appreciated.

Body:
It's a bit of a shame, because it is so easy in the end. But for beginners in Zend, it is sometimes hard to understand, where to do things properly.
So I want to post the solution for others who have the same issues.

In my controller addaction I gave the form field a value, after instantiating the Form class.

$form->get('Formfield')->setValue(some variable);

I had the hole topic, because I was searching for a possibility to do it in the view. There I could give a value of course, but I couldn't fetch a variable. If somebody has still a suggestion for this possibility, please post. I answer my question because I now have one working solution.


问:
how to create a tf.layers.Dense object
I want to create a dense layer in tensorflow. I tried tf.layers.dense(input_placeholder, units) which will directly create this layer and get result, but what I want is just a "layer module", i.e. an object of the class tf.layers.Dense(units). I want to first declare these modules/layers in a class, and then to have several member functions apply1(x, y), apply2(x,y) to use these layers.
But when I did in tensorflow tf.layers.Dense(units), it returned:

layer = tf.layers.Dense(100) AttributeError: 'module' object has no
  attribute 'Dense'

But if I do tf.layers.dense(x, units), there's no problem.
Any help is appreciated, thanks.

答:
Try to avoid the usage of placeholders, you have to feed_dict into the tf.Session so its probably causing this issue.

Try to use the new estimator api to load the data and then use dense layers as is done in the tensorflow's github examoples: [https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/layers/cnn_mnist.py]:

Title: how to create a tf.layers.Dense object


问:
MySQL - Error #1064 in LEFT JOIN
I am currently trying to get the data formatted using only MySQL query. I do not want to manipulate it using a programming language. All the operations are done only on one table.

Here is my query:

```<code>    SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_a FROM users a
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "good"

    LEFT JOIN (SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_b FROM users
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "bad") AS b
    ON b.date = a.date;
</code>```

The output should be like:

```
date           users_a           users_b
2017-12-01     17                20
2017-12-02     4                 9
```

The two queries give accurate results if they are executed separately, and I just want the data to be in one table. However, I get the following error:

```
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN (SELECT DATE(datetime) AS date, COUNT(`id`) AS users_b FROM ' at line 2
```

答:
JOINs must occur before the HAVING clause.

Per the MySQL SELECT documentation:

```<code>SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [FROM table_references
      [PARTITION partition_list]
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name'
        [CHARACTER SET charset_name]
        export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]
</code>```

Plus, you could also simplify it into something like:

```<code>SELECT
    DATE(`datetime_column`) AS `date`,
    SUM(IF(`rank` = 'good', 1, 0)) AS `users_a`,
    SUM(IF(`rank` = 'bad', 1, 0)) AS `users_b`
FROM
    `users`
WHERE
   datetime_column >= '2017-12-01'
GROUP BY
    DATE(datetime_column)
</code>```

Which increments the users_a column for every 'good' user, and users_b for every 'bad'.

Title: MySQL - Error #1064 in LEFT JOIN

Body:
I am currently trying to get the data formatted using only MySQL query. I do not want to manipulate it using a programming language. All the operations are done only on one table.

Here is my query:

    SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_a FROM users a
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "good"

    LEFT JOIN (SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_b FROM users
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "bad") AS b
    ON b.date = a.date;

The output should be like:

date           users_a           users_b
2017-12-01     17                20
2017-12-02     4                 9

The two queries give accurate results if they are executed separately, and I just want the data to be in one table. However, I get the following error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN (SELECT DATE(datetime) AS date, COUNT(`id`) AS users_b FROM ' at line 2

Body:
JOINs must occur before the HAVING clause.

Per the MySQL SELECT documentation:

SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [FROM table_references
      [PARTITION partition_list]
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name'
        [CHARACTER SET charset_name]
        export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]

Plus, you could also simplify it into something like:

SELECT
    DATE(`datetime_column`) AS `date`,
    SUM(IF(`rank` = 'good', 1, 0)) AS `users_a`,
    SUM(IF(`rank` = 'bad', 1, 0)) AS `users_b`
FROM
    `users`
WHERE
   datetime_column >= '2017-12-01'
GROUP BY
    DATE(datetime_column)

Which increments the users_a column for every 'good' user, and users_b for every 'bad'.


问:
UIButton appearance layer in appdelegate not working
I want to make all the buttons in the app as a rounded button.

But UIButton appearance does not change the layer properties in appdelegate:

```<code>[[[UIButton appearance] layer] setMasksToBounds:YES];
[[[UIButton appearance] layer] setCornerRadius:8.0f];
</code>```

What's wrong?

many thanks

答:
As this is an old question but it came up as related, you can't change the layer properties using appearance. For a complete list, you can check this page.

For the UIButton, the valid options are:

```<code>//UIView

@property(nullable, nonatomic,copy) UIColor *backgroundColor UI_APPEARANCE_SELECTOR;

//UIButton

@property(nonatomic) UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR;

- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setTitleShadowColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
</code>```

Body:
I want to make all the buttons in the app as a rounded button.

But UIButton appearance does not change the layer properties in appdelegate:

[[[UIButton appearance] layer] setMasksToBounds:YES];
[[[UIButton appearance] layer] setCornerRadius:8.0f];

What's wrong?

many thanks

Body:
As this is an old question but it came up as related, you can't change the layer properties using appearance. For a complete list, you can check this page.

For the UIButton, the valid options are:

//UIView

@property(nullable, nonatomic,copy) UIColor *backgroundColor UI_APPEARANCE_SELECTOR;

//UIButton

@property(nonatomic) UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR;

- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setTitleShadowColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state UI_APPEARANCE_SELECTOR;


问:
Howto split a string on a multi-character delimiter in bash?
Why doesn't work the following bash code?

```<code>for i in $( echo "emmbbmmaaddsb" | split -t "mm"  )
do
    echo "$i"
done
</code>```

expected output:

```<code>e
bb
aaddsb
</code>```

答:
A more general example, without replacing the multi-character delimiter with a single character delimiter is given below :

Using parameter expansions : (from the comment of @gniourf_gniourf)

```<code>#!/bin/bash

str="LearnABCtoABCSplitABCaABCString"
delimiter=ABC
s=$str$delimiter
array=();
while [[ $s ]]; do
    array+=( "${s%%"$delimiter"*}" );
    s=${s#*"$delimiter"};
done;
declare -p array
</code>```

A more crude kind of way

```<code>#!/bin/bash

# main string
str="LearnABCtoABCSplitABCaABCString"

# delimiter string
delimiter="ABC"

#length of main string
strLen=${#str}
#length of delimiter string
dLen=${#delimiter}

#iterator for length of string
i=0
#length tracker for ongoing substring
wordLen=0
#starting position for ongoing substring
strP=0

array=()
while [ $i -lt $strLen ]; do
    if [ $delimiter == ${str:$i:$dLen} ]; then
        array+=(${str:strP:$wordLen})
        strP=$(( i + dLen ))
        wordLen=0
        i=$(( i + dLen ))
    fi
    i=$(( i + 1 ))
    wordLen=$(( wordLen + 1 ))
done
array+=(${str:strP:$wordLen})

declare -p array
</code>```

Reference - Bash Tutorial - Bash Split String

Body:
Why doesn't work the following bash code?

for i in $( echo "emmbbmmaaddsb" | split -t "mm"  )
do
    echo "$i"
done

expected output:

e
bb
aaddsb

Body:
A more general example, without replacing the multi-character delimiter with a single character delimiter is given below :

Using parameter expansions : (from the comment of @gniourf_gniourf)

#!/bin/bash

str="LearnABCtoABCSplitABCaABCString"
delimiter=ABC
s=$str$delimiter
array=();
while [[ $s ]]; do
    array+=( "${s%%"$delimiter"*}" );
    s=${s#*"$delimiter"};
done;
declare -p array

A more crude kind of way

#!/bin/bash

# main string
str="LearnABCtoABCSplitABCaABCString"

# delimiter string
delimiter="ABC"

#length of main string
strLen=${#str}
#length of delimiter string
dLen=${#delimiter}

#iterator for length of string
i=0
#length tracker for ongoing substring
wordLen=0
#starting position for ongoing substring
strP=0

array=()
while [ $i -lt $strLen ]; do
    if [ $delimiter == ${str:$i:$dLen} ]; then
        array+=(${str:strP:$wordLen})
        strP=$(( i + dLen ))
        wordLen=0
        i=$(( i + dLen ))
    fi
    i=$(( i + 1 ))
    wordLen=$(( wordLen + 1 ))
done
array+=(${str:strP:$wordLen})

declare -p array

Reference - Bash Tutorial - Bash Split String


问:
JavaScript invalid date from DateTime Picker
I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.

But my first value (rtime) always gives an invalid date. Where am I wrong?

Note: stime is not editable, the user only uses the DateTime Picker for rtime field.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);```

This result shows that LastOut is an invalid date:

答:
The format must be month/day/year, not day/month/year

That why you get invallid date on 28/11/2017 09:18:52 because there isn't a 28th month.

console.log(new Date('28/11/2017 09:18:52'))
console.log(new Date('11/28/2017 09:18:52'))```

Body:
I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.

But my first value (rtime) always gives an invalid date. Where am I wrong?

Note: stime is not editable, the user only uses the DateTime Picker for rtime field.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);

This result shows that LastOut is an invalid date:


问:
Immutable Struct in Golang
Is it possible to define an immutable struct in Golang? Once initialized then only read operation on struct's field, no modification of field values. If so, how to do that.</p>

答: There is no way to mark fields/variables as read only in a generic way. The only thing you could do is marking fields/variable as unexported (first letter small) and provide public getters to prevent other packages editing variables.</p>

Title: Immutable Struct in Golang


问:
Communication between App and iWatch: is using app group the only way?
I have an iPhone app that performs some computations. It works well. Now I'd like to create a WatchKit extension and target in order to control the start of the computations and display the results once the computations are finished as well as update the progress (e.g. percentage completed when Watch app is displayed, and send a notification from the iPhone app to the iWatch when the progress reaches a significant percentage mark).

I have found some tutorials that explain to use NSUserDefaults and initWithSuitName providing an app group and then add the data object to synchronise. I could use KVO to display a percentage label on the Watch.

As I am exploring the possible architectures here, are you aware of some alternative methods to achieve this? Is using app group the method that Apple recommends?

答:
You can follow this steps

After setting Watch kit session and creating data dictionary you can use send message with this

```<code>[[WCSession defaultSession] sendMessage:<Your Dictionary> replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {

        //You task on completion

    } errorHandler:^(NSError * _Nonnull error) {

        if (error)
        {
            //Handle the error
        }
    }];
</code>```

at watch extension side
You can set delegate method

```<code>- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
{
     //Handle the received data
}
</code>```

And you are done

Body:
You can follow this steps

After setting Watch kit session and creating data dictionary you can use send message with this

[[WCSession defaultSession] sendMessage:<Your Dictionary> replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {

        //You task on completion

    } errorHandler:^(NSError * _Nonnull error) {

        if (error)
        {
            //Handle the error
        }
    }];

at watch extension side
You can set delegate method

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
{
     //Handle the received data
}

And you are done


问:
horizontal lines along the y axis d3 bar chart
https://jsfiddle.net/betasquirrel/pnyn7vzj/1/   in this plunkr how the horizontal lines along the y axis are added

I just tried adding this css code

```<code>  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
  }
</code>```

I want to develop bar without the x axis , I have attached an image please check with that.

答:
In your code, where you define your xAxis. Instead of:

```<code>var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickFormat(d3.time.format("%Y"));
</code>```

You should try:

```<code>var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickValues([]);
</code>```

This will remove your x-axis labels and ticks. Read this post for more information.

Body:
https://jsfiddle.net/betasquirrel/pnyn7vzj/1/   in this plunkr how the horizontal lines along the y axis are added

I just tried adding this css code

  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
  }

I want to develop bar without the x axis , I have attached an image please check with that.

Body:
In your code, where you define your xAxis. Instead of:

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickFormat(d3.time.format("%Y"));

You should try:

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickValues([]);

This will remove your x-axis labels and ticks. Read this post for more information.


问:
Finding Median in C
I wrote this code to find mean and median but I always take these errors:

"71 warning: passing argument 1 of 'median' makes pointer from integer without a cast"

and:

"14 note: expected 'int *' but argument is of type 'int'".

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

float mean(float x,int y)
{
float toplam = x;
int adet=y;

return toplam/adet;

}

int median(int AlinanSayilar[200],int adet)
{
int kacinci,kacinci2;
int medyan=0;

if(adet%2==1)
{
    kacinci=(adet/2)-1;
    kacinci2=kacinci+1;
    medyan=(AlinanSayilar[kacinci]+AlinanSayilar[kacinci2])/2;
}
else
{
    kacinci=(adet/2)-0.5;
    medyan=AlinanSayilar[kacinci];
}

printf("%d",medyan);

return 0;
}

int main()
{
int sayilar[200];
int i,k,j,holder;
float sum=0;

printf("Welcome the calculator...\n\tThis calculator finds mean,median and
mode of your numbers...\n");
printf("\t\tNOTE:Please enter only integer numbers...\n\n");

for(i=0;true;i++)
{
    printf("Please enter a number(press -1 for exit): ");
    scanf("%d",&sayilar[i]);
    printf("\n");

    if(sayilar[i]==-1){
        break;
        }
    sum +=sayilar[i];
}

for(k=0;k<i-1;k++)
{
    for(j=k+1;j<i;j++)
    {
        if(sayilar[k]>sayilar[j])
        {
            holder=sayilar[k];
            sayilar[k]=sayilar[j];
            sayilar[j]=holder;
        }
    }
}

printf("Mean:%.2f",mean(sum,i));
median(sayilar[i],i);

system("pause");
return 0;
}
</code>```

What should I do?Thanks in advance for your helping.And if you know finding mode(most repetitive number) could you write its code?

答:
```<code>#include <stdio.h>
#include <stdlib.h>
int b[100],m,md,i,n1,md1,md2,mdt,sum,n;
int mean(int n, int a[])
{
    for(i=0;i<n;i++)
    {
        sum+=a[i];
    }
    m=sum/n;
    return m;
}
int median(int n,int a[])
{
    if(n%2==0)
    {
        md1=(n/2)-1;
    md2=(n/2);
    mdt=(a[md1]+a[md2])/2;
    return mdt;

    }
    else
    {
     md=(n/2)-1;
        return a[md];
    }
}
 main()
{
    int rmean,rmedian;
    n1=10;//declaring the number of integers
    for(i=0;i<n1;i++)
    {
        b[i]=i+1;// assigning the integer values of the array in which mean and //median is to be found

    }
    rmean=mean(n1,b);
    rmedian=median(n1,b);
    printf("the mean :%d",rmean);
    printf("the median: %d",rmedian);
}
</code>```

Title: Finding Median in C

Body:
I wrote this code to find mean and median but I always take these errors:

"71 warning: passing argument 1 of 'median' makes pointer from integer without a cast"

and:

"14 note: expected 'int *' but argument is of type 'int'".

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

float mean(float x,int y)
{
float toplam = x;
int adet=y;

return toplam/adet;

}

int median(int AlinanSayilar[200],int adet)
{
int kacinci,kacinci2;
int medyan=0;

if(adet%2==1)
{
    kacinci=(adet/2)-1;
    kacinci2=kacinci+1;
    medyan=(AlinanSayilar[kacinci]+AlinanSayilar[kacinci2])/2;
}
else
{
    kacinci=(adet/2)-0.5;
    medyan=AlinanSayilar[kacinci];
}

printf("%d",medyan);

return 0;
}

int main()
{
int sayilar[200];
int i,k,j,holder;
float sum=0;

printf("Welcome the calculator...\n\tThis calculator finds mean,median and
mode of your numbers...\n");
printf("\t\tNOTE:Please enter only integer numbers...\n\n");

for(i=0;true;i++)
{
    printf("Please enter a number(press -1 for exit): ");
    scanf("%d",&sayilar[i]);
    printf("\n");

    if(sayilar[i]==-1){
        break;
        }
    sum +=sayilar[i];
}

for(k=0;k<i-1;k++)
{
    for(j=k+1;jsayilar[j])
        {
            holder=sayilar[k];
            sayilar[k]=sayilar[j];
            sayilar[j]=holder;
        }
    }
}

printf("Mean:%.2f",mean(sum,i));
median(sayilar[i],i);

system("pause");
return 0;
}

What should I do?Thanks in advance for your helping.And if you know finding mode(most repetitive number) could you write its code?