问:
Should I share types between a Web API service and its client ? What are the other options?
We are developing a Web API RESTful service to provide access to common data to all the applications of our enterprise. To help we will also publish a Client API that encapsulate all the HttpClient details and provides a strongly-typed access to the data.

Our goal is to start small and progressively add features, while still keeping backwards compatibility with already deployed versions of the client API (compatibility with the clients of the same Major version)

While talking about the design, our team just had a very long discussion about whether or not we should share types between the server and the client (for instance via versionned NuGet packages that both server and client would depend on), and ended up with pros and cons ...  and we do not manage to decide one way or another.

Sharing types (shared assembly) between client and server

Pros

Client model and Server model are always up to date

no serializing/deserializing problems because same types are serialized/deserialized

no duplication

Cons

need to find a way to share the types between server and client

non semantic modifications can break existing client applications (changing the name of a class or its namespace in the server model) even though it has no impact on the serialized json and should therefore have no impact

risk of breaking the clint without realizing

Separate (but structurally equivalent) types for client and server

Pros

client "model" is less coupled to the server implementation (just a mirror of the Json output by the server, but no hard "same type" relationship)

server model can evolve without risk of breaking any client

enable to enhance the client-side model independently from the server model

the client model is part of the client package, no "shared package" to maintain between server and client

Cons

duplication between server code and client code

error-prone task of keeping server-side and client-side structure in sync

There seems to be a 50/50 preference for each solution in our team.

I personally have a preference for the second option, because I believe RESt is all about decoupling, and decoupling means the client should not care about how the server side is implemented (which types, or whether it is a .NET app anyway) but wish we could get rid of the possible duplication, maybe thanks to code generation or something like that, but could not find any guidance on the subject

Are there other pros and cons to sharing types between client and server ?

If we do not share them, are there ways to lower the maintenance costs when trying to keep client model and server model in sync ?

答:
Domain model classes are primarily defined to be used by the server. On the server side, model types are used by the methods defined inside controllers to access data, for example by using entity framework.

But, for some reasons you may prefer to pass another version of the model object to the client. A known approach is to define DTO classes which are very similar but not exactly the same as model types.

In each method in the controller, when you fetch data from database, you need to map the retrieved data from its model type format to its comparable DTO class. AutoMapper makes this mapping easier.

Therefore you need these steps to be done:

Define your model types inside the server project.

Add these packages to your server project as dependencies:

AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection  (version 1.2.0)

Define a MappingProfile (or MappingConfiguration) inside the server project and use services.AddAutoMapper() in ConfigureServices method in Startup.cs

Modify your controller methods to do proper mapping on the retrieved data and return equivalent DTO as the output of the method.

In parallel, you can make a new project containing your DTO classes. This project is shared between server and client projects.

Then, on the client side you do not need to know any details of model types. Your client only works with DTO classes. These classes contain all the necessary data on the client side. In some cases you may need to combine data of multiple model objects to provide a single container for client side.


来源: stackexchange

问:
How to partition and typecast a List in Kotlin
In Kotlin I can:

```<code>val (specificMembers, regularMembers) = members.partition {it is SpecificMember}
</code>```

However to my knowledge I can not do something like:

```<code>val (specificMembers as List<SpecificMember>, regularMembers) = members.partition {it is SpecificMember}
</code>```

My question would be - is there's an idiomatic way to partition iterable by class and typecast it those partitioned parts if needed.

答:
If you require that functionality more often, you may just reimplement the actual partition according to your needs, e.g.:

```<code>inline fun <reified U : T, T> Iterable<T>.partitionByType(): Pair<List<U>, List<T>> {
  val first = ArrayList<U>()
  val second = ArrayList<T>()
  for (element in this) {
    if (element is U) first.add(element)
    else second.add(element)
  }
  return Pair(first, second)
}
</code>```

with a usage similar as to follows:

```<code>val (specificMembers, regularMembers) = members.partitionByType<SpecificMember, Member>()
// where specificMembers : List<SpecificMember>
// and regularMembers : List<Member> for this example
</code>```

Note that this way you can also set the second type to a more generic one. I leave that up to you whether this makes sense. At least this way an unchecked cast isn't necessary.

The alternative is also shown by Simon with the let-usage. You can also directly cast the result of partition (without let and another Pair) to whatever fits, e.g.:

```<code>val (specificMembers, regularMembers) = members.partition {it is SpecificMember} as Pair<List<SpecificMember>, List<Member>>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Kotlin I can:

val (specificMembers, regularMembers) = members.partition {it is SpecificMember}

However to my knowledge I can not do something like:

val (specificMembers as List<SpecificMember>, regularMembers) = members.partition {it is SpecificMember}

My question would be - is there's an idiomatic way to partition iterable by class and typecast it those partitioned parts if needed.

Body:
If you require that functionality more often, you may just reimplement the actual partition according to your needs, e.g.:

inline fun <reified U : T, T> Iterable<T>.partitionByType(): Pair<List<U>, List<T>> {
  val first = ArrayList<U>()
  val second = ArrayList<T>()
  for (element in this) {
    if (element is U) first.add(element)
    else second.add(element)
  }
  return Pair(first, second)
}

with a usage similar as to follows:

val (specificMembers, regularMembers) = members.partitionByType<SpecificMember, Member>()
// where specificMembers : List<SpecificMember>
// and regularMembers : List<Member> for this example

Note that this way you can also set the second type to a more generic one. I leave that up to you whether this makes sense. At least this way an unchecked cast isn't necessary.

The alternative is also shown by Simon with the let-usage. You can also directly cast the result of partition (without let and another Pair) to whatever fits, e.g.:

val (specificMembers, regularMembers) = members.partition {it is SpecificMember} as Pair<List<SpecificMember>, List<Member>>


问:
Asp.net FluentValidation unit testing object as null
I'm doing some unit testing using FluentValidation in Asp.net. I have setup a rule stating that an object is not allowed to be null, as it's going to be used as an argument in a method. The rule is made in a validator-class in the constructor:

```<code> //Object itself.
 RuleFor(x => x).NotNull();
</code>```

The unit test looks like (I'm using NUnit):

```<code>[Test]
public void RequestObjectIsNull_ExpectError()
{
    BusinessRequest request = null;
    var result = validator.Validate(request);

    Assert.IsFalse(result.IsValid);
}
</code>```

It fails with the message:

Message: System.ArgumentNullException : Cannot pass null model to Validate.
  Parameter name: instanceToValidate

How do I test this?

答:
This question is quite old but I have stumbled upon the same issue. I wanted the fluent validator to validate it for me if it is null and say so and not throw an exception, instead of me explicitly checking for it. I have found a solution of overriding the existing methods, For example:</p>

```<code> public class MyValidator : AbstractValidator<MyObject>
    {
        public MyValidator()
        {
            RuleSet("MyRule", () =>
            {
                RuleFor(x=>x.MyProperty=="Something").WithMessage("failed");
            });
        }

        public override Task<ValidationResult> ValidateAsync(ValidationContext<MyObjec>> context, CancellationToken cancellation = default)
        {
            return context.InstanceToValidate == null ? Task.FromResult(new ValidationResult(new[] { new ValidationFailure("MyObject", "filed with null") })) : base.ValidateAsync(context, cancellation);
        }
    }
</code>```

Body:
I'm doing some unit testing using FluentValidation in Asp.net. I have setup a rule stating that an object is not allowed to be null, as it's going to be used as an argument in a method. The rule is made in a validator-class in the constructor:

 //Object itself.
 RuleFor(x => x).NotNull();

The unit test looks like (I'm using NUnit):

[Test]
public void RequestObjectIsNull_ExpectError()
{
    BusinessRequest request = null;
    var result = validator.Validate(request);

    Assert.IsFalse(result.IsValid);
}

It fails with the message:

Message: System.ArgumentNullException : Cannot pass null model to Validate.
  Parameter name: instanceToValidate

How do I test this?

Body:
This question is quite old but I have stumbled upon the same issue. I wanted the fluent validator to validate it for me if it is null and say so and not throw an exception, instead of me explicitly checking for it. I have found a solution of overriding the existing methods, For example:

 public class MyValidator : AbstractValidator<MyObject>
    {
        public MyValidator()
        {
            RuleSet("MyRule", () =>
            {
                RuleFor(x=>x.MyProperty=="Something").WithMessage("failed");
            });
        }

        public override Task<ValidationResult> ValidateAsync(ValidationContext<MyObjec>> context, CancellationToken cancellation = default)
        {
            return context.InstanceToValidate == null ? Task.FromResult(new ValidationResult(new[] { new ValidationFailure("MyObject", "filed with null") })) : base.ValidateAsync(context, cancellation);
        }
    }


问:
Checking last element of a string in a list
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff:
So my file looks like this:

YYYY-MM-DD HH:MM:SS.ffffff:

few lines of bytes

YYYY-MM-DD HH:MM:SS.ffffff:

and so on...

I want to extract dates from my file so I could calculate times between messages

I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. I have read my file and saved it in variable which is a list of strings, and each element is a line. Now I want to create a second list of only dates, extracting only those lines that end with colons.

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    if lines[i].endswith(":"):
        dates.append(lines[i])
    i+=1
print (dates)
```

I checked that lines is created correctly, however there are no elements appended to the list dates. It remains empty. Is there something wrong with my ifcondition? Or is there another way of checking last character of a string if it is a list element?

答:
A better way to find the Timestamp in line</p>

```<code>f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    # Check if line is a timestamp.
    if time.strptime(line[:19], '%Y-%m-%d %H:%M:%S'):
        dates.append(lines[i])
    i+=1
print (dates)
</code>```

Body:
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff:
So my file looks like this:

YYYY-MM-DD HH:MM:SS.ffffff:

few lines of bytes

YYYY-MM-DD HH:MM:SS.ffffff:

and so on...

I want to extract dates from my file so I could calculate times between messages

I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. I have read my file and saved it in variable which is a list of strings, and each element is a line. Now I want to create a second list of only dates, extracting only those lines that end with colons.

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    if lines[i].endswith(":"):
        dates.append(lines[i])
    i+=1
print (dates)

I checked that lines is created correctly, however there are no elements appended to the list dates. It remains empty. Is there something wrong with my ifcondition? Or is there another way of checking last character of a string if it is a list element?

Body:
A better way to find the Timestamp in line

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    # Check if line is a timestamp.
    if time.strptime(line[:19], '%Y-%m-%d %H:%M:%S'):
        dates.append(lines[i])
    i+=1
print (dates)


问:
How to Schedule a firebase functions?
The function as created using either the HTTPS or the PubSub trigger won't run using the firebase scheduler.

```<code>exports.helloworld = functions.https.schedule('every 5 minutes').onRequest((req, res) =>{

   res.send("Hello World Ozone Here");
</code>```

functions.https.schedule is not a function

答:
See https://firebase.google.com/docs/functions/schedule-functions .

```<code>export scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
  console.log('This will be run every 5 minutes!');
});
</code>```

```<code>
</code>```

Title: How to Schedule a firebase functions?

Body:
The function as created using either the HTTPS or the PubSub trigger won't run using the firebase scheduler.

exports.helloworld = functions.https.schedule('every 5 minutes').onRequest((req, res) =>{

   res.send("Hello World Ozone Here");

functions.https.schedule is not a function

Body:
See https://firebase.google.com/docs/functions/schedule-functions .

export scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
  console.log('This will be run every 5 minutes!');
});


问:
What is going on when I set app.wsgi_app = ProxyFix(app.wsgi_app) when running a Flask app on gunicorn?
I built a basic web app using Flask, and was able to run it from a virtual machine using its native http server. I quickly realized that with this set up, requests are blocking (I couldn't make concurrent requests for resources; any new request would wait until earlier requests had finished), and decided to try gunicorn to run the app to solve this problem. I followed the documentation, specifically running with this line:

```<code>gunicorn -w 4 -b 127.0.0.1:4000 myproject:app
</code>```

However, it failed to boot doing just this, and complained that there was no WSGI app. Poking around the internet, I found that a number of people had posted examples including the following:

```<code>from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
</code>```

I added that, and it resolved my problem. I am confused though because this is apparently meant to solve a problem serving behind an HTTP proxy, but would the addition of gunicorn impose an HTTP proxy? Or was I always behind a proxy, and it just didn't matter for Flask's built-in server?

Also, Werkzeug's documentation on Fixers warns "Do not use this middleware in non-proxy setups for security reasons." Considering the fix was clearly necessary, can I assume I'm on a proxy setup?

答:
A little late to the party, but here is what the documentation says about ProxyFix.

To paraphrase: Deploying your server using gunicorn behind an HTTP proxy you will need to rewrite some of the headers so that the application can work.
And Werkzeug ships with a fixer that will solve some of the common setups.

ContentLicense: CC BY-SA 3.0

Body:
I built a basic web app using Flask, and was able to run it from a virtual machine using its native http server. I quickly realized that with this set up, requests are blocking (I couldn't make concurrent requests for resources; any new request would wait until earlier requests had finished), and decided to try gunicorn to run the app to solve this problem. I followed the documentation, specifically running with this line:

gunicorn -w 4 -b 127.0.0.1:4000 myproject:app

However, it failed to boot doing just this, and complained that there was no WSGI app. Poking around the internet, I found that a number of people had posted examples including the following:

from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)

I added that, and it resolved my problem. I am confused though because this is apparently meant to solve a problem serving behind an HTTP proxy, but would the addition of gunicorn impose an HTTP proxy? Or was I always behind a proxy, and it just didn't matter for Flask's built-in server?

Also, Werkzeug's documentation on Fixers warns "Do not use this middleware in non-proxy setups for security reasons." Considering the fix was clearly necessary, can I assume I'm on a proxy setup?


问:
How to bind array to arrystore in order to populate combo in extjs
I am having array as

```<code>var cars = new Array('audi','benz','citron','nissan','alto');
</code>```

I want to add this data to arraystore like below

```<code> var myStore = new Ext.data.ArrayStore({
        data   : cars ,
        fields : ['names']
    });
</code>```

On Binding this array store to combo

```<code> var myCombo = new Ext.form.ComboBox({
        store: myStore ,
        displayField: 'name',
        valueField: 'name',
        typeAhead: true,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a state...',
        selectOnFocus: true,

    });
</code>```

The combo is showing only first letter of each word in the array as a, b, c, n, a

How can I properly disply the combo as the arry i am using is is populated programatically and then binding to arraystore

答:
Alternatively, if you just pass the array as the store config, that will also work (assuming a recent version):

```<code>new Ext.form.ComboBox({
    store: ['Audi', 'Benz', 'Citron', 'Nissan', 'Alto']
});
</code>```

Note you don't need to specify displayField/valueField if this is the case.

Body:
I am having array as

var cars = new Array('audi','benz','citron','nissan','alto');

I want to add this data to arraystore like below

 var myStore = new Ext.data.ArrayStore({
        data   : cars ,
        fields : ['names']
    });

On Binding this array store to combo

 var myCombo = new Ext.form.ComboBox({
        store: myStore ,
        displayField: 'name',
        valueField: 'name',
        typeAhead: true,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        emptyText: 'Select a state...',
        selectOnFocus: true,

    });

The combo is showing only first letter of each word in the array as a, b, c, n, a

How can I properly disply the combo as the arry i am using is is populated programatically and then binding to arraystore

Body:
Alternatively, if you just pass the array as the store config, that will also work (assuming a recent version):

new Ext.form.ComboBox({
    store: ['Audi', 'Benz', 'Citron', 'Nissan', 'Alto']
});

Note you don't need to specify displayField/valueField if this is the case.


问:
Review of this linked list program
This is a program on the linked list which prints the given input. But is it possible to do it Without using the if(start==NULL) ...else .. statement?

```<code>#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;

    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}
</code>```

答:
Well, a lot of things are not necessary.

You can simply define a node as

```<code>struct node
{
    int data;
    node * next; // Will hold the value of next node's address
};
</code>```

Now you can simply make a Class of the data structure with methods.

```<code>class LinkedList {
  private:
    node *head, *current, *temp; // 3 Main pointers
  public:

    LinkedList() {
      head = temp = current = NULL; // Set them to NULL
    }

    void insert(int data) { // to add a new node
      if(head == NULL) { // if there is no node in the memory
        head = new node; // use head to make a new node
        head->data = data; // set the data of the node to data
        head->next = NULL; // set the next to NULL
        temp = current = head; // 3 pointers sitting at the head node
      }
      else { // If the node is not the first one in the memory
        current = new node; // use current pointer to make new node
        temp->next = current; // temp pointer one step behind the current node
        current->next = NULL; // make the next of new node NULL
        temp = current; // move the pointer to current
        current->data = data;
      }
    }
};
</code>```

This function will simply add nodes on every call.

To display the list,
Simply move the temp pointer to head and start the iteration

```<code>void display()
{
    temp = head; // move to head
    while(temp != NULL) // while temp doesn't reach the end
    {
        cout<<temp->data<< " "; // print the node's data
        temp = temp->next; // move the pointer to next node
    }
}
</code>```

Title: Review of this linked list program

Body:
This is a program on the linked list which prints the given input. But is it possible to do it Without using the if(start==NULL) ...else .. statement?

#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;

    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}

Body:
Well, a lot of things are not necessary.

You can simply define a node as

struct node
{
    int data;
    node * next; // Will hold the value of next node's address
};

Now you can simply make a Class of the data structure with methods.

class LinkedList {
  private:
    node *head, *current, *temp; // 3 Main pointers
  public:

    LinkedList() {
      head = temp = current = NULL; // Set them to NULL
    }

    void insert(int data) { // to add a new node
      if(head == NULL) { // if there is no node in the memory
        head = new node; // use head to make a new node
        head->data = data; // set the data of the node to data
        head->next = NULL; // set the next to NULL
        temp = current = head; // 3 pointers sitting at the head node
      }
      else { // If the node is not the first one in the memory
        current = new node; // use current pointer to make new node
        temp->next = current; // temp pointer one step behind the current node
        current->next = NULL; // make the next of new node NULL
        temp = current; // move the pointer to current
        current->data = data;
      }
    }
};

This function will simply add nodes on every call.

To display the list,
Simply move the temp pointer to head and start the iteration

void display()
{
    temp = head; // move to head
    while(temp != NULL) // while temp doesn't reach the end
    {
        cout<<temp->data<< " "; // print the node's data
        temp = temp->next; // move the pointer to next node
    }
}


问:
"Size or zero" of value of multivalued hashmap
I have a multivalued Hashmap (technically a LinkedHashMap):

```<code>private LinkedHashMap<String, ArrayList<BodyPart>> bodyParts  = new LinkedHashMap<>();
</code>```

I want to find the number of values associated with a given key.  However, bodyParts.get("sample key") returns null if the key isn't present, whereas I want it to return 0 (as there are zero values associated with that key).

I could shield it in an if statement:

```<code>int numberOfValues;
if(bodyParts.containsKey("sample"){
    numberOfValues = bodyParts.get("sample").size();
}
</code>```

but I was wondering if there is an easier/better way to do it?  I've read the documentation for computeIfPresent but, truthfully, didn't really understand it.

答:
You can use getOrDefault method of Java Map interface.

It allows you to set default value that is to be returned in case value corresponding to key is not found. So in use case mentioned above you can use :
 numberOfValues = bodyParts.getOrDefault("sample", new ArrayList<BodyPart>()).size();

Body:
I have a multivalued Hashmap (technically a LinkedHashMap):

private LinkedHashMap<String, ArrayList<BodyPart>> bodyParts  = new LinkedHashMap<>();

I want to find the number of values associated with a given key.  However, bodyParts.get("sample key") returns null if the key isn't present, whereas I want it to return 0 (as there are zero values associated with that key).

I could shield it in an if statement:

int numberOfValues;
if(bodyParts.containsKey("sample"){
    numberOfValues = bodyParts.get("sample").size();
}

but I was wondering if there is an easier/better way to do it?  I've read the documentation for computeIfPresent but, truthfully, didn't really understand it.


问:
Filter role based users in c# linq
we have multiple roles in our system and a user can have multiple roles assigned to it
and everything is managed custom. We are not using identity or so.

I am sending my api request with some roles like "guest", "admin".
Api should only returns users having these roles

this is how I am filtering users
List<string> roles -> this is a variable that have role names
coming from front-end suppose "admin"

roles = "admin" -> but can have more roles

UserRoleMappings is navigation property that holds user id and
role id combination to save roles of particular user

now while getting all users, I would like to filter them so that

```<code>query.Where(user => user.UserRoleMappings.Any(urm => roles.Contains(urm.UserRole.Name)));
</code>```

This query is fetching users having roles "admin" + "guests" as I have
applied contains. But i need users which only have "admin" role

beacuse

```<code>user

1  user1
2 user2

role
1 admin
2 guest

userMapping
1 1
1 2
2 1
</code>```

Api should only return user2 but it is also returning user1. This methid should be generic and should work formultiple roles

Thanks & Regards

答:
you have to use select and Where,
query.Select(user => user.UserRoleMappings.where(urm => roles.Contains(urm.UserRole.Name))).toList();

now your where clause will return only Matched Element

Title: Filter role based users in c# linq

Body:
we have multiple roles in our system and a user can have multiple roles assigned to it
and everything is managed custom. We are not using identity or so.

I am sending my api request with some roles like "guest", "admin".
Api should only returns users having these roles

this is how I am filtering users
List<string> roles -> this is a variable that have role names
coming from front-end suppose "admin"

roles = "admin" -> but can have more roles

UserRoleMappings is navigation property that holds user id and
role id combination to save roles of particular user

now while getting all users, I would like to filter them so that

query.Where(user => user.UserRoleMappings.Any(urm => roles.Contains(urm.UserRole.Name)));

This query is fetching users having roles "admin" + "guests" as I have
applied contains. But i need users which only have "admin" role

beacuse

user

1  user1
2 user2

role
1 admin
2 guest

userMapping
1 1
1 2
2 1

Api should only return user2 but it is also returning user1. This methid should be generic and should work formultiple roles

Thanks & Regards


问:
how can i forecast next value using lstm?
here is my code

```<code>def create_dataset(data, look_back=1):
    dataX, dataY = [], []
    for i in range(len(data) - look_back):
        dataX.append(data[i:(i + look_back), 0])
        dataY.append(data[i + look_back, 0])
    return np.array(dataX), np.array(dataY)

look_back = 10

df = pd.read_csv('kospi.csv')
data = df.Close.values.astype('float32')
data = data.reshape(len(df), 1)

scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)

train_size = int(len(data) * 0.80)
test_size = len(data) - train_size

train = data[0:train_size]
test = data[train_size:len(data)]
x_train, y_train = create_dataset(train, look_back)
x_test, y_test = create_dataset(test, look_back)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

model = Sequential()
model.add(LSTM(512, input_shape=(None, 1), return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512, input_shape=(None, 1)))
model.add(Dropout(0.3))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='rmsprop', metrics=['accuracy'])
model.summary()
hist = model.fit(x_train, y_train, epochs=10, batch_size=16, verbose=2)
p = model.predict(x_test)

plt.plot(y_test)
plt.plot(p)
plt.legend(['testY', 'p'], loc='upper right')
plt.title(mean_squared_error(y_test, p))
# plt.savefig(datetime.datetime.now())
# plt.savefig(name)
plt.show()
</code>```

this model predcit(x_test) is good working

and now I want to predict the next 100 values

I tried p = model.predict(x_test[-1])

but it looks like not proper method

how can I get predicted next N values?

I think we can solve it using model.predict.

But I do not know what input and how to make a prediction.

I tried a lot but I could not solve it. How can I solve this problem?

kospi.csv link is https://docs.google.com/spreadsheets/d/1Q6Lh07Yg-OGtuz_Rvy979gcA65jrEqVNJNjndklCbg4/edit?usp=sharing

答:
you can able to predict value by using lstm.
REplace to this code:</p>

```<code>from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential

def build_improved_model(input_dim, output_dim, return_sequences):
    """
    Builds an improved Long Short term memory model using keras.layers.recurrent.lstm
    :param input_dim: input dimension of model
    :param output_dim: ouput dimension of model
    :param return_sequences: return sequence for the model
    :return: a 3 layered LSTM model
    """
    model = Sequential()
    model.add(LSTM(
        input_shape=(None, input_dim),
        units=output_dim,
        return_sequences=return_sequences))

    model.add(Dropout(0.2))

    model.add(LSTM(
        128,
        return_sequences=False))

    model.add(Dropout(0.2))

    model.add(Dense(
        units=1))
    model.add(Activation('linear'))

    return model

def build_basic_model(input_dim, output_dim, return_sequences):
    """
    Builds a basic lstm model
    :param input_dim: input dimension of the model
    :param output_dim: output dimension of the model
    :param return_sequences: return sequence of the model
    :return: a basic lstm model with 3 layers.
    """
    model = Sequential()
    model.add(LSTM(
        input_shape=(None, input_dim),
        units=output_dim,
        return_sequences=return_sequences))

    model.add(LSTM(
        100,
        return_sequences=False))

    model.add(Dense(
        units=1))
    model.add(Activation('linear'))

    return model
</code>```

Body:
here is my code

def create_dataset(data, look_back=1):
    dataX, dataY = [], []
    for i in range(len(data) - look_back):
        dataX.append(data[i:(i + look_back), 0])
        dataY.append(data[i + look_back, 0])
    return np.array(dataX), np.array(dataY)

look_back = 10

df = pd.read_csv('kospi.csv')
data = df.Close.values.astype('float32')
data = data.reshape(len(df), 1)

scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)

train_size = int(len(data) * 0.80)
test_size = len(data) - train_size

train = data[0:train_size]
test = data[train_size:len(data)]
x_train, y_train = create_dataset(train, look_back)
x_test, y_test = create_dataset(test, look_back)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

model = Sequential()
model.add(LSTM(512, input_shape=(None, 1), return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512, input_shape=(None, 1)))
model.add(Dropout(0.3))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='rmsprop', metrics=['accuracy'])
model.summary()
hist = model.fit(x_train, y_train, epochs=10, batch_size=16, verbose=2)
p = model.predict(x_test)

plt.plot(y_test)
plt.plot(p)
plt.legend(['testY', 'p'], loc='upper right')
plt.title(mean_squared_error(y_test, p))
# plt.savefig(datetime.datetime.now())
# plt.savefig(name)
plt.show()

this model predcit(x_test) is good working

and now I want to predict the next 100 values

I tried p = model.predict(x_test[-1])

but it looks like not proper method

how can I get predicted next N values?

I think we can solve it using model.predict.

But I do not know what input and how to make a prediction.

I tried a lot but I could not solve it. How can I solve this problem?

kospi.csv link is https://docs.google.com/spreadsheets/d/1Q6Lh07Yg-OGtuz_Rvy979gcA65jrEqVNJNjndklCbg4/edit?usp=sharing

Body:
you can able to predict value by using lstm.
REplace to this code:

from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential

def build_improved_model(input_dim, output_dim, return_sequences):
    """
    Builds an improved Long Short term memory model using keras.layers.recurrent.lstm
    :param input_dim: input dimension of model
    :param output_dim: ouput dimension of model
    :param return_sequences: return sequence for the model
    :return: a 3 layered LSTM model
    """
    model = Sequential()
    model.add(LSTM(
        input_shape=(None, input_dim),
        units=output_dim,
        return_sequences=return_sequences))

    model.add(Dropout(0.2))

    model.add(LSTM(
        128,
        return_sequences=False))

    model.add(Dropout(0.2))

    model.add(Dense(
        units=1))
    model.add(Activation('linear'))

    return model

def build_basic_model(input_dim, output_dim, return_sequences):
    """
    Builds a basic lstm model
    :param input_dim: input dimension of the model
    :param output_dim: output dimension of the model
    :param return_sequences: return sequence of the model
    :return: a basic lstm model with 3 layers.
    """
    model = Sequential()
    model.add(LSTM(
        input_shape=(None, input_dim),
        units=output_dim,
        return_sequences=return_sequences))

    model.add(LSTM(
        100,
        return_sequences=False))

    model.add(Dense(
        units=1))
    model.add(Activation('linear'))

    return model


问:
Python split by multiple separators, including space?
Input:

```<code>Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.
</code>```

Code:

```<code>import re

input_words = list(re.split('\s+', input()))
print(input_words)
</code>```

Works perfect and returns me:

```<code>['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.']
</code>```

But when add some other separators, like this:

```<code>import re

input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input()))
print(input_words)
</code>```

It doesn't split by spaces anymore, where am I wrong?

Expected outpus would be:

```<code>['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc']
</code>```

答:
write the expression inside brackets as shown below. Hope it helps</p>

```<code>import re

input_words = list(re.split('[\s+,:.!()]', input()))
</code>```

Body:
Input:

Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.

Code:

import re

input_words = list(re.split('\s+', input()))
print(input_words)

Works perfect and returns me:

['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.']

But when add some other separators, like this:

import re

input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input()))
print(input_words)

It doesn't split by spaces anymore, where am I wrong?

Expected outpus would be:

['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc']

Body:
write the expression inside brackets as shown below. Hope it helps

import re

input_words = list(re.split('[\s+,:.!()]', input()))


问:
c++ macro to import all names of base template class
When deriving a class from a template base class, one is forced to use the syntax this->member, or using Base::member to get access to a member of the base class. The same would happen if the base class is a generic template parameter and one is sure that some members exists.

Would it be possible to write a macro that "import" all members of the base class that I know (or assume) to be existent?

Simple example:

```<code>struct A {
   int x = 0;
};

struct B {
  int x = 0;
  int y = 1;
};

template <class T>
struct C {
   int x = 0;
   T z = 0;
};

template <class BaseClass>
struct Derived : BaseClass {
  using BaseClass::x;
  void setx1() { x = 1; }
};

template <class T>
struct Derived_from_C : C<T> {
  using C<T>::x;
  void setx1() { x = 1; }
};

int main()
{
    Derived<A> a;
    a.setx1();

    Derived<B> b;
    b.setx1();

    Derived_from_C<double> c;
    c.setx1();

    return 0;
}
</code>```

In defining struct Derived I assume that the template parameter BaseClass contains a member x, but to use it in the member setx1 I have to manually declare a using. The same happens for Derived_from _C where the base class is a template class. But if the base class contains many members that I would like to use, it becomes tedious and error-prone to add a using for each member.

It it possible to write a macro that does this semi-automatically? Something like

```<code>#define USING(class, __VA_ARGS__)
</code>```

such that

```<code>USING(BaseClass, x, y, z)
</code>```

expands to

```<code>using BaseClass::x;
using BaseClass::y;
using BaseClass::z;
</code>```

答:
Based on Marvin's solution to the question Is it possible to iterate over arguments in variadic macros here is a solution</p>

```<code>#define FE_1(CLASS, X) using CLASS::X
#define FE_2(CLASS, X, ...) using CLASS::X;FE_1(CLASS, __VA_ARGS__)
#define FE_3(CLASS, X, ...) using CLASS::X;FE_2(CLASS, __VA_ARGS__)
#define FE_4(CLASS, X, ...) using CLASS::X;FE_3(CLASS, __VA_ARGS__)
#define FE_5(CLASS, X, ...) using CLASS::X;FE_4(CLASS, __VA_ARGS__)
#define FE_6(CLASS, X, ...) using CLASS::X;FE_5(CLASS, __VA_ARGS__)
#define FE_7(CLASS, X, ...) using CLASS::X;FE_6(CLASS, __VA_ARGS__)
#define FE_8(CLASS, X, ...) using CLASS::X;FE_7(CLASS, __VA_ARGS__)
#define FE_9(CLASS, X, ...) using CLASS::X;FE_8(CLASS, __VA_ARGS__)
#define FE_10(CLASS, X, ...) using CLASS::X;FE_9(CLASS, __VA_ARGS__)
#define FE_11(CLASS, X, ...) using CLASS::X;FE_10(CLASS, __VA_ARGS__)
#define FE_12(CLASS, X, ...) using CLASS::X;FE_11(CLASS, __VA_ARGS__)
//... repeat as needed

#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,NAME,...) NAME
#define FOR_EACH_USING(class,...) \
  GET_MACRO(__VA_ARGS__,FE_12,FE_11,FE_10,FE_9,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1,)(class,__VA_ARGS__)
</code>```

Body:
When deriving a class from a template base class, one is forced to use the syntax this->member, or using Base::member to get access to a member of the base class. The same would happen if the base class is a generic template parameter and one is sure that some members exists.

Would it be possible to write a macro that "import" all members of the base class that I know (or assume) to be existent?

Simple example:

struct A {
   int x = 0;
};

struct B {
  int x = 0;
  int y = 1;
};

template <class T>
struct C {
   int x = 0;
   T z = 0;
};

template <class BaseClass>
struct Derived : BaseClass {
  using BaseClass::x;
  void setx1() { x = 1; }
};

template <class T>
struct Derived_from_C : C<T> {
  using C<T>::x;
  void setx1() { x = 1; }
};

int main()
{
    Derived a;
    a.setx1();

    Derived b;
    b.setx1();

    Derived_from_C<double> c;
    c.setx1();

    return 0;
}

In defining struct Derived I assume that the template parameter BaseClass contains a member x, but to use it in the member setx1 I have to manually declare a using. The same happens for Derived_from _C where the base class is a template class. But if the base class contains many members that I would like to use, it becomes tedious and error-prone to add a using for each member.

It it possible to write a macro that does this semi-automatically? Something like

#define USING(class, __VA_ARGS__)

such that

USING(BaseClass, x, y, z)

expands to

using BaseClass::x;
using BaseClass::y;
using BaseClass::z;

Body:
Based on Marvin's solution to the question Is it possible to iterate over arguments in variadic macros here is a solution

#define FE_1(CLASS, X) using CLASS::X
#define FE_2(CLASS, X, ...) using CLASS::X;FE_1(CLASS, __VA_ARGS__)
#define FE_3(CLASS, X, ...) using CLASS::X;FE_2(CLASS, __VA_ARGS__)
#define FE_4(CLASS, X, ...) using CLASS::X;FE_3(CLASS, __VA_ARGS__)
#define FE_5(CLASS, X, ...) using CLASS::X;FE_4(CLASS, __VA_ARGS__)
#define FE_6(CLASS, X, ...) using CLASS::X;FE_5(CLASS, __VA_ARGS__)
#define FE_7(CLASS, X, ...) using CLASS::X;FE_6(CLASS, __VA_ARGS__)
#define FE_8(CLASS, X, ...) using CLASS::X;FE_7(CLASS, __VA_ARGS__)
#define FE_9(CLASS, X, ...) using CLASS::X;FE_8(CLASS, __VA_ARGS__)
#define FE_10(CLASS, X, ...) using CLASS::X;FE_9(CLASS, __VA_ARGS__)
#define FE_11(CLASS, X, ...) using CLASS::X;FE_10(CLASS, __VA_ARGS__)
#define FE_12(CLASS, X, ...) using CLASS::X;FE_11(CLASS, __VA_ARGS__)
//... repeat as needed

#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,NAME,...) NAME
#define FOR_EACH_USING(class,...) \
  GET_MACRO(__VA_ARGS__,FE_12,FE_11,FE_10,FE_9,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1,)(class,__VA_ARGS__)


问:
Rotate value text vertically outside bar in BarChart MPAndroidChart
Rotate value text vertically outside bar in BarChart MPAndroidChart

I am able to rotate the text but it is coming inside the bar which I have achieved using code below:

chart.setRenderer(CustomBarChartRenderer(context, this, this.getAnimator(), this.getViewPortHandler()))

```<code>public class CustomBarChartRenderer extends BarChartRenderer {
      public CustomBarChartRenderer(BarDataProvider chart,
                                    ChartAnimator animator, ViewPortHandler viewPortHandler) {
           super(chart, animator, viewPortHandler);
      }

      @Override
      public void drawValue(Canvas canvas, IValueFormatter formatter,
                            float value, Entry entry, int dataSetIndex, float x, float y, int color) {
           mValuePaint.setColor(color);

           canvas.save();
           canvas.rotate(-90);

           canvas.drawText(formatter.getFormattedValue(value, entry,
                                                       dataSetIndex, mViewPortHandler), x, y, mValuePaint);
           canvas.restore();
      }
}
</code>```

Text is rotated but comes inside the bar can see in the image link below:

How to make text value properly align above the bar??

答:
I was able to fix it by moving the label up.

Worth noticing is x and y dimensions changes internally as we are rotating the label so for moving label up you have to increase x value and not y value.

Also note to make it dynamic and work for all text lengths, I am calculating the pixel size for text to be displayed and moving label up by that pixel size only. See code below (in kotlin):

```<code>override fun drawValue(c: Canvas, formatter: IValueFormatter, value: Float, entry: Entry, dataSetIndex: Int, x: Float, y: Float, color: Int) {
    mValuePaint.color = Color.WHITE
    val text = formatter.getFormattedValue(value, entry, dataSetIndex, mViewPortHandler)

    c.save()
    val width = mValuePaint.measureText(text)
    c.rotate(-90f, x, y)

    c.drawText(text, x + (width / 2), y, mValuePaint)
    c.restore()
}
</code>```

Body:
Rotate value text vertically outside bar in BarChart MPAndroidChart

I am able to rotate the text but it is coming inside the bar which I have achieved using code below:

chart.setRenderer(CustomBarChartRenderer(context, this, this.getAnimator(), this.getViewPortHandler()))

public class CustomBarChartRenderer extends BarChartRenderer {
      public CustomBarChartRenderer(BarDataProvider chart,
                                    ChartAnimator animator, ViewPortHandler viewPortHandler) {
           super(chart, animator, viewPortHandler);
      }

      @Override
      public void drawValue(Canvas canvas, IValueFormatter formatter,
                            float value, Entry entry, int dataSetIndex, float x, float y, int color) {
           mValuePaint.setColor(color);

           canvas.save();
           canvas.rotate(-90);

           canvas.drawText(formatter.getFormattedValue(value, entry,
                                                       dataSetIndex, mViewPortHandler), x, y, mValuePaint);
           canvas.restore();
      }
}

Text is rotated but comes inside the bar can see in the image link below:

How to make text value properly align above the bar??

Body:
I was able to fix it by moving the label up.

Worth noticing is x and y dimensions changes internally as we are rotating the label so for moving label up you have to increase x value and not y value.

Also note to make it dynamic and work for all text lengths, I am calculating the pixel size for text to be displayed and moving label up by that pixel size only. See code below (in kotlin):

override fun drawValue(c: Canvas, formatter: IValueFormatter, value: Float, entry: Entry, dataSetIndex: Int, x: Float, y: Float, color: Int) {
    mValuePaint.color = Color.WHITE
    val text = formatter.getFormattedValue(value, entry, dataSetIndex, mViewPortHandler)

    c.save()
    val width = mValuePaint.measureText(text)
    c.rotate(-90f, x, y)

    c.drawText(text, x + (width / 2), y, mValuePaint)
    c.restore()
}


问:
Plotting nb object in ggplot?
I would like to plot the outline of UK, along with an nb object that I generated from a spatial points dataframe.

The problem is that the outline of UK takes really, really long to plot --it keeps crashing my Rstudio. This for example, either take really long to load or my Rstudio just stops responding.

```<code>library(raster)
UK_gadm <- getData("GADM", country="GB", level=0)
    plot(UK_gadm)
</code>```

So I resorted to using ggplot2 from this solution where I can get the outline of UK like in a fraction of a second with the following commands:

```<code>library(ggplot2)
UK <- map_data(map = "world", region = "UK") # changed map to "world"
    ggplot(data = UK, aes(x = long, y = lat, group = group)) +
      geom_polygon() +
      coord_map()
</code>```

The issue now is that I would like the nb object to be plotting against the backdrop of the outline of UK -- however, this seems only achievable in base R like for example:

```<code>plot(orotl.shp, xlim=c(-125, -115), ylim=c(42,47))
plot(orstationc.neighbors.dist, orstationc.loc, add=T, lwd=2, col="blue")
</code>```

Is there any way I could plot nb objects in ggplot or is there a way for R to plot the outline of UK without crashing my computer with the base R plot function?

答:
Managed to find a fast, simple solution after a whole night of effort. Hope this helps someone else with a similar issue.

Just to elaborate on the goal: plot a neighbours object (nb) against a shapefile. This is to visualise the linkages among certain coordinates. After some googling, I think this can only be done with base R's plot function.  The problem however, was loading a country's shapefile (downloaded from official sources/gadm)-- its too big.

To solve this issue, get a more generalised, simple map of the country via the maps package, turn it into a shapefile and then plot it alongside the neighbours object.

Here's the code:

```<code>library(spdep)

# get your neighbour object from your spatial points df
rest_neighbours <- dnearneigh(rest_spdf,0,1)

library(maps)

# get boundary of UK
UK_map <- sf::st_as_sf(maps::map(database='world',regions='UK', plot = FALSE, fill = TRUE))

# write to shapefile
st_write(UK_map, 'shapefiles/UK.shp')

# henceforth, we can just call the shapefile
UK <- readOGR('shapefiles/UK.shp')

# plot the boundary and the neighbours
plot(UK)
plot(rest_neighbours, rest_coords, add=T, lwd=2, col="blue")
</code>```

I did not realise that official boundary files are often really detailed which also means that they are really huge and I'm glad that there's ready-made watered down versions of the maps available in the maps package of r. (Sorry if you already knew -- I'm still learning!)

Hope this helps anyone else!

Title: Plotting nb object in ggplot?

Body:
I would like to plot the outline of UK, along with an nb object that I generated from a spatial points dataframe.

The problem is that the outline of UK takes really, really long to plot --it keeps crashing my Rstudio. This for example, either take really long to load or my Rstudio just stops responding.

library(raster)
UK_gadm <- getData("GADM", country="GB", level=0)
    plot(UK_gadm)

So I resorted to using ggplot2 from this solution where I can get the outline of UK like in a fraction of a second with the following commands:

library(ggplot2)
UK <- map_data(map = "world", region = "UK") # changed map to "world"
    ggplot(data = UK, aes(x = long, y = lat, group = group)) +
      geom_polygon() +
      coord_map()

The issue now is that I would like the nb object to be plotting against the backdrop of the outline of UK -- however, this seems only achievable in base R like for example:

plot(orotl.shp, xlim=c(-125, -115), ylim=c(42,47))
plot(orstationc.neighbors.dist, orstationc.loc, add=T, lwd=2, col="blue")

Is there any way I could plot nb objects in ggplot or is there a way for R to plot the outline of UK without crashing my computer with the base R plot function?

Body:
Managed to find a fast, simple solution after a whole night of effort. Hope this helps someone else with a similar issue.

Just to elaborate on the goal: plot a neighbours object (nb) against a shapefile. This is to visualise the linkages among certain coordinates. After some googling, I think this can only be done with base R's plot function.  The problem however, was loading a country's shapefile (downloaded from official sources/gadm)-- its too big.

To solve this issue, get a more generalised, simple map of the country via the maps package, turn it into a shapefile and then plot it alongside the neighbours object.

Here's the code:

library(spdep)

# get your neighbour object from your spatial points df
rest_neighbours <- dnearneigh(rest_spdf,0,1)

library(maps)

# get boundary of UK
UK_map <- sf::st_as_sf(maps::map(database='world',regions='UK', plot = FALSE, fill = TRUE))

# write to shapefile
st_write(UK_map, 'shapefiles/UK.shp')

# henceforth, we can just call the shapefile
UK <- readOGR('shapefiles/UK.shp')

# plot the boundary and the neighbours
plot(UK)
plot(rest_neighbours, rest_coords, add=T, lwd=2, col="blue")

I did not realise that official boundary files are often really detailed which also means that they are really huge and I'm glad that there's ready-made watered down versions of the maps available in the maps package of r. (Sorry if you already knew -- I'm still learning!)

Hope this helps anyone else!


问:
Not able to get data when form is submitted using phpmailer and later forwared
Simple PHP script to capture user form input and send me email.

Empty form gets submitted using phpmailer script i.e. Receiving email without user filled data. There is no SMTP error, Page get submitted and redirected to new Page. Request to please help. Sometimes email received also form has user filled data also, not sure why ?

```<code><?php

date_default_timezone_set('Etc/UTC');
 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
require './PHPMailer/src/Exception.php';

try {
$mail = new PHPMailer(true);

    $mail->SMTPDebug = 0;
     $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = "XXXXX@gmail.com";
    $mail->Password = "XXXXX";
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('XXXXX@gmail.com', 'Mr Singh');
    $mail->addReplyTo('XXXXX@gmail.com', 'Mr Singh');
    $mail->addAddress('XXXXX@gmail.com', 'Mr Singh');

    $mail->Subject = 'PHPMailer Exceptions test';
$mail->isHTML(false);

        $mail->Body = <<<EOT
Email: {$_POST['name']}
Email: {$_POST['email']}
Mobile: {$_POST['mobile']}
EOT;

    $mail->send();
    header("Refresh:1; contact.html");
} catch (Exception $e) {
    echo $e->errorMessage();
} catch (\Exception $e) { //The leading slash means the Global PHP Exception class will be caught
    echo $e->getMessage();
}

?>
</code>```

答:
If this script is ever run at all, it will send an email, regardless of whether any data was submitted or not. Wrap it in a condition that only sends a message if data has been submitted, something like:

```<code>if (isset(_POST['email'])) {
   try {
        $mail = new PHPMailer(true);
...
</code>```

You can be more thorough about this check, for example validate that a valid email address was submitted, that the other fields contain what you expect, and so on, but you should get the general idea.

Body:
Simple PHP script to capture user form input and send me email.

Empty form gets submitted using phpmailer script i.e. Receiving email without user filled data. There is no SMTP error, Page get submitted and redirected to new Page. Request to please help. Sometimes email received also form has user filled data also, not sure why ?

<?php

date_default_timezone_set('Etc/UTC');
 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
require './PHPMailer/src/Exception.php';

try {
$mail = new PHPMailer(true);

    $mail->SMTPDebug = 0;
     $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = "XXXXX@gmail.com";
    $mail->Password = "XXXXX";
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('XXXXX@gmail.com', 'Mr Singh');
    $mail->addReplyTo('XXXXX@gmail.com', 'Mr Singh');
    $mail->addAddress('XXXXX@gmail.com', 'Mr Singh');

    $mail->Subject = 'PHPMailer Exceptions test';
$mail->isHTML(false);

        $mail->Body = <<<EOT
Email: {$_POST['name']}
Email: {$_POST['email']}
Mobile: {$_POST['mobile']}
EOT;

    $mail->send();
    header("Refresh:1; contact.html");
} catch (Exception $e) {
    echo $e->errorMessage();
} catch (\Exception $e) { //The leading slash means the Global PHP Exception class will be caught
    echo $e->getMessage();
}

?>

Body:
If this script is ever run at all, it will send an email, regardless of whether any data was submitted or not. Wrap it in a condition that only sends a message if data has been submitted, something like:

if (isset(_POST['email'])) {
   try {
        $mail = new PHPMailer(true);
...

You can be more thorough about this check, for example validate that a valid email address was submitted, that the other fields contain what you expect, and so on, but you should get the general idea.


问:
Can't modify ETCD manifest for Kubernetes static pod
I'd like to modify etcd pod to listening 0.0.0.0(or host machine IP) instead of 127.0.0.1.

I'm working on a migration from a single master to multi-master kubernetes cluster, but I faced with an issue that after I modified /etc/kubernetes/manifests/etcd.yaml with correct settings and restart kubelet and even docker daemons, etcd still working on 127.0.0.1.

Inside docker container I'm steel seeing that etcd started with --listen-client-urls=https://127.0.0.1:2379 instead of host IP

cat /etc/kubernetes/manifests/etcd.yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  annotations:
    scheduler.alpha.kubernetes.io/critical-pod: ""
  creationTimestamp: null
  labels:
    component: etcd
    tier: control-plane
  name: etcd
  namespace: kube-system
spec:
  containers:
  - command:
    - etcd
    - --advertise-client-urls=https://192.168.22.9:2379
    - --cert-file=/etc/kubernetes/pki/etcd/server.crt
    - --client-cert-auth=true
    - --data-dir=/var/lib/etcd
    - --initial-advertise-peer-urls=https://192.168.22.9:2380
    - --initial-cluster=test-master-01=https://192.168.22.9:2380
    - --key-file=/etc/kubernetes/pki/etcd/server.key
    - --listen-client-urls=https://192.168.22.9:2379
    - --listen-peer-urls=https://192.168.22.9:2380
    - --name=test-master-01
    - --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt
    - --peer-client-cert-auth=true
    - --peer-key-file=/etc/kubernetes/pki/etcd/peer.key
    - --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    - --snapshot-count=10000
    - --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    image: k8s.gcr.io/etcd-amd64:3.2.18
    imagePullPolicy: IfNotPresent
    livenessProbe:
      exec:
        command:
        - /bin/sh
        - -ec
        - ETCDCTL_API=3 etcdctl --endpoints=https://[192.168.22.9]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt
          --cert=/etc/kubernetes/pki/etcd/healthcheck-client.crt --key=/etc/kubernetes/pki/etcd/healthcheck-client.key
          get foo
      failureThreshold: 8
      initialDelaySeconds: 15
      timeoutSeconds: 15
    name: etcd
    resources: {}
    volumeMounts:
    - mountPath: /var/lib/etcd
      name: etcd-data
    - mountPath: /etc/kubernetes/pki/etcd
      name: etcd-certs
  hostNetwork: true
  priorityClassName: system-cluster-critical
  volumes:
  - hostPath:
      path: /var/lib/etcd
      type: DirectoryOrCreate
    name: etcd-data
  - hostPath:
      path: /etc/kubernetes/pki/etcd
      type: DirectoryOrCreate
    name: etcd-certs
status: {}
</code>```

[root@test-master-01 centos]# kubectl -n kube-system get po etcd-test-master-01 -o yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/config.hash: c3eef2d48a776483adc00311df8cb940
    kubernetes.io/config.mirror: c3eef2d48a776483adc00311df8cb940
    kubernetes.io/config.seen: 2019-05-24T13:50:06.335448715Z
    kubernetes.io/config.source: file
    scheduler.alpha.kubernetes.io/critical-pod: ""
  creationTimestamp: 2019-05-24T14:08:14Z
  labels:
    component: etcd
    tier: control-plane
  name: etcd-test-master-01
  namespace: kube-system
  resourceVersion: "6288"
  selfLink: /api/v1/namespaces/kube-system/pods/etcd-test-master-01
  uid: 5efadb1c-7e2d-11e9-adb7-fa163e267af4
spec:
  containers:
  - command:
    - etcd
    - --advertise-client-urls=https://127.0.0.1:2379
    - --cert-file=/etc/kubernetes/pki/etcd/server.crt
    - --client-cert-auth=true
    - --data-dir=/var/lib/etcd
    - --initial-advertise-peer-urls=https://127.0.0.1:2380
    - --initial-cluster=test-master-01=https://127.0.0.1:2380
    - --key-file=/etc/kubernetes/pki/etcd/server.key
    - --listen-client-urls=https://127.0.0.1:2379
    - --listen-peer-urls=https://127.0.0.1:2380
    - --name=test-master-01
    - --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt
    - --peer-client-cert-auth=true
    - --peer-key-file=/etc/kubernetes/pki/etcd/peer.key
    - --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    - --snapshot-count=10000
    - --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    image: k8s.gcr.io/etcd-amd64:3.2.18
    imagePullPolicy: IfNotPresent
    livenessProbe:
      exec:
        command:
        - /bin/sh
        - -ec
        - ETCDCTL_API=3 etcdctl --endpoints=https://[127.0.0.1]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt
          --cert=/etc/kubernetes/pki/etcd/healthcheck-client.crt --key=/etc/kubernetes/pki/etcd/healthcheck-client.key
          get foo
</code>```

答: Reviewed my automation scripts step by step and found that I've performed a backup of etcd yaml in the same folder with .bak extension. Looks like kubelet daemon uploads all the files inside the manifests folder and despite the file extension. </p>

Body:
I'd like to modify etcd pod to listening 0.0.0.0(or host machine IP) instead of 127.0.0.1.

I'm working on a migration from a single master to multi-master kubernetes cluster, but I faced with an issue that after I modified /etc/kubernetes/manifests/etcd.yaml with correct settings and restart kubelet and even docker daemons, etcd still working on 127.0.0.1.

Inside docker container I'm steel seeing that etcd started with --listen-client-urls=https://127.0.0.1:2379 instead of host IP

cat /etc/kubernetes/manifests/etcd.yaml

apiVersion: v1
kind: Pod
metadata:
  annotations:
    scheduler.alpha.kubernetes.io/critical-pod: ""
  creationTimestamp: null
  labels:
    component: etcd
    tier: control-plane
  name: etcd
  namespace: kube-system
spec:
  containers:
  - command:
    - etcd
    - --advertise-client-urls=https://192.168.22.9:2379
    - --cert-file=/etc/kubernetes/pki/etcd/server.crt
    - --client-cert-auth=true
    - --data-dir=/var/lib/etcd
    - --initial-advertise-peer-urls=https://192.168.22.9:2380
    - --initial-cluster=test-master-01=https://192.168.22.9:2380
    - --key-file=/etc/kubernetes/pki/etcd/server.key
    - --listen-client-urls=https://192.168.22.9:2379
    - --listen-peer-urls=https://192.168.22.9:2380
    - --name=test-master-01
    - --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt
    - --peer-client-cert-auth=true
    - --peer-key-file=/etc/kubernetes/pki/etcd/peer.key
    - --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    - --snapshot-count=10000
    - --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    image: k8s.gcr.io/etcd-amd64:3.2.18
    imagePullPolicy: IfNotPresent
    livenessProbe:
      exec:
        command:
        - /bin/sh
        - -ec
        - ETCDCTL_API=3 etcdctl --endpoints=https://[192.168.22.9]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt
          --cert=/etc/kubernetes/pki/etcd/healthcheck-client.crt --key=/etc/kubernetes/pki/etcd/healthcheck-client.key
          get foo
      failureThreshold: 8
      initialDelaySeconds: 15
      timeoutSeconds: 15
    name: etcd
    resources: {}
    volumeMounts:
    - mountPath: /var/lib/etcd
      name: etcd-data
    - mountPath: /etc/kubernetes/pki/etcd
      name: etcd-certs
  hostNetwork: true
  priorityClassName: system-cluster-critical
  volumes:
  - hostPath:
      path: /var/lib/etcd
      type: DirectoryOrCreate
    name: etcd-data
  - hostPath:
      path: /etc/kubernetes/pki/etcd
      type: DirectoryOrCreate
    name: etcd-certs
status: {}

[root@test-master-01 centos]# kubectl -n kube-system get po etcd-test-master-01 -o yaml

apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/config.hash: c3eef2d48a776483adc00311df8cb940
    kubernetes.io/config.mirror: c3eef2d48a776483adc00311df8cb940
    kubernetes.io/config.seen: 2019-05-24T13:50:06.335448715Z
    kubernetes.io/config.source: file
    scheduler.alpha.kubernetes.io/critical-pod: ""
  creationTimestamp: 2019-05-24T14:08:14Z
  labels:
    component: etcd
    tier: control-plane
  name: etcd-test-master-01
  namespace: kube-system
  resourceVersion: "6288"
  selfLink: /api/v1/namespaces/kube-system/pods/etcd-test-master-01
  uid: 5efadb1c-7e2d-11e9-adb7-fa163e267af4
spec:
  containers:
  - command:
    - etcd
    - --advertise-client-urls=https://127.0.0.1:2379
    - --cert-file=/etc/kubernetes/pki/etcd/server.crt
    - --client-cert-auth=true
    - --data-dir=/var/lib/etcd
    - --initial-advertise-peer-urls=https://127.0.0.1:2380
    - --initial-cluster=test-master-01=https://127.0.0.1:2380
    - --key-file=/etc/kubernetes/pki/etcd/server.key
    - --listen-client-urls=https://127.0.0.1:2379
    - --listen-peer-urls=https://127.0.0.1:2380
    - --name=test-master-01
    - --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt
    - --peer-client-cert-auth=true
    - --peer-key-file=/etc/kubernetes/pki/etcd/peer.key
    - --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    - --snapshot-count=10000
    - --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
    image: k8s.gcr.io/etcd-amd64:3.2.18
    imagePullPolicy: IfNotPresent
    livenessProbe:
      exec:
        command:
        - /bin/sh
        - -ec
        - ETCDCTL_API=3 etcdctl --endpoints=https://[127.0.0.1]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt
          --cert=/etc/kubernetes/pki/etcd/healthcheck-client.crt --key=/etc/kubernetes/pki/etcd/healthcheck-client.key
          get foo


问:
Trying to plot stacked barplot from percentages
I'm trying to plot a stacked barplot of the rate of computer used in different departments with details on what type of PC in each bar( so that for each department type1+type2+type3=tot_rate) . I've got a dataframe that looks like this :

```<code>dat=read.table(text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10
DPT2 80 30 20 30
DPT3 92 54 14 24", header = TRUE)

</code>```

I tried to plot my barplot with raw data but now it's very important that i get the one with percentages and i can't seem to understand how i can do that.

This is how i thought i could that, but it just doesn't work

```<code>p<-ggplot(dat, aes(x=row.names(dat), y=dat$Tot_rate, fill=data[,2:ncol(dat)])) + geom_bar(stat="identity")+theme_minimal()+xlab("") + ylab("PC rate")+geom_abline(slope=0, intercept=90,  col = "red",lty=2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
p

</code>```

When i try the code above i get :

```<code>Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (9): fill

</code>```

Can you please help ?
Thank you,
Liana

答:
Here is one way to do it using a ggplot2 extension package called ggstatsplot-

set.seed(123)
library(tidyverse)

# creating dataframe in long format
(dat <- read.table(
  text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10
DPT2 80 30 20 30
DPT3 92 54 14 24",
  header = TRUE
) %>%
  tibble::rownames_to_column(var = "id") %>%
  tidyr::gather(., "key", "counts", Type1:Type3))

#>     id Tot_rate   key counts
#> 1 DPT1       72 Type1     50
#> 2 DPT2       80 Type1     30
#> 3 DPT3       92 Type1     54
#> 4 DPT1       72 Type2     12
#> 5 DPT2       80 Type2     20
#> 6 DPT3       92 Type2     14
#> 7 DPT1       72 Type3     10
#> 8 DPT2       80 Type3     30
#> 9 DPT3       92 Type3     24

# bar plot
ggstatsplot::ggbarstats(dat,
                        main = id,
                        condition = key,
                        counts = counts,
                        messages = FALSE)

```

Created on 2019-05-27 by the reprex package (v0.3.0)

Body:
I'm trying to plot a stacked barplot of the rate of computer used in different departments with details on what type of PC in each bar( so that for each department type1+type2+type3=tot_rate) . I've got a dataframe that looks like this :

dat=read.table(text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10
DPT2 80 30 20 30
DPT3 92 54 14 24", header = TRUE)

I tried to plot my barplot with raw data but now it's very important that i get the one with percentages and i can't seem to understand how i can do that.

This is how i thought i could that, but it just doesn't work

p<-ggplot(dat, aes(x=row.names(dat), y=dat$Tot_rate, fill=data[,2:ncol(dat)])) + geom_bar(stat="identity")+theme_minimal()+xlab("") + ylab("PC rate")+geom_abline(slope=0, intercept=90,  col = "red",lty=2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
p

When i try the code above i get :

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (9): fill

Can you please help ?
Thank you,
Liana

Body:
Here is one way to do it using a ggplot2 extension package called ggstatsplot-

set.seed(123)
library(tidyverse)

# creating dataframe in long format
(dat <- read.table(
  text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10
DPT2 80 30 20 30
DPT3 92 54 14 24",
  header = TRUE
) %>%
  tibble::rownames_to_column(var = "id") %>%
  tidyr::gather(., "key", "counts", Type1:Type3))

#>     id Tot_rate   key counts
#> 1 DPT1       72 Type1     50
#> 2 DPT2       80 Type1     30
#> 3 DPT3       92 Type1     54
#> 4 DPT1       72 Type2     12
#> 5 DPT2       80 Type2     20
#> 6 DPT3       92 Type2     14
#> 7 DPT1       72 Type3     10
#> 8 DPT2       80 Type3     30
#> 9 DPT3       92 Type3     24

# bar plot
ggstatsplot::ggbarstats(dat,
                        main = id,
                        condition = key,
                        counts = counts,
                        messages = FALSE)

Created on 2019-05-27 by the reprex package (v0.3.0)


问:
Replacing duplicate list elements with NaN
I would like to replace all duplicates of elements in arrays with NaN.
For example:

```<code>a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]
</code>```

Goal:

```<code>a = [NaN, NaN, 2, 3, NaN, 8, NaN, 6, 7, NaN, NaN]
</code>```

答:
you can use collections.Counter to count all instances of each element in a,
and then create a new a based on the count:

from collections import Counter

a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]
histogram = Counter(a)

a = [n if histogram[n]<=1 else None for n in a]
print(a)
```

Body:
I would like to replace all duplicates of elements in arrays with NaN.
For example:

a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]

Goal:

a = [NaN, NaN, 2, 3, NaN, 8, NaN, 6, 7, NaN, NaN]


问:
How to open a web resource in a new tab instead of a new window when clicking a ribbon button
I've created a ribbon button inside my Dynamics 365 crm.
On click, the ribbon Button should open a new tab with some stuff in it.

The problem:

This is the code launched when its clicked:

```<code>function OpenPage ()
{
     Xrm.Utility.openWebResource("new_someWebResourceHTML");
}
</code>```

the code actually works, and it works well, it opens a new window new_someWebResourceHTML.html.

The question:

Is there some way to open a web resource on a new tab, instead of a new window, using javascript?

Thanks for any help

答:
Use window.open with second parameter '_blank':</p>

```<code>function openInNewTab(webResource) {
  var prefixUrl = Xrm.Page.context.getClientUri() + '/WebResources/'
  var win = window.open(prefixUrl + webResource +, '_blank');
  win.focus();
}
</code>```

Body:
I've created a ribbon button inside my Dynamics 365 crm.
On click, the ribbon Button should open a new tab with some stuff in it.

The problem:

This is the code launched when its clicked:

function OpenPage ()
{
     Xrm.Utility.openWebResource("new_someWebResourceHTML");
}

the code actually works, and it works well, it opens a new window new_someWebResourceHTML.html.

The question:

Is there some way to open a web resource on a new tab, instead of a new window, using javascript?

Thanks for any help

Body:
Use window.open with second parameter '_blank':

function openInNewTab(webResource) {
  var prefixUrl = Xrm.Page.context.getClientUri() + '/WebResources/'
  var win = window.open(prefixUrl + webResource +, '_blank');
  win.focus();
}


问:
By clicking one checkbox other checkbox should be disable
I've 2 columns with checkboxes when one column is checked all respective are checked likewise in 2nd column but the problem is here, client wants when One column of checkbox is checked then 2nd column will be disable or throw alert message to check only one column at a time?

```<code>function SelectAll1(headerchk, gridId) {

        var gvcheck = document.getElementById(gridId);
        var i, j;
        if (headerchk.checked) {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
               for (j = 1; j < inputs.length; j++) {
                 if (inputs[j].type == "checkbox") {
                        inputs[j].checked = true;
                    }
                }
            }
        }
        else {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
                 for (j = 1; j < inputs.length; j++) {
                   if (inputs[j].type == "checkbox") {
                        inputs[j].checked = false;
                    }
                }
            }
        }
    }
</code>```

You can ch

答:
From the little info given I assume this:

SelectAll1 clear or set all checkboxes in column 1.

SelectAll2 clear or set all checkboxes in column 2.

headerchk is a checkbox when clicked clears or sets all.

Do this change:

After each line in the code where SelectAll1(headerchk, gridId) is called you change it to SelectAll1(headerchk.checked, gridId).

Insert another line below this line with a negation:
SelectAll2(!headerchk.checked, gridId)

After each line in the code where SelectAll2(headerchk, gridId) is called you change it to SelectAll2(headerchk.checked, gridId).

Insert another line below this line with a negation:
SelectAll1(!headerchk.checked, gridId)

You only showed me the code for SelectAll1, so I assume SelectAll2 is the same when you not yet know how to make them different. Correct me if this is not the fact!

Continue by change the function SelectAll1 to the following:

```<code>function SelectAll1(header_checked, gridId) {
    var gvcheck = document.getElementById(gridId);
    var i, j;
    for (i = 0; i < gvcheck.rows.length - 1; i++) {
        var inputs = gvcheck.rows[i].getElementsByTagName('input');
        for (j = 1; j < inputs.length; j++) {
            if (inputs[j].type == "checkbox") {
                inputs[j].checked = header_checked;
            }
        }
    }
}
</code>```

The else-part and if is eliminated by moving the condition to the assignment that is eiher true or false. The .checked part is moved outside the function.

Do the same change in SelectAll2

Test if it works and report to me!

Body:
I've 2 columns with checkboxes when one column is checked all respective are checked likewise in 2nd column but the problem is here, client wants when One column of checkbox is checked then 2nd column will be disable or throw alert message to check only one column at a time?

function SelectAll1(headerchk, gridId) {

        var gvcheck = document.getElementById(gridId);
        var i, j;
        if (headerchk.checked) {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
               for (j = 1; j < inputs.length; j++) {
                 if (inputs[j].type == "checkbox") {
                        inputs[j].checked = true;
                    }
                }
            }
        }
        else {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
                 for (j = 1; j < inputs.length; j++) {
                   if (inputs[j].type == "checkbox") {
                        inputs[j].checked = false;
                    }
                }
            }
        }
    }

You can ch

Body:
From the little info given I assume this:

SelectAll1 clear or set all checkboxes in column 1.

SelectAll2 clear or set all checkboxes in column 2.

headerchk is a checkbox when clicked clears or sets all.

Do this change:

After each line in the code where SelectAll1(headerchk, gridId) is called you change it to SelectAll1(headerchk.checked, gridId).

Insert another line below this line with a negation:
SelectAll2(!headerchk.checked, gridId)

After each line in the code where SelectAll2(headerchk, gridId) is called you change it to SelectAll2(headerchk.checked, gridId).

Insert another line below this line with a negation:
SelectAll1(!headerchk.checked, gridId)

You only showed me the code for SelectAll1, so I assume SelectAll2 is the same when you not yet know how to make them different. Correct me if this is not the fact!

Continue by change the function SelectAll1 to the following:

function SelectAll1(header_checked, gridId) {
    var gvcheck = document.getElementById(gridId);
    var i, j;
    for (i = 0; i < gvcheck.rows.length - 1; i++) {
        var inputs = gvcheck.rows[i].getElementsByTagName('input');
        for (j = 1; j < inputs.length; j++) {
            if (inputs[j].type == "checkbox") {
                inputs[j].checked = header_checked;
            }
        }
    }
}

The else-part and if is eliminated by moving the condition to the assignment that is eiher true or false. The .checked part is moved outside the function.

Do the same change in SelectAll2

Test if it works and report to me!


问:
Overwrite repository definition in gradle subproject
Imagine you have a gradle build with a gradle subproject.
This subproject has some applied script plugin which define their own repositories like this:

```<code>buildscript {
    repositories {
        //jcenter()
        maven {
            url 'https://example.com/plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
    }
}
</code>```

Now imagine you only own the main project, not the sub project (it is a git submodule).

How can you override the repository definitions of the subproject from the main project?

PS: if you need a better description of the subproject, here it is: https://github.com/docToolchain/docToolchain

Update: I've created an example to paly around with: https://github.com/rdmueller/SO56283254/blob/master/README.adoc

see the readme for more details

答:
I've just tried a little, while I have no project where the sub-projects would feature a build-script:

```<code>// this lists buildscript repositories:
getRootProject().getBuildscript().getRepositories().each { repo ->
    println "root: " + repo.getName().toString()
}

// this might list nothing:
subprojects.findAll { project ->
    project.buildscript.getRepositories().each { repo ->
        println "sub: " +  repo.getName().toString()
    }
}
</code>```

The main problem might be, that this is being configured top-down; eg. passing a command-line argument which would apply an alternate buildscript.gradle block could work, but changing the root-project's configuration from within the scope of a sub-project won't. It might be rather uncommon, that sub-projects feature their own buildscript block (these Gradle plugin dependencies behave different than the regular Java dependencies - one generally can only decide where to apply them).

Body:
Imagine you have a gradle build with a gradle subproject.
This subproject has some applied script plugin which define their own repositories like this:

buildscript {
    repositories {
        //jcenter()
        maven {
            url 'https://example.com/plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
    }
}

Now imagine you only own the main project, not the sub project (it is a git submodule).

How can you override the repository definitions of the subproject from the main project?

PS: if you need a better description of the subproject, here it is: https://github.com/docToolchain/docToolchain

Update: I've created an example to paly around with: https://github.com/rdmueller/SO56283254/blob/master/README.adoc

see the readme for more details

Body:
I've just tried a little, while I have no project where the sub-projects would feature a build-script:

// this lists buildscript repositories:
getRootProject().getBuildscript().getRepositories().each { repo ->
    println "root: " + repo.getName().toString()
}

// this might list nothing:
subprojects.findAll { project ->
    project.buildscript.getRepositories().each { repo ->
        println "sub: " +  repo.getName().toString()
    }
}

The main problem might be, that this is being configured top-down; eg. passing a command-line argument which would apply an alternate buildscript.gradle block could work, but changing the root-project's configuration from within the scope of a sub-project won't. It might be rather uncommon, that sub-projects feature their own buildscript block (these Gradle plugin dependencies behave different than the regular Java dependencies - one generally can only decide where to apply them).


问:
How to use materialize-css with React?
I have a Meteor/React project, using ES6 modules. I've installed materialize-css using npm, but I'm not sure how to actually use the Materialize classes in my JSX code. What am I supposed to import from materialize-css? Or do I just have to include the CSS in my main index.html file?

I mostly want it for the grid system, as I'll be using material-ui for the actual UI components.

答:
Use CDN:

```<code><!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</code>```

Then const M = window.M; to do initialization.

Title: How to use materialize-css with React?

Body:
Use CDN:

<!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

Then const M = window.M; to do initialization.


问:
Two images on my website are different height to others
two of these images are different height

I'm doing a web dev course online and first HTML/CSS section revolves around making a website as you cover each topic. I'm trying to make all these images appear one next to the other and have the same size - for some reason two of the divs still remain larger than the rest, setting height does not work for these two.

Here is what I tried in CSS:

```<code>body{
font-family: 'Barlow', sans-serif;
background:white;
max-width: 1000px;
margin: 0 auto;

.product {
border: 1px solid grey;
width: 200px;
margin: 5px;
padding: 5px;
display: inline-block;
}

img{
max-width: 100%;
height: 200px;
}
</code>```

And example of how all divs from .product class were created:

```<code> <div class="product">
<a href="product-details-lip-balm.html">
    <img src="images/makeup5.jpg" alt="Lip balm">
</a>
<h4><a href="product-details-lip-balm.html">Lip balm</a></h4>
<p> £ 5</p>
<p> Organic lip balm by Make Me Bio</p>
<a href="product-detail.html" class="button">More info</a>
<a href="" class="button">Add To Cart</a>
</code>```

two images have different height

答:
I think probably you can use "display:block;" instead of "display:inline-block;"

Use following code in the class "product".

```<code>   .product {
        display: block;
        float:left;
     }
</code>```

And if you provide "margin:auto;" for the img, then the image will be center.

Body:
two of these images are different height

I'm doing a web dev course online and first HTML/CSS section revolves around making a website as you cover each topic. I'm trying to make all these images appear one next to the other and have the same size - for some reason two of the divs still remain larger than the rest, setting height does not work for these two.

Here is what I tried in CSS:

body{
font-family: 'Barlow', sans-serif;
background:white;
max-width: 1000px;
margin: 0 auto;

.product {
border: 1px solid grey;
width: 200px;
margin: 5px;
padding: 5px;
display: inline-block;
}

img{
max-width: 100%;
height: 200px;
}

And example of how all divs from .product class were created:

Lip balm

 £ 5

 Organic lip balm by Make Me Bio

More info
Add To Cart

two images have different height

Body:
I think probably you can use "display:block;" instead of "display:inline-block;"

Use following code in the class "product".

   .product {
        display: block;
        float:left;
     }

And if you provide "margin:auto;" for the img, then the image will be center.


问:
HTML5 iFrame Seamless Attribute
in HTML5 the iframe has new attributes like 'seamless' that should remove borders and scrollbars. I've tried it but doesn't seem to work, I still can see scrollbars and borders (I'm using Google Chrome as browser), Here's my code:

```<code><iframe seamless="seamless" title="google" width="600" height="300" src="http://www.google.co.uk"></iframe>
</code>```

Any idea why it's not working?

One more question, is it possible to target a specific section of the page inside the iframe?

答:
Updated: October 2016

The seamless attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:

So I think the gist of it all both from the implementor side and the web-dev side is that seamless as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.

In other words: purge the seamless attribute from your memory, and pretend it never existed.

For posterity's sake, here's my original answer from five years ago:

Original answer: April 2011

The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:

```<code>iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}
</code>```

There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big  nested inside the  element, for example).

Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:

```<code><iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>
</code>```

Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.

Title: HTML5 iFrame Seamless Attribute

Body:
in HTML5 the iframe has new attributes like 'seamless' that should remove borders and scrollbars. I've tried it but doesn't seem to work, I still can see scrollbars and borders (I'm using Google Chrome as browser), Here's my code:

Any idea why it's not working?

One more question, is it possible to target a specific section of the page inside the iframe?

Body:
Updated: October 2016

The seamless attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:

So I think the gist of it all both from the implementor side and the web-dev side is that seamless as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.

In other words: purge the seamless attribute from your memory, and pretend it never existed.

For posterity's sake, here's my original answer from five years ago:

Original answer: April 2011

The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:

iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}

There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big  nested inside the  element, for example).

Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:

<iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>

Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.


问:
DataGridView not showing data when i use while loop or if statement
```<code>private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("select * from AccountTbl where EmployeeCode=" + comboBox1.Text, con);
            con.Open();
            DataTable dt = new DataTable();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                textBox1.Text = (dr["Status"].ToString());
            }
            dt.Load(dr);
            dataGridView1.DataSource = dt;
            con.Close();

        }
        catch (Exception ex)
        {

            MessageBox.Show("Enter");
        }
        finally
        {
            con.Close();
        }
    }
</code>```

答:
So when debugging your snippet, you should be able to see, that there is data read by the dr.Read().

And while reading your DataReader dr.Read() will consume all incoming data rows one-by-one. And within your while-loop you will operate with the received data.

```<code>// Get data row by row
while (dr.Read())
{
     // Displays the current "Status" content in your textbox
     textBox1.Text = (dr["Status"].ToString());
}
</code>```

And when it now comes to creating your DataTable with Load(). The reader has just finished reading and hasn't any row left to read.

```<code>dt.Load(dr);
</code>```

So your displayed DataGrid will be empty.

As a hint:

I recommend wrapping your data reader in a using block like

```<code>using(SqlDataReader dr = cmd.ExecuteReader())
{
   while (dr.Read())
   {
      //Processing
   }

   // or

   dt.Load(dr);
}
</code>```

This will close and dispose your data reader.
You may take a look at
Is it necessary to manually close and dispose of SqlDataReader?

Body:
So when debugging your snippet, you should be able to see, that there is data read by the dr.Read().

And while reading your DataReader dr.Read() will consume all incoming data rows one-by-one. And within your while-loop you will operate with the received data.

// Get data row by row
while (dr.Read())
{
     // Displays the current "Status" content in your textbox
     textBox1.Text = (dr["Status"].ToString());
}

And when it now comes to creating your DataTable with Load(). The reader has just finished reading and hasn't any row left to read.

dt.Load(dr);

So your displayed DataGrid will be empty.

As a hint:

I recommend wrapping your data reader in a using block like

using(SqlDataReader dr = cmd.ExecuteReader())
{
   while (dr.Read())
   {
      //Processing
   }

   // or

   dt.Load(dr);
}

This will close and dispose your data reader.
You may take a look at
Is it necessary to manually close and dispose of SqlDataReader?


问:
How to solve truncated text in flutter
In flutter, I made image and add text under image, but the text is truncated (image below)

I do the following :

```<code>body: new TabBarView(
        children: [
          new Scaffold(
            body: GridView.count(
              primary: true,
              padding: const EdgeInsets.all(20.0),
              crossAxisCount: 2,
              childAspectRatio: 1.0,
              mainAxisSpacing: 100.0,
              crossAxisSpacing: 15.0,
              children: <Widget>[
                ListView(
                  children: <Widget>[
                    new Container(
                      decoration: gradientBackDecoration(),
                      child: new ClipRRect(
                        borderRadius: BorderRadius.circular(30.0),
                        child: Image.asset("src/images/2way.jpg",
                            height: 167.0, fit: BoxFit.fitHeight),
                      ),
                    ),
                    new Text(
                      '2 Way',
                      style: TextStyle(
                        fontSize: 20.0,
                        fontFamily: "AbrilFatFace",
                      ),
                    ),
                  ],
                ),
    ListView(
                  children: <Widget>[
                    new Container(
                      decoration: gradientBackDecoration(),
                      child: new ClipRRect(
                        borderRadius: BorderRadius.circular(30.0),
                        child: Image.asset("src/images/andycaldwell.jpg",
                            height: 167.0, fit: BoxFit.fitHeight),
                      ),
                    ),
                    new Text(
                      'Andy Caldwell',
                      style: TextStyle(
                        fontSize: 20.0,
                        fontFamily: "AbrilFatFace",
                      ),
                    ),
                  ],
                ),
              ],
            ),
</code>```

I have updated my code.

I expect the text looks more bigger, centered and not truncated.
Thanks for your help guys.

答:
So in a grid view when the aspect ration is 1, the width and height of its children is same. For a vertically scrolling gridview it first calculates the available screen to fit the width which then determines its height.

In the above scenario the height was as big as the width of the item, which was not allowing the text to show. Adjust the aspect ratio(0.8 worked for me) and that should work. If you want to be more precise then use SliverGridDelegate.

Title: How to solve truncated text in flutter

Body:
In flutter, I made image and add text under image, but the text is truncated (image below)

I do the following :

body: new TabBarView(
        children: [
          new Scaffold(
            body: GridView.count(
              primary: true,
              padding: const EdgeInsets.all(20.0),
              crossAxisCount: 2,
              childAspectRatio: 1.0,
              mainAxisSpacing: 100.0,
              crossAxisSpacing: 15.0,
              children: <Widget>[
                ListView(
                  children: <Widget>[
                    new Container(
                      decoration: gradientBackDecoration(),
                      child: new ClipRRect(
                        borderRadius: BorderRadius.circular(30.0),
                        child: Image.asset("src/images/2way.jpg",
                            height: 167.0, fit: BoxFit.fitHeight),
                      ),
                    ),
                    new Text(
                      '2 Way',
                      style: TextStyle(
                        fontSize: 20.0,
                        fontFamily: "AbrilFatFace",
                      ),
                    ),
                  ],
                ),
    ListView(
                  children: <Widget>[
                    new Container(
                      decoration: gradientBackDecoration(),
                      child: new ClipRRect(
                        borderRadius: BorderRadius.circular(30.0),
                        child: Image.asset("src/images/andycaldwell.jpg",
                            height: 167.0, fit: BoxFit.fitHeight),
                      ),
                    ),
                    new Text(
                      'Andy Caldwell',
                      style: TextStyle(
                        fontSize: 20.0,
                        fontFamily: "AbrilFatFace",
                      ),
                    ),
                  ],
                ),
              ],
            ),

I have updated my code.

I expect the text looks more bigger, centered and not truncated.
Thanks for your help guys.