问:
email confirmation verification
I have a Wcf service and an Xamarin.forms mobile application, when the user registers from the mobile app I want the web service to send an email verification to the user, when the user goes to his/her email and clicks the link the user account will be activated.

I only have one solution which is to have the user id in the verification link and give the service url followed by verification function and user id.

Is there a better secure way to do so as I dont want to give wcf link in the link?

```<code>private void SendEmailConfirmation(String EmailId,string UserId)
        {
            MailMessage msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            string emailId = EmailId;
            msg.From = new MailAddress("YourGmailEmailId@gmail.com");
            msg.To.Add(emailId);
            msg.Subject = "Confirmation email for account activation";
            //For testing replace the local host path with your lost host path and while making online replace with your website domain name
            //string ActivationUrl = "http://localhost:8665/FetchUserId(emailId) & "&EmailId=" & emailId);
            msg.Body ="Thanks for showing interest and registring in <a href='http://www.activationlink.com'> webservice.com<a> " +
                  " Please Thanks!";
            msg.IsBodyHtml = true;
            smtp.Credentials = new NetworkCredential("emailaddress@gmail.com", "mypassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            //NetworkCredential Credentials = new NetworkCredential("emailaddress@gmail.com", "Super2@17");
            //smtp.UseDefaultCredentials = false;
            smtp.Send(msg);
        }
</code>```

答:
You can create a function to generate a non sensible code (like a token, hash, guid or something like this) and associate this to the user data and a date limit to activate that link (24 hours for example). </p>

<p>Then, when the user click this link with the token, you verify if the token is still valid and enable the user's account. </p>

Title: email confirmation verification

Body:
I have a Wcf service and an Xamarin.forms mobile application, when the user registers from the mobile app I want the web service to send an email verification to the user, when the user goes to his/her email and clicks the link the user account will be activated.

I only have one solution which is to have the user id in the verification link and give the service url followed by verification function and user id.

Is there a better secure way to do so as I dont want to give wcf link in the link?

private void SendEmailConfirmation(String EmailId,string UserId)
        {
            MailMessage msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            string emailId = EmailId;
            msg.From = new MailAddress("YourGmailEmailId@gmail.com");
            msg.To.Add(emailId);
            msg.Subject = "Confirmation email for account activation";
            //For testing replace the local host path with your lost host path and while making online replace with your website domain name
            //string ActivationUrl = "http://localhost:8665/FetchUserId(emailId) & "&EmailId=" & emailId);
            msg.Body ="Thanks for showing interest and registring in  webservice.com " +
                  " Please Thanks!";
            msg.IsBodyHtml = true;
            smtp.Credentials = new NetworkCredential("emailaddress@gmail.com", "mypassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            //NetworkCredential Credentials = new NetworkCredential("emailaddress@gmail.com", "Super2@17");
            //smtp.UseDefaultCredentials = false;
            smtp.Send(msg);
        }

Body:
You can create a function to generate a non sensible code (like a token, hash, guid or something like this) and associate this to the user data and a date limit to activate that link (24 hours for example).

Then, when the user click this link with the token, you verify if the token is still valid and enable the user's account.


来源: stackexchange

问:
How to determine if a JSON response will bind to a model
We have a 3rd party service provider that based on a action a notification Webhook is sent to our webhook url using JSON. Due to the fact that i can only provide 1 webhook url all notifications need to funnel to the 1 url. I need to determine which model to deserialze to.

I understand how to deserialize JSON string into an object model.

Here is an example of what is first sent to our webhook

```<code>{
    "providerAccount": {
        "id": XXXXXX,
        "aggregationSource": "USER",
        "refreshInfo": {
            "statusCode": 801,
            "statusMessage": "ADD_IN_PROGRESS",
            "status": "IN_PROGRESS",
            "additionalStatus": "LOGIN_IN_PROGRESS"
        }
    }
}
</code>```

and then after another 10 or so seconds another JSON webhook comes in.

```<code>{
    "event": {
        "info": "REFRESH.INTERIM_PROGRESS",
        "loginName": "XXXXXX",
        "data": {
            "providerAccount": {
                "id": XXXXXX,
                "providerId": XXXXXX,
                "isManual": false,
                "createdDate": "2017-12-08",
                "aggregationSource": "USER",
                "refreshInfo": {
                    "status": "IN_PROGRESS",
                    "additionalStatus": "LOGIN_SUCCESS",
                    "statusCode": 0,
                    "statusMessage": "OK",
                    "nextRefreshScheduled": "0001-01-01T00:00:00",
                    "lastRefreshed": "0001-01-01T00:00:00",
                    "lastRefreshAttempt": "0001-01-01T00:00:00"
                },
                "loginForm": null
            }
        }
    }
}
</code>```

As you can see they would be 2 separate model objects which i need to deserialize.

I find that checking for null on the first model to the second model seems wrong and can be achieved in a different way.

There are another 3 different JSON strings that come through the same webhook. and to check for if model is null, if this model is null etc. then move to next seems wrong.

答:
You can use json schemas to be sure that incoming json indeed matches one of your models exactly. Schemas can be generated from your models (see here for details). Sample code (install Newtonsoft.Json.Schemas package):

```<code>public class ModelMapper {
    private readonly List<SchemaAndHandler> _handlers = new List<SchemaAndHandler>();

    public void AddModelHandler<T>(Func<T, object> handler) {
        // generate schema once
        var schema = new JSchemaGenerator().Generate(typeof(T));
        _handlers.Add(new SchemaAndHandler(schema, typeof(T), o => handler((T) o)));
    }

    public object Parse(string json) {
        var raw = JObject.Parse(json);
        foreach (var handler in _handlers) {
            // validate according to each schema
            if (raw.IsValid(handler.Schema)) {
                return handler.Handler(JsonConvert.DeserializeObject(json, handler.Type));
            }
        }
        // or throw
        return null;
    }

    private class SchemaAndHandler {
        public SchemaAndHandler(JSchema schema, Type type, Func<object, object> handler) {
            Schema = schema;
            Type = type;
            Handler = handler;
        }
        public JSchema Schema { get; }
        public Type Type { get; }
        public Func<object, object> Handler { get; }
    }
}

public class Model1 {
    public int Id { get; set; }
}

public class Model2 {
    public string Name { get; set; }
}
</code>```

Usage:

```<code>// should be reused - no need to create per every request
var mapper = new ModelMapper();
// this also needs to be done only once
mapper.AddModelHandler((Model1 model) => {
    // do something
    return model;
});
mapper.AddModelHandler((Model2 model) => {
    // do something
    return model;
});
// parse incoming json to some result
var result = mapper.Parse("{Name: \"test\"}");
</code>```

If you don't need to do anything specific with parsed model and just need to pass it somewhere, it can be simplified:

```<code>public class ModelMapper {
    private readonly List<Tuple<Type, JSchema>> _schemas = new List<Tuple<Type, JSchema>>();

    public ModelMapper(params Type[] models) {
        foreach (var model in models) {
            var schema = new JSchemaGenerator().Generate(model);
            _schemas.Add(Tuple.Create(model, schema));
        }
    }

    public object ParseModel(string json) {
        var raw = JObject.Parse(json);
        foreach (var schema in _schemas) {
            // validate according to each schema
            if (raw.IsValid(schema.Item2)) {
                return JsonConvert.DeserializeObject(json, schema.Item1);
            }
        }
        // or throw
        return null;
    }
}
</code>```

Usage is then:

```<code>// should be reused - no need to create per every request
var mapper = new ModelMapper(typeof(Model1), typeof(Model2));
var result = mapper.ParseModel("{Name: \"test\"}");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We have a 3rd party service provider that based on a action a notification Webhook is sent to our webhook url using JSON. Due to the fact that i can only provide 1 webhook url all notifications need to funnel to the 1 url. I need to determine which model to deserialze to.

I understand how to deserialize JSON string into an object model.

Here is an example of what is first sent to our webhook

{
    "providerAccount": {
        "id": XXXXXX,
        "aggregationSource": "USER",
        "refreshInfo": {
            "statusCode": 801,
            "statusMessage": "ADD_IN_PROGRESS",
            "status": "IN_PROGRESS",
            "additionalStatus": "LOGIN_IN_PROGRESS"
        }
    }
}

and then after another 10 or so seconds another JSON webhook comes in.

{
    "event": {
        "info": "REFRESH.INTERIM_PROGRESS",
        "loginName": "XXXXXX",
        "data": {
            "providerAccount": {
                "id": XXXXXX,
                "providerId": XXXXXX,
                "isManual": false,
                "createdDate": "2017-12-08",
                "aggregationSource": "USER",
                "refreshInfo": {
                    "status": "IN_PROGRESS",
                    "additionalStatus": "LOGIN_SUCCESS",
                    "statusCode": 0,
                    "statusMessage": "OK",
                    "nextRefreshScheduled": "0001-01-01T00:00:00",
                    "lastRefreshed": "0001-01-01T00:00:00",
                    "lastRefreshAttempt": "0001-01-01T00:00:00"
                },
                "loginForm": null
            }
        }
    }
}

As you can see they would be 2 separate model objects which i need to deserialize.

I find that checking for null on the first model to the second model seems wrong and can be achieved in a different way.

There are another 3 different JSON strings that come through the same webhook. and to check for if model is null, if this model is null etc. then move to next seems wrong.

Body:
You can use json schemas to be sure that incoming json indeed matches one of your models exactly. Schemas can be generated from your models (see here for details). Sample code (install Newtonsoft.Json.Schemas package):

public class ModelMapper {
    private readonly List<SchemaAndHandler> _handlers = new List<SchemaAndHandler>();

    public void AddModelHandler<T>(Func<T, object> handler) {
        // generate schema once
        var schema = new JSchemaGenerator().Generate(typeof(T));
        _handlers.Add(new SchemaAndHandler(schema, typeof(T), o => handler((T) o)));
    }

    public object Parse(string json) {
        var raw = JObject.Parse(json);
        foreach (var handler in _handlers) {
            // validate according to each schema
            if (raw.IsValid(handler.Schema)) {
                return handler.Handler(JsonConvert.DeserializeObject(json, handler.Type));
            }
        }
        // or throw
        return null;
    }

    private class SchemaAndHandler {
        public SchemaAndHandler(JSchema schema, Type type, Func<object, object> handler) {
            Schema = schema;
            Type = type;
            Handler = handler;
        }
        public JSchema Schema { get; }
        public Type Type { get; }
        public Func<object, object> Handler { get; }
    }
}

public class Model1 {
    public int Id { get; set; }
}

public class Model2 {
    public string Name { get; set; }
}

Usage:

// should be reused - no need to create per every request
var mapper = new ModelMapper();
// this also needs to be done only once
mapper.AddModelHandler((Model1 model) => {
    // do something
    return model;
});
mapper.AddModelHandler((Model2 model) => {
    // do something
    return model;
});
// parse incoming json to some result
var result = mapper.Parse("{Name: \"test\"}");

If you don't need to do anything specific with parsed model and just need to pass it somewhere, it can be simplified:

public class ModelMapper {
    private readonly List<Tuple<Type, JSchema>> _schemas = new List<Tuple<Type, JSchema>>();

    public ModelMapper(params Type[] models) {
        foreach (var model in models) {
            var schema = new JSchemaGenerator().Generate(model);
            _schemas.Add(Tuple.Create(model, schema));
        }
    }

    public object ParseModel(string json) {
        var raw = JObject.Parse(json);
        foreach (var schema in _schemas) {
            // validate according to each schema
            if (raw.IsValid(schema.Item2)) {
                return JsonConvert.DeserializeObject(json, schema.Item1);
            }
        }
        // or throw
        return null;
    }
}

Usage is then:

// should be reused - no need to create per every request
var mapper = new ModelMapper(typeof(Model1), typeof(Model2));
var result = mapper.ParseModel("{Name: \"test\"}");


问:
problem with sizeof operator
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result.
here is one demo program to show you, what i want to do.

```<code>//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------
</code>```

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

```<code>array size(in function):2
array size:19
</code>```

please explain ,why this is happening.
what can be done to solve this problem.

答: you are getting the size of the pointer to the array. If you want the size of the array you have to multiply the number of elements by the size of each element.</p>

ContentLicense: CC BY-SA 2.5

Title: problem with sizeof operator

Body:
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result.
here is one demo program to show you, what i want to do.

//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

array size(in function):2
array size:19

please explain ,why this is happening.
what can be done to solve this problem.


问:
How to do Pagination with All option in kendo grid with angular 2
I want to add 'All' option pagination dropdown. How do I achieve this for Kendo Grid with Angular 2

答:
You can use the Grid PagerTemplate and provide a DropDownList (or other UI element of your preference) with custom page sizes and behavior, e.g.:

```<code><ng-template kendoPagerTemplate let-totalPages="totalPages" let-currentPage="currentPage">
            <kendo-pager-prev-buttons></kendo-pager-prev-buttons>
            <kendo-pager-numeric-buttons [buttonCount]="10"></kendo-pager-numeric-buttons>
            <kendo-pager-info></kendo-pager-info>
            <kendo-pager-next-buttons></kendo-pager-next-buttons>
            <kendo-dropdownlist
              [data]="pageSizes"
              [textField]="'text'"
              [valueField]="'value'"
              [valuePrimitive]="true"
              [(value)]="pageSize"></kendo-dropdownlist>
         </ng-template>
</code>```

EXAMPLE

Body:
You can use the Grid PagerTemplate and provide a DropDownList (or other UI element of your preference) with custom page sizes and behavior, e.g.:

<ng-template kendoPagerTemplate let-totalPages="totalPages" let-currentPage="currentPage">
            <kendo-pager-prev-buttons></kendo-pager-prev-buttons>
            <kendo-pager-numeric-buttons [buttonCount]="10"></kendo-pager-numeric-buttons>
            <kendo-pager-info></kendo-pager-info>
            <kendo-pager-next-buttons></kendo-pager-next-buttons>
            <kendo-dropdownlist
              [data]="pageSizes"
              [textField]="'text'"
              [valueField]="'value'"
              [valuePrimitive]="true"
              [(value)]="pageSize"></kendo-dropdownlist>
         </ng-template>

EXAMPLE


问:
php: chars from String without conversion
i try to decode a string with php. It was coded bevore with vba on another machine. The Strings will come from a database. But for the first time a hardcoded String, to find the problems. The Teststring is "¦ÞµºÎ× hg". With VBA i get the following result when exploding to chars an get the Ascii Values:

¦ÞµºÎ× hg <- the String

9 <- length of the String

1:¦:166  <- first Char = "¦", Ascii Code 166
2:Þ:222  <- second Char = "Þ", Ascii Code 222
3:µ:181  and so on
4:º:186
5:Î:206
6:×:215
7: :160
8:h:104
9:g:103```
</div>
</div>
</p>

<p>when Trying the same with php maybe php thinks this is UTF8 coded or anything else and gives me wrong chars:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>"¦ÞµºÎ× hg" <- Input String

16 <- length 16???

b"""       <- i dindn't know from where this is?!
\n
1:¦:166\n  <- first Char = "¦", Ascii Code 166, correct!
2:Ã:195\n  <- second Char = "Ã", Ascii Code 195, WTF?
3:ž:158\n
4:Â:194\n
5:µ:181\n
6:Â:194\n
7:º:186\n
8:Ã:195\n
9:Ž:142\n
10:Ã:195\n
11:—:151\n
"""

""</code>```

I've tried different ways to get the chars out of the String and i've tried different things with detect_encoding and iconv, but the result stays always the same:

$strToDecode = "¦ÞµºÎ× hg"
$lenEnc = mb_strlen($strToDecode, 'ASCII');

 $r = "";
 $asci = 0;
 $char = "";
 $rTest = "\n";
 for($i=1; $i <= $lenEnc-5; $i++) {
  //$r = Right($strToDecode, $lenEnc - $i );
  //$r = mb_substr($strToDecode, $i, 1, "ASCII");
  $r = $strToDecode[$i];
  $asci = ord($r);
  $rTest .= $i . ":" . $r . ":" . $asci . "\n";
  $strResult .= $char;
 }

dd($strToDecode, $lenEnc, $rTest, $strResult);```

What can i do, to get the real chars without changing them?

Many thanks for every tip :)

best Regards.

答:
That is because your string "¦ÞµºÎ× hg" is probably stored in multi-bytes in your PHP file (the source file) and you are using the ASCII parameter.

If you just removed the ASCII parameter(because it's not ASCII) from the mb_* functions your code will work as you expect

```<code>$strToDecode = "¦ÞµºÎ× hg";
$lenEnc = mb_strlen($strToDecode);// REMOVED 'ASCII'
//var_dump($lenEnc); // its 9 NOW
$r = "";
$vp = 0;
$asci = 0;
$gofi = 0;
$char = "";
$rTest = "\n";
$strResult = "";
for($i=0; $i < $lenEnc; $i++) {
    $r = mb_substr($strToDecode, $i, 1);// REMOVED 'ASCII'
    $asci = ord($r);
    $rTest .= $i . ":" . $r . ":" . $asci . "\n";
    $strResult .= $char;
}
var_dump($rTest);exit;
</code>```

this outputs on my machine

```<code>string(78) "
0:¦:194
1:Þ:195
2:µ:194
3:º:194
4:Î:195
5:×:195
6: :32
7:h:104
8:g:103
"
</code>```

I have made another test to verify . I changed the source file encoding to ANSI (after making a backup of the file), and your old code works fine with the ASCII parameters. change it with your editor to see with yourself.

Body:
i try to decode a string with php. It was coded bevore with vba on another machine. The Strings will come from a database. But for the first time a hardcoded String, to find the problems. The Teststring is "¦ÞµºÎ× hg". With VBA i get the following result when exploding to chars an get the Ascii Values:

¦ÞµºÎ× hg <- the String

9 <- length of the String

1:¦:166  <- first Char = "¦", Ascii Code 166
2:Þ:222  <- second Char = "Þ", Ascii Code 222
3:µ:181  and so on
4:º:186
5:Î:206
6:×:215
7: :160
8:h:104
9:g:103

when Trying the same with php maybe php thinks this is UTF8 coded or anything else and gives me wrong chars:

"¦ÞµºÎ× hg" <- Input String

16 <- length 16???

b"""       <- i dindn't know from where this is?!
\n
1:¦:166\n  <- first Char = "¦", Ascii Code 166, correct!
2:Ã:195\n  <- second Char = "Ã", Ascii Code 195, WTF?
3:ž:158\n
4:Â:194\n
5:µ:181\n
6:Â:194\n
7:º:186\n
8:Ã:195\n
9:Ž:142\n
10:Ã:195\n
11:—:151\n
"""

""

I've tried different ways to get the chars out of the String and i've tried different things with detect_encoding and iconv, but the result stays always the same:

$strToDecode = "¦ÞµºÎ× hg"
$lenEnc = mb_strlen($strToDecode, 'ASCII');

 $r = "";
 $asci = 0;
 $char = "";
 $rTest = "\n";
 for($i=1; $i <= $lenEnc-5; $i++) {
  //$r = Right($strToDecode, $lenEnc - $i );
  //$r = mb_substr($strToDecode, $i, 1, "ASCII");
  $r = $strToDecode[$i];
  $asci = ord($r);
  $rTest .= $i . ":" . $r . ":" . $asci . "\n";
  $strResult .= $char;
 }

dd($strToDecode, $lenEnc, $rTest, $strResult);

What can i do, to get the real chars without changing them?

Many thanks for every tip :)

best Regards.

Body:
That is because your string "¦ÞµºÎ× hg" is probably stored in multi-bytes in your PHP file (the source file) and you are using the ASCII parameter.

If you just removed the ASCII parameter(because it's not ASCII) from the mb_* functions your code will work as you expect

$strToDecode = "¦ÞµºÎ× hg";
$lenEnc = mb_strlen($strToDecode);// REMOVED 'ASCII'
//var_dump($lenEnc); // its 9 NOW
$r = "";
$vp = 0;
$asci = 0;
$gofi = 0;
$char = "";
$rTest = "\n";
$strResult = "";
for($i=0; $i < $lenEnc; $i++) {
    $r = mb_substr($strToDecode, $i, 1);// REMOVED 'ASCII'
    $asci = ord($r);
    $rTest .= $i . ":" . $r . ":" . $asci . "\n";
    $strResult .= $char;
}
var_dump($rTest);exit;

this outputs on my machine

string(78) "
0:¦:194
1:Þ:195
2:µ:194
3:º:194
4:Î:195
5:×:195
6: :32
7:h:104
8:g:103
"

I have made another test to verify . I changed the source file encoding to ANSI (after making a backup of the file), and your old code works fine with the ASCII parameters. change it with your editor to see with yourself.


答:
```<code>void getSize(int *S1)
</code>```

When you pass an array to this function, it decays to pointer type, so sizeof operator will return the size of pointer.

However, you define your function as,

```<code>template<int N>
void getSize(int (&S1)[N])
{
   //N is the size of array
   int S_size1 = N;
   int S_size2 = sizeof(S1)/sizeof(int); //would be equal to N!!
   std::cout<<"array size(in function):"<<S_size1<<std::endl;
   std::cout<<"array size(in function):"<<S_size2<<std::endl;
}

int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
getSize(S); //same as before
</code>```

then you can have the size of array, in the function!

See the demonstration yourself here : http://www.ideone.com/iGXNU

Title: problem with sizeof operator

Body:
void getSize(int *S1)

When you pass an array to this function, it decays to pointer type, so sizeof operator will return the size of pointer.

However, you define your function as,

template<int N>
void getSize(int (&S1)[N])
{
   //N is the size of array
   int S_size1 = N;
   int S_size2 = sizeof(S1)/sizeof(int); //would be equal to N!!
   std::cout<<"array size(in function):"<<S_size1<<std::endl;
   std::cout<<"array size(in function):"<<S_size2<<std::endl;
}

int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
getSize(S); //same as before

then you can have the size of array, in the function!

See the demonstration yourself here : http://www.ideone.com/iGXNU


问:
Product of numbers with tail-recursive predicate in prolog
I'm trying to write a tail-recursive predicate in Prolog: product(A,B), which is true if B is the product of the numbers in list A. Here is the code I've written so far:

```<code>product(A, B) :- product(A, 1, B).
product(0, B, B) :- !.
product(A, X, B) :- Z is A - 1, Y is X * A, product(Z, Y, B).
</code>```

The code works without a list. I'm pretty new to lists in Prolog, so I want to ask what is the best way to do this. The query should be something like this:

```<code>?- product([1,2,3], B).
B = 6.
</code>```

答:
You can write something like that

```<code>product(In, Out) :-
    % We call the predicate product/3, initialize with 1
    product(In, 1, Out).

% when the list is empty with have the result
product([], Out, Out).

% we compute the first element of the list
product([H|T], Cur, Out) :-
    Next is Cur * H,
    % we carry on with the rest
    product(T, Next, Out).
</code>```

EDIT
Product not tail recursive.

```<code>product1([], 1).

product1([H|T],Out) :-
    product1(T, Next),
    Out is Next * H.
</code>```

Body:
I'm trying to write a tail-recursive predicate in Prolog: product(A,B), which is true if B is the product of the numbers in list A. Here is the code I've written so far:

product(A, B) :- product(A, 1, B).
product(0, B, B) :- !.
product(A, X, B) :- Z is A - 1, Y is X * A, product(Z, Y, B).

The code works without a list. I'm pretty new to lists in Prolog, so I want to ask what is the best way to do this. The query should be something like this:

?- product([1,2,3], B).
B = 6.

Body:
You can write something like that

product(In, Out) :-
    % We call the predicate product/3, initialize with 1
    product(In, 1, Out).

% when the list is empty with have the result
product([], Out, Out).

% we compute the first element of the list
product([H|T], Cur, Out) :-
    Next is Cur * H,
    % we carry on with the rest
    product(T, Next, Out).

EDIT
Product not tail recursive.

product1([], 1).

product1([H|T],Out) :-
    product1(T, Next),
    Out is Next * H.


问:
What is a simple way to set up an on click handler for 4 quiz answer buttons?
I have 4 beautiful buttons of class .button in css. Is there a simple way (presumably jQuery is the standard method) to put a event listener on these buttons.

Obviously the code will need to record which button was clicked, because only one of them has the right answer. The code below doesn't make that distinction, as button is a class not an ID. I suspect I will have to create four separate button IDs but that will multiply my css code by four.

I have been searching for a jQuery solution for a few days but not able to get any code to suit my particular situation.

This is the first time I have used jQuery, so if I have blundered, please don't be too harsh! I will greatly appreciate any knowledgeable contribution to solve this puzzle.

Here is the code from where the answers get sorted and displayed:

$(document).ready(function() {
  $("input:button").click(function() {
    alert('a button was clicked.')
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>What is this?</b></p>
<div>
  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">
</div></code>```

答:
Here's one way you can do it with a for loop.

javascript file

```<code>$(document).ready(function() {
  var $buttons = $('.control-panel input:button');

  for (var i = 0; i < $buttons.length; i++) {
    $($buttons[i]).click((button) => {
      alert(button.target.value);
    });
  }
});
</code>```

html file

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>What is this?</b></p>
<div class="control-panel">
  <input type="button" class="button" value="Button 1">
  <input type="button" class="button" value="Button 2">
  <input type="button" class="button" value="Button 3">
  <input type="button" class="button" value="Button 4">
</div>
</code>```

I added a value attribute to your inputs (which you're using as the buttons) to differentiate them.

Also, added a .control-panel class to the parent element so you can target only the buttons that are within this
 without affecting other buttons on the page (it wouldn't matter if you didn't have any other input buttons on the page).

The idea here is to use the jQuery selector $('.control-panel input:button'); to get an array of the button nodes, then loop through them one by one and attach an event listener to them.

Note that button is the parameter that the .click(button) function will receive, and it refers to the HTML element node itself - that's why you'll need to use button.target.value to retrieve its value, which would be "Button 1" or "Button 4" depending on which button you click.

Body:
I have 4 beautiful buttons of class .button in css. Is there a simple way (presumably jQuery is the standard method) to put a event listener on these buttons.

Obviously the code will need to record which button was clicked, because only one of them has the right answer. The code below doesn't make that distinction, as button is a class not an ID. I suspect I will have to create four separate button IDs but that will multiply my css code by four.

I have been searching for a jQuery solution for a few days but not able to get any code to suit my particular situation.

This is the first time I have used jQuery, so if I have blundered, please don't be too harsh! I will greatly appreciate any knowledgeable contribution to solve this puzzle.

Here is the code from where the answers get sorted and displayed:

$(document).ready(function() {
  $("input:button").click(function() {
    alert('a button was clicked.')
  });
});

What is this?

  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">

Body:
Here's one way you can do it with a for loop.

javascript file

$(document).ready(function() {
  var $buttons = $('.control-panel input:button');

  for (var i = 0; i < $buttons.length; i++) {
    $($buttons[i]).click((button) => {
      alert(button.target.value);
    });
  }
});

html file

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>What is this?</b></p>
<div class="control-panel">
  <input type="button" class="button" value="Button 1">
  <input type="button" class="button" value="Button 2">
  <input type="button" class="button" value="Button 3">
  <input type="button" class="button" value="Button 4">
</div>

I added a value attribute to your inputs (which you're using as the buttons) to differentiate them.

Also, added a .control-panel class to the parent element so you can target only the buttons that are within this <div> without affecting other buttons on the page (it wouldn't matter if you didn't have any other input buttons on the page).

The idea here is to use the jQuery selector $('.control-panel input:button'); to get an array of the button nodes, then loop through them one by one and attach an event listener to them.

Note that button is the parameter that the .click(button) function will receive, and it refers to the HTML element node itself - that's why you'll need to use button.target.value to retrieve its value, which would be "Button 1" or "Button 4" depending on which button you click.


问:
Serving cached version of the site only
I am working on a local classifieds website and right now every time a page loads the database gets queried.

I have noticed that other popular classifieds websites serve a cached version of their site, which would greatly reduce the load time and server load.

How can I achieve this with Spring Boot or Tomcat? I want the website's cache to update every X minutes.

I am using Thymeleaf as my template engine

答:
First you should add org.springframework.boot:spring-boot-starter-cache to your dependencies in build.gradle or pom.xml.

Let's say you're using DataService to get data to feed your view. You can put @Cacheable annotation on it.

```<code>@Service
class DataService {

    @Cacheable("cache")
    String compute() {
        return "something"
    }

}
</code>```

Then you should add the following configuration:

```<code>@EnableCaching
@Configuration
public class CacheConfiguration {

    public static final String CACHE_NAME = "cache";

    @Bean
    public CacheManager cacheManager() {
          ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(CACHE_NAME);
         return cacheManager;
    }

    @CacheEvict(allEntries = true, value = CACHE_NAME)
    @Scheduled(fixedDelay = 10* 60 * 1000 ,  initialDelay = 500)
    public void evictCache() {}
}
</code>```

Every 10 minutes cache will be cleared.

Title: Serving cached version of the site only

Body:
First you should add org.springframework.boot:spring-boot-starter-cache to your dependencies in build.gradle or pom.xml.

Let's say you're using DataService to get data to feed your view. You can put @Cacheable annotation on it.

@Service
class DataService {

    @Cacheable("cache")
    String compute() {
        return "something"
    }

}

Then you should add the following configuration:

@EnableCaching
@Configuration
public class CacheConfiguration {

    public static final String CACHE_NAME = "cache";

    @Bean
    public CacheManager cacheManager() {
          ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(CACHE_NAME);
         return cacheManager;
    }

    @CacheEvict(allEntries = true, value = CACHE_NAME)
    @Scheduled(fixedDelay = 10* 60 * 1000 ,  initialDelay = 500)
    public void evictCache() {}
}

Every 10 minutes cache will be cleared.

ContentLicense: CC BY-SA 4.0


问:
Can only concatenate tuple (not "int") to tuple
It doesn't move like it should be and it says:

x += x_change
  TypeError: can only concatenate tuple (not "int") to tuple

Code is here:

```<code>import pygame

pygame.init()

display_width = 800
display_height = 600

green = (30,255,50)

gameDisplay = pygame.display.set_mode((display_width,display_height))

pygame.display.set_caption("testV1.0")

clock = pygame.time.Clock()

CharacterImg = pygame.image.load("Character.png")
def Character(x,y):
    gameDisplay.blit(CharacterImg,(x,y))

x = (display_width * 0,45)
y = (display_height * 0,8)

x_change = 0

hit = False

while not hit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            hit = True

            if event.type == pygame.KEYDOWN:
                if pygame.key == K_LEFT:
                    x_change += -50
                if pygame.key == K_RIGHT:
                    x_change += 50

            if event.type == pygame.KEYUP:
                if pygame.key == K_LEFT:
                    x_change += 50
                if pygame.key == K_RIGHT:
                    x_change += -50

            x += x_change

        print(event)

    gameDisplay.fill(green)
    Character(x,y)
    pygame.display.update()
    clock.tick(30)

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

答:
Commas create tuples, therefore both x and y are tuples. Use a dot if you want floating point numbers (you also don't need the parentheses):

```<code>x = display_width * 0.45
y = display_height * 0.8
</code>```

Also, in the event loop you have to replace pygame.key with event.key.

x += x_change should probably be in the while loop not in the event loop.

And you have to dedent this block one time:

```<code>        if event.type == pygame.KEYDOWN:
            if pygame.key == K_LEFT:
                x_change += -50
            if pygame.key == K_RIGHT:
                x_change += 50

        if event.type == pygame.KEYUP:
            if pygame.key == K_LEFT:
                x_change += 50
            if pygame.key == K_RIGHT:
                x_change += -50
</code>```

Body:
It doesn't move like it should be and it says:

x += x_change
  TypeError: can only concatenate tuple (not "int") to tuple

Code is here:

import pygame

pygame.init()

display_width = 800
display_height = 600

green = (30,255,50)

gameDisplay = pygame.display.set_mode((display_width,display_height))

pygame.display.set_caption("testV1.0")

clock = pygame.time.Clock()

CharacterImg = pygame.image.load("Character.png")
def Character(x,y):
    gameDisplay.blit(CharacterImg,(x,y))

x = (display_width * 0,45)
y = (display_height * 0,8)

x_change = 0

hit = False

while not hit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            hit = True

            if event.type == pygame.KEYDOWN:
                if pygame.key == K_LEFT:
                    x_change += -50
                if pygame.key == K_RIGHT:
                    x_change += 50

            if event.type == pygame.KEYUP:
                if pygame.key == K_LEFT:
                    x_change += 50
                if pygame.key == K_RIGHT:
                    x_change += -50

            x += x_change

        print(event)

    gameDisplay.fill(green)
    Character(x,y)
    pygame.display.update()
    clock.tick(30)

pygame.quit()
quit()

Body:
Commas create tuples, therefore both x and y are tuples. Use a dot if you want floating point numbers (you also don't need the parentheses):

x = display_width * 0.45
y = display_height * 0.8

Also, in the event loop you have to replace pygame.key with event.key.

x += x_change should probably be in the while loop not in the event loop.

And you have to dedent this block one time:

        if event.type == pygame.KEYDOWN:
            if pygame.key == K_LEFT:
                x_change += -50
            if pygame.key == K_RIGHT:
                x_change += 50

        if event.type == pygame.KEYUP:
            if pygame.key == K_LEFT:
                x_change += 50
            if pygame.key == K_RIGHT:
                x_change += -50


问:
How to stream a video file for html5 video tag
I was wondering what's the best way to stream a video file (mpg4/avi - or any other format) in Go. Possibly, I'd like to be able to play it using a simple  tag.

I've tried playing the famous Big Buck Bunny file with this code:

```<code>package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func serveHTTP(w http.ResponseWriter, r *http.Request) {
    video, err := os.Open("./bunny.avi")
    if err != nil {
        log.Fatal(err)
    }
    http.ServeContent(w, r, "bunny.avi", time.Now(), video)
    defer video.Close()
}

func main() {
    http.HandleFunc("/", serveHTTP)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}
</code>```

But when loading the html page in my browser nothing plays and only one http request is actually triggered and only one response with 206 Partial content is sent to the page.

The html page contains the following code in the body:

```<code><video width="320" height="240" controls autoplay>
    <source src="http://localhost:8080">
    Your browser does not support the video tag.
</video>
</code>```

Thank you!

答:
I just ran your code and worked in the latest version of Chrome. My video was a MP4 file with H264 video and AAC audio (Both codecs are pretty commonplace and widely supported).

You should convert your video to a supported format for browsers. See this MDN docs to see supported formats and pay attention to "Browser compatibility" part of it.

Body:
I was wondering what's the best way to stream a video file (mpg4/avi - or any other format) in Go. Possibly, I'd like to be able to play it using a simple  tag.

I've tried playing the famous Big Buck Bunny file with this code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func serveHTTP(w http.ResponseWriter, r *http.Request) {
    video, err := os.Open("./bunny.avi")
    if err != nil {
        log.Fatal(err)
    }
    http.ServeContent(w, r, "bunny.avi", time.Now(), video)
    defer video.Close()
}

func main() {
    http.HandleFunc("/", serveHTTP)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}

But when loading the html page in my browser nothing plays and only one http request is actually triggered and only one response with 206 Partial content is sent to the page.

The html page contains the following code in the body:

<video width="320" height="240" controls autoplay>
    <source src="http://localhost:8080">
    Your browser does not support the video tag.
</video>

Thank you!


问:
Quadratic fitting for grouped data in R
although I've found plenty of help regarding fitting models in general, I keep running into a specific issue with my data because of the way it's organized. It's from an intro stats book and is supposed to represent sample data of errors as a function of milligrams of some drug.

```<code>|-----|-------|-------|-------|
| 0mg | 100mg | 200mg | 300mg |
|-----|-------|-------|-------|
| 25  |  16   |   6   |   8   |
| 19  |  15   |  14   |  18   |
| 22  |  19   |   9   |   9   |
| 15  |  11   |   5   |  10   |
| 16  |  14   |   9   |  12   |
| 20  |  23   |  11   |  13   |
</code>```

The data looks like it dips around group C, then goes up a bit for D, hence looking for a quadratic fit.

I've tried the following:

```<code>scores = c(25, 19, 22, 15, 16, 20,
           16, 15, 19, 11, 14, 23,
            6, 14,  9,  5,  9, 11,
            8, 18,  9, 10, 12, 13)

x_groups = rep(c(0,100, 200, 300), each = 6)
scores.quadratic = lm(scores ~ poly(x_groups, 2, raw = TRUE))
</code>```

I can then use the summary() function to view the results. I'm confused about the lm() function and how it's supposed to fit a quadratic function. My understanding is that it will take each index in x_groups and square that, then use a linear fit with that new vector, but that doesn't seem correct to me.

Can someone provide feedback on how this is supposed to fit a quadratic to my data, or if it's not doing that, please help me understand where I'm going wrong.

Thank you.

答:
Let's go through your way of thinking step by step. First, you spot this dip via your numbers for group C. The best way to visualise this is

```<code>library(ggplot2)
library(dplyr)

scores = c(25, 19, 22, 15, 16, 20,
           16, 15, 19, 11, 14, 23,
           6, 14,  9,  5,  9, 11,
           8, 18,  9, 10, 12, 13)

x_groups = rep(c(0,100, 200, 300), each = 6)

# create dataset
d1 = data.frame(scores, x_groups)

# calcuate average scores for each group
d2 = d1 %>% group_by(x_groups) %>% summarise(Avg = mean(scores))

# plot them
ggplot() +
  geom_point(data = d1, aes(x_groups, scores)) +
  geom_line(data = d2, aes(x_groups, Avg), col="blue")
</code>```

Now you can actually see the dip and that's the pattern you want to model.

Then, you want to fit your quadratic model. Keep in mind that quadratic is a specific case of a polynomial formula, but it has order = 2. A polynomial fit with order = n of a variable x will fit intercept + x + x^2 + x^3 + ... + x^n. Therefore, the quadratic will fit intercept + x + x^2 and that's exactly the coefficients you get in your model's output:

```<code>scores.quadratic = lm(scores ~ poly(x_groups, 2, raw = TRUE))
summary(scores.quadratic)

# Call:
#   lm(formula = scores ~ poly(x_groups, 2, raw = TRUE))
#
# Residuals:
#   Min      1Q  Median      3Q     Max
# -6.1250 -2.3333 -0.2083  1.8542  8.7917
#
# Coefficients:
#                                    Estimate Std. Error t value Pr(>|t|)
#   (Intercept)                    20.2083333  1.5925328  12.689 2.58e-11 ***
#   poly(x_groups, 2, raw = TRUE)1 -0.0745833  0.0255747  -2.916  0.00825 **
#   poly(x_groups, 2, raw = TRUE)2  0.0001458  0.0000817   1.785  0.08870 .
# ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 4.002 on 21 degrees of freedom
# Multiple R-squared:  0.4999,  Adjusted R-squared:  0.4523
# F-statistic:  10.5 on 2 and 21 DF,  p-value: 0.0006919
</code>```

The coefficient of the quadratic term is 0.0001458 ,close to zero , but statistically significantly different than zero at a 0.1 level (p value = 0.08870). Therefore, the model kind of feels that there's a dip.

You can plot the fit like this:

```<code># plot the model
ggplot(d1, aes(x_groups, scores)) +
  geom_point() +
  geom_smooth(formula = y ~ poly(x, 2, raw = TRUE),
              method = "lm")
</code>```

You can see this as a smoothed version of the real pattern (1st plot).

Title: Quadratic fitting for grouped data in R

Body:
although I've found plenty of help regarding fitting models in general, I keep running into a specific issue with my data because of the way it's organized. It's from an intro stats book and is supposed to represent sample data of errors as a function of milligrams of some drug.

|-----|-------|-------|-------|
| 0mg | 100mg | 200mg | 300mg |
|-----|-------|-------|-------|
| 25  |  16   |   6   |   8   |
| 19  |  15   |  14   |  18   |
| 22  |  19   |   9   |   9   |
| 15  |  11   |   5   |  10   |
| 16  |  14   |   9   |  12   |
| 20  |  23   |  11   |  13   |

The data looks like it dips around group C, then goes up a bit for D, hence looking for a quadratic fit.

I've tried the following:

scores = c(25, 19, 22, 15, 16, 20,
           16, 15, 19, 11, 14, 23,
            6, 14,  9,  5,  9, 11,
            8, 18,  9, 10, 12, 13)

x_groups = rep(c(0,100, 200, 300), each = 6)
scores.quadratic = lm(scores ~ poly(x_groups, 2, raw = TRUE))

I can then use the summary() function to view the results. I'm confused about the lm() function and how it's supposed to fit a quadratic function. My understanding is that it will take each index in x_groups and square that, then use a linear fit with that new vector, but that doesn't seem correct to me.

Can someone provide feedback on how this is supposed to fit a quadratic to my data, or if it's not doing that, please help me understand where I'm going wrong.

Thank you.

Body:
Let's go through your way of thinking step by step. First, you spot this dip via your numbers for group C. The best way to visualise this is

library(ggplot2)
library(dplyr)

scores = c(25, 19, 22, 15, 16, 20,
           16, 15, 19, 11, 14, 23,
           6, 14,  9,  5,  9, 11,
           8, 18,  9, 10, 12, 13)

x_groups = rep(c(0,100, 200, 300), each = 6)

# create dataset
d1 = data.frame(scores, x_groups)

# calcuate average scores for each group
d2 = d1 %>% group_by(x_groups) %>% summarise(Avg = mean(scores))

# plot them
ggplot() +
  geom_point(data = d1, aes(x_groups, scores)) +
  geom_line(data = d2, aes(x_groups, Avg), col="blue")

Now you can actually see the dip and that's the pattern you want to model.

Then, you want to fit your quadratic model. Keep in mind that quadratic is a specific case of a polynomial formula, but it has order = 2. A polynomial fit with order = n of a variable x will fit intercept + x + x^2 + x^3 + ... + x^n. Therefore, the quadratic will fit intercept + x + x^2 and that's exactly the coefficients you get in your model's output:

scores.quadratic = lm(scores ~ poly(x_groups, 2, raw = TRUE))
summary(scores.quadratic)

# Call:
#   lm(formula = scores ~ poly(x_groups, 2, raw = TRUE))
#
# Residuals:
#   Min      1Q  Median      3Q     Max
# -6.1250 -2.3333 -0.2083  1.8542  8.7917
#
# Coefficients:
#                                    Estimate Std. Error t value Pr(>|t|)
#   (Intercept)                    20.2083333  1.5925328  12.689 2.58e-11 ***
#   poly(x_groups, 2, raw = TRUE)1 -0.0745833  0.0255747  -2.916  0.00825 **
#   poly(x_groups, 2, raw = TRUE)2  0.0001458  0.0000817   1.785  0.08870 .
# ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 4.002 on 21 degrees of freedom
# Multiple R-squared:  0.4999,  Adjusted R-squared:  0.4523
# F-statistic:  10.5 on 2 and 21 DF,  p-value: 0.0006919

The coefficient of the quadratic term is 0.0001458 ,close to zero , but statistically significantly different than zero at a 0.1 level (p value = 0.08870). Therefore, the model kind of feels that there's a dip.

You can plot the fit like this:

# plot the model
ggplot(d1, aes(x_groups, scores)) +
  geom_point() +
  geom_smooth(formula = y ~ poly(x, 2, raw = TRUE),
              method = "lm")

You can see this as a smoothed version of the real pattern (1st plot).


答:
Inside getSize(), you're getting size of pointer, which is 8 bytes (since you're probably running 64-bit OS). In main(), you're getting size of array.

If you want to know array size, pass result of sizeof(S) as additional argument to getSize().

More alternatives would be using some container (like std::vector) or turning function into template function, as Nawaz proposed.

Title: problem with sizeof operator


问:
How to use var.get in JDBC in Jmeter
I have a question about jdbc in jmeter,
I have a value (employee), that I want to check if it exists in a list.
i try to perform a query to DB and to use var.get function, is it possible?
it only worked when I use ${value}. is it possible to use var.get?

in the test I try to perform call and check if employee exists in test_case_string_employee.

```<code>select count (*)
from employee
where CreatedAtDate ='today'
and employee IN ${test_case_string_employee};
</code>```

the code is working. but can I change what is after the "IN"?

I tried

```<code>IN 'vars.get("test_case_string_employee")';
</code>```

and

```<code>IN vars.get("test_case_string_employee");
</code>```

and got exceptions
regards

答:
vars.get only works in scripting elements (jsr223, beanshell).

In other test elements, you need to use:

${}

Title: How to use var.get in JDBC in Jmeter

Body:
I have a question about jdbc in jmeter,
I have a value (employee), that I want to check if it exists in a list.
i try to perform a query to DB and to use var.get function, is it possible?
it only worked when I use ${value}. is it possible to use var.get?

in the test I try to perform call and check if employee exists in test_case_string_employee.

select count (*)
from employee
where CreatedAtDate ='today'
and employee IN ${test_case_string_employee};

the code is working. but can I change what is after the "IN"?

I tried

IN 'vars.get("test_case_string_employee")';

and

IN vars.get("test_case_string_employee");

and got exceptions
regards


问:
Ionic 3 sending http post request as application/x-www-form-urlencoded to Django backend
I'm trying to make a post request to my Django backend with Ionic 3 as the front end app. Right now my post method looks like this:

```<code>register(username, password, email, first_name, last_name) {
    let url = "https://www.example.com/api/create_user/";
    let headers = new Headers();
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"first_name": first_name,
      "last_name": last_name,
      "email": email,
      "username": username,
      "password": password},
      {headers: headers})
      .map(res => res.json());
  }
</code>```

But Django is receiving it like this:
<QueryDict: {'{\n  "first_name": "bob",\n  "last_name": "bob",\n  "email": "bob@bob.bob",\n  "username": "bob",\n  "password": "bob"\n}': ['']}>
And changing the JSON object to a string. I want to properly send form data on my front end so I don't have to do an janky fixes on my Django backend. I tried to add a transformRequest to the header, but this triggers a preflight response because the content-type either gets stripped away or is automatically changed to undefined. How do I change this to properly send the form data so the QueryDict isn't so messed up?

答:
So I realized I'm asking the wrong question. It is much easier to keep the request in the ionic app as application/json and then on the Django side implement a parser for the JSON on the view the post request is being sent to, as shown below:

```<code>from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser

@parser_classes((JSONParser,))
def some_view:
    # View code here
</code>```

Body:
I'm trying to make a post request to my Django backend with Ionic 3 as the front end app. Right now my post method looks like this:

register(username, password, email, first_name, last_name) {
    let url = "https://www.example.com/api/create_user/";
    let headers = new Headers();
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"first_name": first_name,
      "last_name": last_name,
      "email": email,
      "username": username,
      "password": password},
      {headers: headers})
      .map(res => res.json());
  }

But Django is receiving it like this:
<QueryDict: {'{\n  "first_name": "bob",\n  "last_name": "bob",\n  "email": "bob@bob.bob",\n  "username": "bob",\n  "password": "bob"\n}': ['']}>
And changing the JSON object to a string. I want to properly send form data on my front end so I don't have to do an janky fixes on my Django backend. I tried to add a transformRequest to the header, but this triggers a preflight response because the content-type either gets stripped away or is automatically changed to undefined. How do I change this to properly send the form data so the QueryDict isn't so messed up?

Body:
So I realized I'm asking the wrong question. It is much easier to keep the request in the ionic app as application/json and then on the Django side implement a parser for the JSON on the view the post request is being sent to, as shown below:

from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser

@parser_classes((JSONParser,))
def some_view:
    # View code here


问:
Animating a UIImage or UIImageView?
I'm trying to animate an image's height (from height of 0 pixels to 480 pixels) to create the effect of the image being rendered top-down.

With an UIImageView i noticed that it appears correct in the Interface Builder. But when it runs in the simulator the size (width and height) is always set to whatever the size of the image is; meaning, if I set the height of the image view to be 50% the original height, the image is still rendered in full height.

I also tried do this effect with an UIImage. However, although the size of the image appears correct, the image is scaled to reflect the size/aspect-ratio.

Question:
How can i achieve this dynamic sizing (i.e. animation of an image's size) while NOT scaling the image? I thought about using CGImageCreateWithMask, but im pretty sure that would create huge performance hiccups.

* Update *

The effect that im looking for is this:
Animate an image by making it grow in height, from to-down (like a set of blinds being pulled on a window). This image cannot be scaled (as it would lose the visual effect of looking like a "blind"). This image must also be rendered on top of another image. So there are 2 images total.

* ANSWER *

For the top-most imageview, i set the content mode to Top (so it doesnt scale). Then in code, i set the clipsToBounds to True. Now i am able to animate the top-most imageview height thus giving me the effect i am looking for.

答:
Try set your UIImageView's contentMode property to one of the following value. I think what you need is UIViewContentModeScaleAspectFit:

```<code>typedef enum {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
} UIViewContentMode;
</code>```

Title: Animating a UIImage or UIImageView?

Body:
Try set your UIImageView's contentMode property to one of the following value. I think what you need is UIViewContentModeScaleAspectFit:

typedef enum {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
} UIViewContentMode;


问:
Combine two sets conditionally
I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

```<code>public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}
</code>```

Is there a cleaner way of doing this in java8?

答:
You can use a HashMap with name as key, then you avoid the O(n²) runtime complexity of your method. If you need HashSet, then there is no faster way. Even if you use Java 8 Streams. They add just more overhead.

```<code>public Map<String, Person> combine(Set<Person> set1, Set<Person> set2) {
        Map<String, Person> persons = new HashMap<>();
        set1.forEach(pers -> persons.computeIfAbsent(pers.getName(), key -> pers));
        set2.forEach(pers -> persons.computeIfAbsent(pers.getName(), key -> pers));
        return persons;
}
</code>```

Title: Combine two sets conditionally

Body:
I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}

Is there a cleaner way of doing this in java8?

Body:
You can use a HashMap with name as key, then you avoid the O(n²) runtime complexity of your method. If you need HashSet, then there is no faster way. Even if you use Java 8 Streams. They add just more overhead.

public Map<String, Person> combine(Set<Person> set1, Set<Person> set2) {
        Map<String, Person> persons = new HashMap<>();
        set1.forEach(pers -> persons.computeIfAbsent(pers.getName(), key -> pers));
        set2.forEach(pers -> persons.computeIfAbsent(pers.getName(), key -> pers));
        return persons;
}


问:
Not able to send email from elastic beanstalk environment through my gmail email id
I'm using Django as the framework, Running inside docker and docker is running on AWS elastic beanstalk docker platform.So, I'm Trying to send email using my Gmail id it works fine in the local environment(in docker).

BUt the same docker image running on elastic beanstalk docker fails to send emails and it is not even giving me an error or something.It is just not sending emails.

If it is working fine in local environment why is that it not sending an email when running in the cloud?

答:
Without knowing more details, here are a couple of things to check out and remedy if necessary:

Is the Docker container running on an instance in a public subnet? If it's not and it's running in a private subnet, you'll need to setup a NAT instance or gateway and route traffic bound for the internet through that.

Have you got your network security setup correct? Make sure that your Network ACLs and Security Groups will allow the appropriate traffic out to the internet (e.g. 465 or 587 to smtp.gmail.com).

A couple more references that may be helpful:

http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/vpc.html
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.vpc.html


问:
How to add more inputs in a form inside
```

答:
Rather than return true add $("#signup-form").submit();

Further explanation

The current code that you have is doing the following.

$(document).on('click', '.signup-submit', function () {

The above line means when click event occurs on the button with the signup-submit class, then execute the function that is provided as the third argument to the $(document).on method.

When the function is executed it executes the following lines

$("#signup-form").submit( function(eventObj) {
  alert("fwf");
  $('<input />').attr('type', 'hidden')
    .attr('name', "something")
    .attr('value', "something")
    .appendTo('#signup-form');
  return true;
});

These lines are actually defining or attaching a function when the submit event will occur for form with id signup-form.

But they are not actually triggering the submit event.

To trigger the submit event you have write $("#signup-form").submit(); without anything within (). That will trigger the submit event on the form.

You can check further details on this link. Its the official document explaining the usage of submit to attach a handler function or if you want to trigger the submit event for a form then how to do that.

Title: How to add more inputs in a form inside <script> tags

Body:
I have a form inside the script tags and I would love to add more input fields before I submit. My submit button does not work and i think it a pblem with how am accessing the submit button when I try this.

below is my form inside the script tags


问:
Sylius, search products by slug not working
i'm trying to filter products by slug, using:

```<code>$this->get('sylius.repository.product')->findOneBy(array('slug' => $slug));
</code>```

I've tried using findBy and findOneBySlug, but it always says that Product does not have a "slug" property:

```<code>Unrecognized field: slug
</code>```

or

```<code>Entity 'Sylius\Component\Core\Model\Product' has no field 'slug'. You can therefore not call 'findOneBySlug' on the entities' repository
</code>```

but the documentation on their website says it should be working:
http://docs.sylius.org/en/latest/components_and_bundles/bundles/SyliusProductBundle/product.html

```<code>$product = $repository->findOneBy(array('slug' => 'my-super-product')); // Get one product by defined criteria.
</code>```

答:
I think that doesn't work, because the slug is available on the translations of the product. There are some default methods in the repository available that might be helpful to you, e.g.: findOneByChannelAndSlug or findByName.

Alternatively, you can construct it yourself when extending the product repository:

```<code>/**
 * @param string $name
 * @param string $locale
 * @return array
 */
public function findBySlug(string $slug, string $locale): ?ProductInterface
{
    return $this->createQueryBuilder('o')
        ->innerJoin('o.translations', 'translation', 'WITH', 'translation.locale = :locale')
        ->andWhere('translation.slug = :slug')
        ->setParameter('slug', $slug)
        ->setParameter('locale', $locale)
        ->getQuery()
        ->getOneOrNullResult()
    ;
}
</code>```

Body:
i'm trying to filter products by slug, using:

$this->get('sylius.repository.product')->findOneBy(array('slug' => $slug));

I've tried using findBy and findOneBySlug, but it always says that Product does not have a "slug" property:

Unrecognized field: slug

or

Entity 'Sylius\Component\Core\Model\Product' has no field 'slug'. You can therefore not call 'findOneBySlug' on the entities' repository

but the documentation on their website says it should be working:
http://docs.sylius.org/en/latest/components_and_bundles/bundles/SyliusProductBundle/product.html

$product = $repository->findOneBy(array('slug' => 'my-super-product')); // Get one product by defined criteria.

Body:
I think that doesn't work, because the slug is available on the translations of the product. There are some default methods in the repository available that might be helpful to you, e.g.: findOneByChannelAndSlug or findByName.

Alternatively, you can construct it yourself when extending the product repository:

/**
 * @param string $name
 * @param string $locale
 * @return array
 */
public function findBySlug(string $slug, string $locale): ?ProductInterface
{
    return $this->createQueryBuilder('o')
        ->innerJoin('o.translations', 'translation', 'WITH', 'translation.locale = :locale')
        ->andWhere('translation.slug = :slug')
        ->setParameter('slug', $slug)
        ->setParameter('locale', $locale)
        ->getQuery()
        ->getOneOrNullResult()
    ;
}


问:
Nginx rewrite by map with parameters
I would like to rewrite with map as

```<code>/oldpage?f=regist      -> /signup
/oldpage?f=regist&a=1  -> /signup?a=1
/oldpage?f=confirm     -> /signup?t=confirm
/oldpage?f=confirm&a=1 -> /signup?t=confirm&a=1
</code>```

but my redirect result in nginx (v1.12.2) is

```<code>/oldpage?f=regist      -> /signup?f=regist
/oldpage?f=regist&a=1  -> Not Found
/oldpage?f=confirm     -> /signup?t=confirm?f=confirm
/oldpage?f=confirm&a=1 -> Not Found
</code>```

I set nginx.conf as,

```<code>map $request_uri $rewrite_uri {
    include conf.d/redirect.map;
}
server {
    ...
    if ($rewrite_uri) {
        rewrite ^ $rewrite_uri redirect;
    }
}
</code>```

and redirect.map is

```<code>/oldpage?f=regist /signup;
/oldpage?f=confirm /signup?t=confirm;
</code>```

It would be really appreciated if you could give me some advices.

答:
If the a=1 parameter represents any other parameters, and you do not wish to add those combinations to the map file, you should change the syntax of your map file to use regular expressions.

The regular expressions in the map block can create named captures which can be used later in the configuration. In the example below, the $prefix and $suffix variables are named captures from the map block.

The example below has some caveats - because the $prefix and $suffix values may be empty, the generated URIs may contain a trailing ? or & - which should not affect the overall semantics.

All of the regular expressions and the mapped values have a common pattern to capture optional parameters and append them to the resulting value.

```<code>map $request_uri $new {
    default 0;
    ~*^/oldpage\?(?<prefix>.*&)?f=regist(&(?<suffix>.*))?$   /signup?;
    ~*^/oldpage\?(?<prefix>.*&)?f=confirm(&(?<suffix>.*))?$  /signup?t=confirm&;
}

server {
    ...
    if ($new) {
        return 301 $new$prefix$suffix;
    }
</code>```

See this document for more.

Title: Nginx rewrite by map with parameters

Body:
I would like to rewrite with map as

/oldpage?f=regist      -> /signup
/oldpage?f=regist&a=1  -> /signup?a=1
/oldpage?f=confirm     -> /signup?t=confirm
/oldpage?f=confirm&a=1 -> /signup?t=confirm&a=1

but my redirect result in nginx (v1.12.2) is

/oldpage?f=regist      -> /signup?f=regist
/oldpage?f=regist&a=1  -> Not Found
/oldpage?f=confirm     -> /signup?t=confirm?f=confirm
/oldpage?f=confirm&a=1 -> Not Found

I set nginx.conf as,

map $request_uri $rewrite_uri {
    include conf.d/redirect.map;
}
server {
    ...
    if ($rewrite_uri) {
        rewrite ^ $rewrite_uri redirect;
    }
}

and redirect.map is

/oldpage?f=regist /signup;
/oldpage?f=confirm /signup?t=confirm;

It would be really appreciated if you could give me some advices.

Body:
If the a=1 parameter represents any other parameters, and you do not wish to add those combinations to the map file, you should change the syntax of your map file to use regular expressions.

The regular expressions in the map block can create named captures which can be used later in the configuration. In the example below, the $prefix and $suffix variables are named captures from the map block.

The example below has some caveats - because the $prefix and $suffix values may be empty, the generated URIs may contain a trailing ? or & - which should not affect the overall semantics.

All of the regular expressions and the mapped values have a common pattern to capture optional parameters and append them to the resulting value.

map $request_uri $new {
    default 0;
    ~*^/oldpage\?(?<prefix>.*&)?f=regist(&(?<suffix>.*))?$   /signup?;
    ~*^/oldpage\?(?<prefix>.*&)?f=confirm(&(?<suffix>.*))?$  /signup?t=confirm&;
}

server {
    ...
    if ($new) {
        return 301 $new$prefix$suffix;
    }

See this document for more.


问:
Structure tkinter program - Best practices
I dive into tkinter at the moment and many code examples on the internet cover only very simple examples and don't teach best-practices.

For better maintainability and clearness, I'd like to use OOP for a GUI, which makes sense from my point of view.
However, I'd live your advice about how to structure it because I'm a beginner in general.
I've already browsed other questions, but they could not answer my specific general question I have.

My idea here:

Would like to create a menubar for the GUI and create a new file menu.py that only deals with that menu. Here you can find two examples:

1. Example:
Logically, the menubar consists of other menus. So the menu contains menus. But I am not sure if it's good to use nested classes?

```<code>import tkinter as tk

class Menu(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.menubar = Menubar(self)

    class Menubar(tk.Menu):
        def __init__(self, parent, *args, **kwargs):
            super().__init__(parent, *args, **kwargs)
            self.parent = parent

            self.add_cascade(label="File", menu=self.file_menu)
            self.add_cascade(label="Edit", menu=self.edit_menu)

            self.file_menu = FileMenu(self)
            self.edit_menu = EditMenu(self)

        class FileMenu(tk.Menu):
            def __init__(self, parent, *args, **kwargs):
                super().__init__(parent, *args, **kwargs)
                self.parent = parent

        class EditMenu(tk.Menu):
            def __init__(self, parent, *args, **kwargs):
                super().__init__(parent, *args, **kwargs)
                self.parent = parent
</code>```

2. Example: Here you can find a more procedural example. But the weakness here from my point of view is that hierarchical the Menubar as well as the file_menu and the edit_menu are on the same level. But logically the Menubar consists of the file_menu and edit_menu. So, it's not really modular. On the other side, it's perhaps(?) more easy to read than the first example.

```<code>import tkinter as tk

class Menu(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.menubar = tk.Menu(self)

        self.create_file_menu(self.menubar)
        self.create_edit_menu(self.menubar)

    def create_file_menu(self, parent):
        self.file_menu = tk.Menu(parent)
        self.menubar.add_cascade(label="File", menu=self.file_menu)

    def create_edit_menu(self, parent):
        self.edit_menu = tk.Menu(parent)
        self.menubar.add_cascade(label="Edit", menu=self.edit_menu)
</code>```

答:
Nesting a class doesn't reduce nor increase execution efficiency. It may alter maintenance and understanding efficiency. Python's nested classes aren't like Java's where the nested class where the inner class can reference instances of the outer class. They're effectively two separate classes.

Thus your example 1 is better than example 2.

See also:

Is it a bad idea to define a local class inside a function in python?

Is it a good practice to make nested class in python?

What is the purpose of python's inner classes?

Body:
I dive into tkinter at the moment and many code examples on the internet cover only very simple examples and don't teach best-practices.

For better maintainability and clearness, I'd like to use OOP for a GUI, which makes sense from my point of view.
However, I'd live your advice about how to structure it because I'm a beginner in general.
I've already browsed other questions, but they could not answer my specific general question I have.

My idea here:

Would like to create a menubar for the GUI and create a new file menu.py that only deals with that menu. Here you can find two examples:

1. Example:
Logically, the menubar consists of other menus. So the menu contains menus. But I am not sure if it's good to use nested classes?

import tkinter as tk

class Menu(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.menubar = Menubar(self)

    class Menubar(tk.Menu):
        def __init__(self, parent, *args, **kwargs):
            super().__init__(parent, *args, **kwargs)
            self.parent = parent

            self.add_cascade(label="File", menu=self.file_menu)
            self.add_cascade(label="Edit", menu=self.edit_menu)

            self.file_menu = FileMenu(self)
            self.edit_menu = EditMenu(self)

        class FileMenu(tk.Menu):
            def __init__(self, parent, *args, **kwargs):
                super().__init__(parent, *args, **kwargs)
                self.parent = parent

        class EditMenu(tk.Menu):
            def __init__(self, parent, *args, **kwargs):
                super().__init__(parent, *args, **kwargs)
                self.parent = parent

2. Example: Here you can find a more procedural example. But the weakness here from my point of view is that hierarchical the Menubar as well as the file_menu and the edit_menu are on the same level. But logically the Menubar consists of the file_menu and edit_menu. So, it's not really modular. On the other side, it's perhaps(?) more easy to read than the first example.

import tkinter as tk

class Menu(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.menubar = tk.Menu(self)

        self.create_file_menu(self.menubar)
        self.create_edit_menu(self.menubar)

    def create_file_menu(self, parent):
        self.file_menu = tk.Menu(parent)
        self.menubar.add_cascade(label="File", menu=self.file_menu)

    def create_edit_menu(self, parent):
        self.edit_menu = tk.Menu(parent)
        self.menubar.add_cascade(label="Edit", menu=self.edit_menu)


问:
Error while executing and initializing kubeadm
While initializing kubeadm I am getting following errors. I have also tried command kubeadm reset before doing kubadm init. Kubelet is also running and command I have used for same is systemctl enable kubelet && systemctl start kubelet. Following is log after executing kubeadm init

[kubeadm] WARNING: kubeadm is in beta, please do not use it for production clusters.
[init] Using Kubernetes version: v1.8.2
[init] Using Authorization modes: [Node RBAC]
[preflight] Running pre-flight checks
[preflight] WARNING: Connection to "https://192.168.78.48:6443" uses proxy "http://user:pwd@192.168.78.15:3128/". If that is not intended, adjust your proxy settings
[preflight] WARNING: Running with swap on is not supported. Please disable swap or set kubelet's --fail-swap-on flag to false.
[preflight] Starting the kubelet service
[kubeadm] WARNING: starting in 1.8, tokens expire after 24 hours by default (if you require a non-expiring token use --token-ttl 0)
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [steller.india.com kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.140.48]
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated sa key and public key.
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[kubeconfig] Wrote KubeConfig file to disk: "admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "scheduler.conf"
[controlplane] Wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] Wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] Wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] Waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests"
[init] This often takes around a minute; or longer if the control plane images have to be pulled.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.
 ```
</div>
</div>
</p>

<p>Following is output of <code>journalctl -u kubelet</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>-- Logs begin at Thu 2017-11-02 16:20:50 IST, end at Fri 2017-11-03 17:11:12 IST. --
Nov 03 16:36:48 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:36:48 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998467   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998532   52511 controller.go:114] kubelet config controller: starting controller
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998536   52511 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837248   52511 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837282   52511 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.839719   52511 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.846959   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.847216   52511 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:36:49 steller.india.com kubelet[52511]: error: failed to run Kubelet: unable to load bootstrap kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such
Nov 03 16:36:49 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service failed.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service holdoff time over, scheduling restart.
Nov 03 16:37:00 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:37:00 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134702   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134763   52975 controller.go:114] kubelet config controller: starting controller
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134767   52975 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141273   52975 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141364   52975 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.143023   52975 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.149537   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.149780   52975 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.179873   52975 certificate_manager.go:361] Requesting new certificate.
Nov 03 16:37:00 steller.india.com kubelet[52975]: E1103 16:37:00.180392   52975 certificate_manager.go:284] Failed while requesting a signed certificate from the master:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.181404   52975 manager.go:149] cAdvisor running in container: "/sys/fs/cgroup/cpu,cpuacct/system.slice/k
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.223876   52975 manager.go:157] unable to connect to Rkt api service: rkt: cannot tcp Dial rkt api servic
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.224005   52975 manager.go:166] unable to connect to CRI-O api service: Get http://%2Fvar%2Frun%2Fcrio.so
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262573   52975 fs.go:139] Filesystem UUIDs: map[17856e0b-777f-4065-ac97-fb75d7a1e197:/dev/dm-1 2dc6a878-
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262604   52975 fs.go:140] Filesystem partitions: map[/dev/sdb:{mountpoint:/D major:8 minor:16 fsType:xfs
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.268969   52975 manager.go:216] Machine: {NumCores:56 CpuFrequency:2600000 MemoryCapacity:540743667712 Hu
Nov 03 16:37:00 steller.india.com kubelet[52975]: 967295 Mtu:1500} {Name:eno49 MacAddress:14:02:ec:82:57:30 Speed:10000 Mtu:1500} {Name:eno50 MacAddress:14:02:ec:82:57:3
Nov 03 16:37:00 steller.india.com kubelet[52975]: evel:1} {Size:262144 Type:Unified Level:2}]} {Id:13 Threads:[12 40] Caches:[{Size:32768 Type:Data Level:1} {Size:32768
Nov 03 16:37:00 steller.india.com kubelet[52975]: s:[26 54] Caches:[{Size:32768 Type:Data Level:1} {Size:32768 Type:Instruction Level:1} {Size:262144 Type:Unified Level:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.270145   52975 manager.go:222] Version: {KernelVersion:3.10.0-229.14.1.el7.x86_64 ContainerOsVersion:Cen
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.271263   52975 server.go:422] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaultin
Nov 03 16:37:00 steller.india.com kubelet[52975]: error: failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:37:00 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service failed.</code>```

答: just disable the swap in the machine. sudo swapoff -a

Body:
While initializing kubeadm I am getting following errors. I have also tried command kubeadm reset before doing kubadm init. Kubelet is also running and command I have used for same is systemctl enable kubelet && systemctl start kubelet. Following is log after executing kubeadm init

[kubeadm] WARNING: kubeadm is in beta, please do not use it for production clusters.
[init] Using Kubernetes version: v1.8.2
[init] Using Authorization modes: [Node RBAC]
[preflight] Running pre-flight checks
[preflight] WARNING: Connection to "https://192.168.78.48:6443" uses proxy "http://user:pwd@192.168.78.15:3128/". If that is not intended, adjust your proxy settings
[preflight] WARNING: Running with swap on is not supported. Please disable swap or set kubelet's --fail-swap-on flag to false.
[preflight] Starting the kubelet service
[kubeadm] WARNING: starting in 1.8, tokens expire after 24 hours by default (if you require a non-expiring token use --token-ttl 0)
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [steller.india.com kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.140.48]
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated sa key and public key.
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[kubeconfig] Wrote KubeConfig file to disk: "admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "scheduler.conf"
[controlplane] Wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] Wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] Wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] Waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests"
[init] This often takes around a minute; or longer if the control plane images have to be pulled.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.

Following is output of journalctl -u kubelet

-- Logs begin at Thu 2017-11-02 16:20:50 IST, end at Fri 2017-11-03 17:11:12 IST. --
Nov 03 16:36:48 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:36:48 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998467   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998532   52511 controller.go:114] kubelet config controller: starting controller
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998536   52511 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837248   52511 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837282   52511 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.839719   52511 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.846959   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.847216   52511 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:36:49 steller.india.com kubelet[52511]: error: failed to run Kubelet: unable to load bootstrap kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such
Nov 03 16:36:49 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service failed.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service holdoff time over, scheduling restart.
Nov 03 16:37:00 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:37:00 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134702   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134763   52975 controller.go:114] kubelet config controller: starting controller
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134767   52975 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141273   52975 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141364   52975 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.143023   52975 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.149537   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.149780   52975 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.179873   52975 certificate_manager.go:361] Requesting new certificate.
Nov 03 16:37:00 steller.india.com kubelet[52975]: E1103 16:37:00.180392   52975 certificate_manager.go:284] Failed while requesting a signed certificate from the master:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.181404   52975 manager.go:149] cAdvisor running in container: "/sys/fs/cgroup/cpu,cpuacct/system.slice/k
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.223876   52975 manager.go:157] unable to connect to Rkt api service: rkt: cannot tcp Dial rkt api servic
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.224005   52975 manager.go:166] unable to connect to CRI-O api service: Get http://%2Fvar%2Frun%2Fcrio.so
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262573   52975 fs.go:139] Filesystem UUIDs: map[17856e0b-777f-4065-ac97-fb75d7a1e197:/dev/dm-1 2dc6a878-
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262604   52975 fs.go:140] Filesystem partitions: map[/dev/sdb:{mountpoint:/D major:8 minor:16 fsType:xfs
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.268969   52975 manager.go:216] Machine: {NumCores:56 CpuFrequency:2600000 MemoryCapacity:540743667712 Hu
Nov 03 16:37:00 steller.india.com kubelet[52975]: 967295 Mtu:1500} {Name:eno49 MacAddress:14:02:ec:82:57:30 Speed:10000 Mtu:1500} {Name:eno50 MacAddress:14:02:ec:82:57:3
Nov 03 16:37:00 steller.india.com kubelet[52975]: evel:1} {Size:262144 Type:Unified Level:2}]} {Id:13 Threads:[12 40] Caches:[{Size:32768 Type:Data Level:1} {Size:32768
Nov 03 16:37:00 steller.india.com kubelet[52975]: s:[26 54] Caches:[{Size:32768 Type:Data Level:1} {Size:32768 Type:Instruction Level:1} {Size:262144 Type:Unified Level:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.270145   52975 manager.go:222] Version: {KernelVersion:3.10.0-229.14.1.el7.x86_64 ContainerOsVersion:Cen
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.271263   52975 server.go:422] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaultin
Nov 03 16:37:00 steller.india.com kubelet[52975]: error: failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:37:00 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service failed.


问:
Install NumPy for W10
I want to install NumPy for Python 3.4 on W10. I used next process:

```<code>- download numpy-1.13.3+mkl-cp34-cp34m-win_amd64.whl
- installation from folder which constaints *.whl and I used pip install *.whl
- I obtained message: *.whl is not a supported wheel on this platform
</code>```

Where is problem?

答:
To install NumPy on W10:

run cmd as administrator

in that window type: pip install numpy

Title: Install NumPy for W10

Body:
I want to install NumPy for Python 3.4 on W10. I used next process:

- download numpy-1.13.3+mkl-cp34-cp34m-win_amd64.whl
- installation from folder which constaints *.whl and I used pip install *.whl
- I obtained message: *.whl is not a supported wheel on this platform

Where is problem?


问:
Tensorflow indexing into 2d tensor with 1d tensor
I have a 2D tensor A with shape [batch_size, D] , and a 1D tensor B with shape [batch_size].  Each element of B is a column index of A, for each row of A, eg. B[i] in [0,D).

What is the best way in tensorflow to get the values A[B]

For example:

```<code>A = tf.constant([[0,1,2],
                 [3,4,5]])
B = tf.constant([2,1])
</code>```

with desired output:

```<code>some_slice_func(A, B) -> [2,4]
</code>```

There is another constraint.  In practice, batch_size is actually None.

Thanks in advance!

答:
Code for what @Eugene Brevdo said:</p>

```<code>def vector_slice(A, B):
    """ Returns values of rows i of A at column B[i]

    where A is a 2D Tensor with shape [None, D]
    and B is a 1D Tensor with shape [None]
    with type int32 elements in [0,D)

    Example:
      A =[[1,2], B = [0,1], vector_slice(A,B) -> [1,4]
          [3,4]]
    """
    B = tf.expand_dims(B, 1)
    range = tf.expand_dims(tf.range(tf.shape(B)[0]), 1)
    ind = tf.concat([range, B], 1)
    return tf.gather_nd(A, ind)
</code>```

Body:
I have a 2D tensor A with shape [batch_size, D] , and a 1D tensor B with shape [batch_size].  Each element of B is a column index of A, for each row of A, eg. B[i] in [0,D).

What is the best way in tensorflow to get the values A[B]

For example:

A = tf.constant([[0,1,2],
                 [3,4,5]])
B = tf.constant([2,1])

with desired output:

some_slice_func(A, B) -> [2,4]

There is another constraint.  In practice, batch_size is actually None.

Thanks in advance!

Body:
Code for what @Eugene Brevdo said:

def vector_slice(A, B):
    """ Returns values of rows i of A at column B[i]

    where A is a 2D Tensor with shape [None, D]
    and B is a 1D Tensor with shape [None]
    with type int32 elements in [0,D)

    Example:
      A =[[1,2], B = [0,1], vector_slice(A,B) -> [1,4]
          [3,4]]
    """
    B = tf.expand_dims(B, 1)
    range = tf.expand_dims(tf.range(tf.shape(B)[0]), 1)
    ind = tf.concat([range, B], 1)
    return tf.gather_nd(A, ind)