问:
How to pass Isolated Directive Values from directive to div
Here i wrote simple Isolated directive for showing x And Y values

```<code>app.directive('meassageFunction', function () {
    return {
       templateUrl: '/Html/IsolatedScope/ISolatedDirective.html',
       scope: {
           X: '@',
           Y:'@'
       }
    }
})
</code>```

HtmlPage

```<code>  <div meassage-function X="Md" , Y="Ghouse">

</div>
</code>```

答:
There were a lot of typos in your work, which was interfering with what you were trying to do.

Please be aware that scope variables are case-sensitive (x is not the same as X), and that using the directive you define is super important.

angular.module('thing',[]).directive('messageFunction', function () {
    return {
       template: '{{x}} {{y}}',
       scope: {
           x: '@',
           y:'@'
       }
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="thing">
  <div message-function x="Hello" y="World">
  </div>
</div></code>```

Body:
Here i wrote simple Isolated directive for showing x And Y values

app.directive('meassageFunction', function () {
    return {
       templateUrl: '/Html/IsolatedScope/ISolatedDirective.html',
       scope: {
           X: '@',
           Y:'@'
       }
    }
})

HtmlPage

Body:
There were a lot of typos in your work, which was interfering with what you were trying to do.

Please be aware that scope variables are case-sensitive (x is not the same as X), and that using the directive you define is super important.

angular.module('thing',[]).directive('messageFunction', function () {
    return {
       template: '{{x}} {{y}}',
       scope: {
           x: '@',
           y:'@'
       }
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="thing">
  <div message-function x="Hello" y="World">
  </div>
</div>


来源: stackexchange

问:
Why is it mandatory to mention the Type information before the return type in case of static as well as non-static methods
I need to understand the need of putting a Type before the return type in case of both, static and non-static classes. Is it only to ensure that the method abides by the type, or is there some other part of the story.</p>

答:
I suppose you refer to this kind of method :

```<code>public <T> void myMethod(T t){
}
</code>```

or

```<code>public <T> T myMethod(){
}
</code>```

Specifying a T type in this way sets a constraint on parameters or the returned object.

When you declare a generic class you generally don't declare the type in the method as the type is already declared in the class :

```<code>public class MyGenericClass<T>{
</code>```

For non generic classes, declaring a type in the method may be helpful.

There are multiple use cases.

It may for example allow to return a type according to the variable type assigned to the method by its caller.

The compiler may indeed use the target typing to infer the type of a generic method invocation.

For example you could define a method that converts one object to another type :

```<code>public <T>> convert(Object object, Class<T> clazz){
     ... // copy by reflection for example
    return (T) convertedObject;
 }
</code>```

And you could invoke it in this way :

```<code>MyStringWrapper stringWrapper = convert("myString");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I suppose you refer to this kind of method :

public <T> void myMethod(T t){
}

or

public <T> T myMethod(){
}

Specifying a T type in this way sets a constraint on parameters or the returned object.

When you declare a generic class you generally don't declare the type in the method as the type is already declared in the class :

public class MyGenericClass<T>{

For non generic classes, declaring a type in the method may be helpful.

There are multiple use cases.

It may for example allow to return a type according to the variable type assigned to the method by its caller.

The compiler may indeed use the target typing to infer the type of a generic method invocation.

For example you could define a method that converts one object to another type :

public <T>> convert(Object object, Class<T> clazz){
     ... // copy by reflection for example
    return (T) convertedObject;
 }

And you could invoke it in this way :

MyStringWrapper stringWrapper = convert("myString");

ContentLicense: CC BY-SA 3.0


问:
How to get intersection of the arrays in a nested array
I have an array like the following which is computed from another function I don't want to modify.

```<code>var d = [[1, 2, 3], [2, 3], [1, 3]];
</code>```

I want to use _.intersection with all the arrays within the above array like this:

```<code>var c = _.intersection(d);
// should return [3]
</code>```

but _.intersection takes multiple array parameters as input, not an array of arrays.

I have tried to flatten an array using something similar to Merge/flatten an array of arrays in JavaScript? but it convert the whole array into a single array.

```<code>var merged = [].concat.apply([], d);
[1, 2, 3, 2, 3, 1, 3]; // I don't want this
</code>```

Let me explain this in detail. I have a nested array d (which contains arrays and length is dynamic). Now I want to find the intersection of all arrays that are within array d.

How can I call _.intersection([1, 2, 3], [2, 3], [1, 3], ...) but dynamically with d?

答:
The only way to do that is to put each of those internal arrays into a separate variable. With ES6, it's as easy as:

```<code>let d = [[1, 2, 3], [2, 3], [1, 3]];
let [arr1, arr2, arr3] = d;
// -> arr1: [1, 2, 3], arr2: [2, 3], arr3: [1, 3]
</code>```

Otherwise, you can do it using the standard ES5 syntax of course.

The only way you'll be able to work with all of those internal arrays with the same variable is to use the parent array you already have, d.

Body:
I have an array like the following which is computed from another function I don't want to modify.

var d = [[1, 2, 3], [2, 3], [1, 3]];

I want to use _.intersection with all the arrays within the above array like this:

var c = _.intersection(d);
// should return [3]

but _.intersection takes multiple array parameters as input, not an array of arrays.

I have tried to flatten an array using something similar to Merge/flatten an array of arrays in JavaScript? but it convert the whole array into a single array.

var merged = [].concat.apply([], d);
[1, 2, 3, 2, 3, 1, 3]; // I don't want this

Let me explain this in detail. I have a nested array d (which contains arrays and length is dynamic). Now I want to find the intersection of all arrays that are within array d.

How can I call _.intersection([1, 2, 3], [2, 3], [1, 3], ...) but dynamically with d?

Body:
The only way to do that is to put each of those internal arrays into a separate variable. With ES6, it's as easy as:

let d = [[1, 2, 3], [2, 3], [1, 3]];
let [arr1, arr2, arr3] = d;
// -> arr1: [1, 2, 3], arr2: [2, 3], arr3: [1, 3]

Otherwise, you can do it using the standard ES5 syntax of course.

The only way you'll be able to work with all of those internal arrays with the same variable is to use the parent array you already have, d.


问:
How to get old entity value in @HandleBeforeSave event to determine if a property is changed or not?
I'm trying to get the old entity in a @HandleBeforeSave event.

```<code>@Component
@RepositoryEventHandler(Customer.class)
public class CustomerEventHandler {

    private CustomerRepository customerRepository;

    @Autowired
    public CustomerEventHandler(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @HandleBeforeSave
    public void handleBeforeSave(Customer customer) {
        System.out.println("handleBeforeSave :: customer.id = " + customer.getId());
        System.out.println("handleBeforeSave :: new customer.name = " + customer.getName());

        Customer old = customerRepository.findOne(customer.getId());
        System.out.println("handleBeforeSave :: new customer.name = " + customer.getName());
        System.out.println("handleBeforeSave :: old customer.name = " + old.getName());
    }
}
</code>```

In the event I try to get the old entity using the findOne method but this return the new event. Probably because of Hibernate/Repository caching in the current session.

Is there a way to get the old entity?

I need this to determine if a given property is changed or not. In case the property is changes I need to perform some action.

答:
Just another solution using model:

```<code>public class Customer {

  @JsonIgnore
  private String name;

  @JsonIgnore
  @Transient
  private String newName;

  public void setName(String name){
    this.name = name;
  }

  @JsonProperty("name")
  public void setNewName(String newName){
    this.newName = newName;
  }

  @JsonProperty
  public void getName(String name){
    return name;
  }

  public void getNewName(String newName){
    return newName;
  }

}
</code>```

Alternative to consider. Might be reasonable if you need some special handling for this use-case then treat it separately. Do not allow direct property writing on the object. Create a separate endpoint with a custom controller to rename customer.

Example request:

```<code>POST /customers/{id}/identity

{
  "name": "New name"
}
</code>```

Body:
I'm trying to get the old entity in a @HandleBeforeSave event.

@Component
@RepositoryEventHandler(Customer.class)
public class CustomerEventHandler {

    private CustomerRepository customerRepository;

    @Autowired
    public CustomerEventHandler(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @HandleBeforeSave
    public void handleBeforeSave(Customer customer) {
        System.out.println("handleBeforeSave :: customer.id = " + customer.getId());
        System.out.println("handleBeforeSave :: new customer.name = " + customer.getName());

        Customer old = customerRepository.findOne(customer.getId());
        System.out.println("handleBeforeSave :: new customer.name = " + customer.getName());
        System.out.println("handleBeforeSave :: old customer.name = " + old.getName());
    }
}

In the event I try to get the old entity using the findOne method but this return the new event. Probably because of Hibernate/Repository caching in the current session.

Is there a way to get the old entity?

I need this to determine if a given property is changed or not. In case the property is changes I need to perform some action.

Body:
Just another solution using model:

public class Customer {

  @JsonIgnore
  private String name;

  @JsonIgnore
  @Transient
  private String newName;

  public void setName(String name){
    this.name = name;
  }

  @JsonProperty("name")
  public void setNewName(String newName){
    this.newName = newName;
  }

  @JsonProperty
  public void getName(String name){
    return name;
  }

  public void getNewName(String newName){
    return newName;
  }

}

Alternative to consider. Might be reasonable if you need some special handling for this use-case then treat it separately. Do not allow direct property writing on the object. Create a separate endpoint with a custom controller to rename customer.

Example request:

POST /customers/{id}/identity

{
  "name": "New name"
}


问:
How to remove duplicate values from dict?
I'm trying to remove duplicate values in my dict but its not working:

```<code>samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.iteritems():
      if value not in samples_antibiotics.values():
        samples_antibiotics[key] = value
print samples_antibiotics
</code>```

This prints:

```<code>{'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
</code>```

答:
You can try this:</p>

```<code>samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}

new_dict = {a:list(set(b)) for a, b in samples_antibiotics_with_duplicatates.items()}
</code>```

Body:
I'm trying to remove duplicate values in my dict but its not working:

samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.iteritems():
      if value not in samples_antibiotics.values():
        samples_antibiotics[key] = value
print samples_antibiotics

This prints:

{'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}

Body:
You can try this:

samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}

new_dict = {a:list(set(b)) for a, b in samples_antibiotics_with_duplicatates.items()}


问:
How to represent multiple types (union types) when targeting JavaScript
What I would like to do is use a generic type that can be one of three other types.

Here's an example with a function:

```<code>fun <T> get(key: String) : T where T: String, T: Number, T: Boolean {}
</code>```

The above code doesn't work, so how should I go about doing this?

答:
How would the compiler know what type is being returned in this case? T could presumably be anything, so they would be no way to define something like that.

You could define three type-specific methods:

```<code>fun getString(key: String): String = ...
fun getBoolean(key: String): Boolean= ...
fun getInt(key: String): Int = ...
</code>```

(Or a wrapper method, as kevinmost suggested)

Body:
What I would like to do is use a generic type that can be one of three other types.

Here's an example with a function:

fun <T> get(key: String) : T where T: String, T: Number, T: Boolean {}

The above code doesn't work, so how should I go about doing this?

Body:
How would the compiler know what type is being returned in this case? T could presumably be anything, so they would be no way to define something like that.

You could define three type-specific methods:

fun getString(key: String): String = ...
fun getBoolean(key: String): Boolean= ...
fun getInt(key: String): Int = ...

(Or a wrapper method, as kevinmost suggested)


问:
R - Apply dist function to groups
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.

```<code>df2 %>% dplyr::group_by(X1) %>% dist()
</code>```

Where df2 is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.

Here is my dataframe:

```<code>   X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0
</code>```

My desired output is the lower triangular matrix of each group, here is an example:

Title: R - Apply dist function to groups

Body:
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.

df2 %>% dplyr::group_by(X1) %>% dist()

Where df2 is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.

Here is my dataframe:

   X1  A              B
1   1  12             0.0
2   1  18             0.0
3   1  18             1.0
4   1  13             0.0
5   1  18             4.0
6   1  18             0.0
7   1  18             5.0
8   1  18             0.0
9   1  18             0.0
10  2  73            -2.0
11  2  73            -0.5
12  2  74            -0.5
13  2  73             0.0
14  2  71            -1.0
15  2  75             0.0

My desired output is the lower triangular matrix of each group, here is an example:

Body:
Here's my code and the solution

require(dplyr)
df2 <- structure(list(X1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L), A = c(12L, 18L, 18L, 13L, 18L, 18L, 18L,
18L, 18L, 73L, 73L, 74L, 73L, 71L, 75L), B = c(0, 0, 1, 0, 4,
0, 5, 0, 0, -2, -0.5, -0.5, 0, -1, 0)), .Names = c("X1", "A",
"B"), class = "data.frame", row.names = c("1", "2", "3", "4",
"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"))
mydf <- df2 %>% group_by(X1) %>% summarise(distmatrix=list(dist(cbind(A,B))))
mydf
# # A tibble: 2 × 2
# X1 distmatrix
# <int>     <list>
#   1     1 <S3: dist>
#   2     2 <S3: dist>
mydf$distmatrix
# [[1]]
# 1        2        3        4        5        6        7        8
# 2 6.000000
# 3 6.082763 1.000000
# 4 1.000000 5.000000 5.099020
# 5 7.211103 4.000000 3.000000 6.403124
# 6 6.000000 0.000000 1.000000 5.000000 4.000000
# 7 7.810250 5.000000 4.000000 7.071068 1.000000 5.000000
# 8 6.000000 0.000000 1.000000 5.000000 4.000000 0.000000 5.000000
# 9 6.000000 0.000000 1.000000 5.000000 4.000000 0.000000 5.000000 0.000000
#
# [[2]]
# 1        2        3        4        5
# 2 1.500000
# 3 1.802776 1.000000
# 4 2.000000 0.500000 1.118034
# 5 2.236068 2.061553 3.041381 2.236068
# 6 2.828427 2.061553 1.118034 2.000000 4.123106


问:
add-migration not adding model to migration file
I have created a model called "SupportTicket" and tried to create a migration to scaffold the database however, the migration file came back as blank. I have migrations enabled.

The SupportTicket model

```<code>public class SupportTicket
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}
</code>```

The DAO file:

```<code>public class ApplicationUser : IdentityUser
        {
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                // Add custom user claims here

                userIdentity.AddClaim(new Claim("FirstName", FirstName.ToString()));
                userIdentity.AddClaim(new Claim("LastName", LastName.ToString()));

                return userIdentity;
            }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {

            public DbSet<SupportTicket> SupportTickets { get; set; }
            public ApplicationDbContext()
                : base("DefaultConnection")
            {
            }

            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }
</code>```

The output migration file:

```<code>public partial class added_support_ticket : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}
</code>```

What am I doing wong? This is my first time using Migrations and I have very little clue what I'm doing.

Thanks in advance for help.

答: I deleted the migration file and re-created it and the migration worked.</p>

Body:
I have created a model called "SupportTicket" and tried to create a migration to scaffold the database however, the migration file came back as blank. I have migrations enabled.

The SupportTicket model

public class SupportTicket
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

The DAO file:

public class ApplicationUser : IdentityUser
        {
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                // Add custom user claims here

                userIdentity.AddClaim(new Claim("FirstName", FirstName.ToString()));
                userIdentity.AddClaim(new Claim("LastName", LastName.ToString()));

                return userIdentity;
            }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {

            public DbSet<SupportTicket> SupportTickets { get; set; }
            public ApplicationDbContext()
                : base("DefaultConnection")
            {
            }

            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }

The output migration file:

public partial class added_support_ticket : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

What am I doing wong? This is my first time using Migrations and I have very little clue what I'm doing.

Thanks in advance for help.


问:
Passing Data between sibling components in Angular

Above image depicts my Angular 2 application , Main component has two child
components "FromComponent" and "ToComponent".

"FromComponent" displays a list of items with a checkbox beside each item.

When user selects/deselects an item in FromComponent , it should be added/removed from ToComponent list of items.

what is the best way to implement this in angular 2 ?

答: I have implemented that using a service as described here where parent-child communication is described. A service can connect a parent with all its children.</p>


问:
Android - Validate Fields Prior To Switching Tabs
I have 2 tabs A and B. Tab A contains fields that must be entered by the user. If the user clicks tab B, I am calling my validate routine in a "OnTabSelectedListener". The problem I have is when I want to stop the tab change and keep the user on Tab A to fill out the required fields. Is there a way to accomplish this within the OnTabSelectedListener? </p>

答: In OnTabSelectedListener method onTabSelected() is invoked when tab change has already happened, so all you can do is check user input and switch back to tab A if input validation failed.</p>


问:
Where is EJB method run
I'm calling an EJB method remotly using next code:

```<code>RemCallRemote rc = null;
String Text = "";
Properties props = new Properties();

//Filling the properties for connection to a remote server
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sap.engine.services.jndi.InitialContextFactoryImpl");

props.put(Context.PROVIDER_URL, "hostaddress:50004");

props.put(Context.SECURITY_PRINCIPAL, "LOGINNAME");

props.put(Context.SECURITY_CREDENTIALS, "*****");

props.put(Context.URL_PKG_PREFIXES, "com.sap.engine.services");

InitialContext ctx = new InitialContext(props);

//getting a reference to an interface
rc = (RemCallRemote)ctx.lookup("ejb:/appName=sap.com/RemoteCallEAR, jarName=RemoteCallEJB.jar, beanName=RemCall, interfaceName=RemCallRemote");

//calling an EJB method
Text = rc.Check();
</code>```

The code works fine, but my question is: Where is the EJB method run? Is it run always on 'hostaddress' machine or anywhere else?

答:
EJB architecture is based on RMI and uses RMI's Stubs and Skeletons.

In your example RemCallRemote is the stub and all it does is send Check() method call back to server.

These days EJB does not use Skeletons any more and relies on container to handle Stubs requests.

Title: Where is EJB method run

Body:
I'm calling an EJB method remotly using next code:

RemCallRemote rc = null;
String Text = "";
Properties props = new Properties();

//Filling the properties for connection to a remote server
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sap.engine.services.jndi.InitialContextFactoryImpl");

props.put(Context.PROVIDER_URL, "hostaddress:50004");

props.put(Context.SECURITY_PRINCIPAL, "LOGINNAME");

props.put(Context.SECURITY_CREDENTIALS, "*****");

props.put(Context.URL_PKG_PREFIXES, "com.sap.engine.services");

InitialContext ctx = new InitialContext(props);

//getting a reference to an interface
rc = (RemCallRemote)ctx.lookup("ejb:/appName=sap.com/RemoteCallEAR, jarName=RemoteCallEJB.jar, beanName=RemCall, interfaceName=RemCallRemote");

//calling an EJB method
Text = rc.Check();

The code works fine, but my question is: Where is the EJB method run? Is it run always on 'hostaddress' machine or anywhere else?


问:
tcp/ip without ip in .net
Strange title I know, but please hear me out. I am looking for a version of TcpClient and TcpListener which don't use IP. In essence, I would like to be able to use all the TCP benefits (reliable & ordered) on top of any protocol of my choosing (UDP, ICMP, DNS, carrier pigeon).

Is there a way I could somehow tap into what TCP is passing down to the IP layer?

Thanks,
Fidel

Edit:

I want a reliable protocol (eg. TCP) which can pump data into a stream, and read data from a stream, without knowing exactly how the stream transports that data.

I have explicit control over that stream. I just need TCP to send information to that stream instead of its regular underlying layer.

答:
There was an experiment run to get TCP working with Pigeons.
Recently there also was an experiment using Humans and Xylophones.</p>

ContentLicense: CC BY-SA 2.5

Title: tcp/ip without ip in .net


问:
Loading two different SQL tables in a single JSP file using spring + hibernate
Sorry, I edited my post due to a misleading error i posted.

I have two tables on MySQL and I am trying to display both of them in a single JSP page.

I am using @RequestMapping to try to achieve this.

```<code>@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listFolders(Model model) {
    model.addAttribute("folders", new Folders());
    model.addAttribute("listFolders", this.foldersService.listFolders());
    return "person"; //name of the jsp page
}

@RequestMapping(value = "/folders", method = RequestMethod.GET)
public String listPersons(Model model) {
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person"; //name of the jsp page
}
</code>```

I need to show both tables in the same JSP page, but if i try to access /folders i get erros because it wont recognise the person table.

actions in my JSP file:

```<code><c:if test="${!empty listPersons}">
<table class="tg">
<tr>
    <th width="80">Person ID</th>
    <th width="120">Person Name</th>
    <th width="120">Person Country</th>
</tr>
<c:forEach items="${listPersons}" var="person">
    <tr>
        <td>${person.id} </td>
        <td>${person.name}</td>
        <td>${person.country}</td>

    </tr>
</c:forEach>
</table>
</code>```

And:

```<code>    <c:if test="${!empty listFolders}">
<table class="tg">
<tr>
    <th width="80">Folders ID</th>
    <th width="120">Folders Parent</th>
</tr>
<c:forEach items="${listFolders}" var="person">
    <tr>
        <td>${folders.id} </td>
        <td>${folders.parent}</td>
    </tr>
</c:forEach>
</table>
</code>```

Erros:

```<code>Jun 06, 2017 5:53:07 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/CitelumApp] threw exception [java.lang.IllegalStateException: Neither
BindingResult nor plain target object for bean name 'person' available as
request attribute] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'person' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>
</code>```

My question is:
Is there a way to display two different SQL tables on the same JSP page?

答:
a route is specified for one action. so you can not use @RequestMapping(value = "/persons", method = RequestMethod.GET) twice with the same value. please change persons to folders for example on listOfFolders.

```<code>@RequestMapping(value = "/folder", method = RequestMethod.GET)
</code>```

Body:
Sorry, I edited my post due to a misleading error i posted.

I have two tables on MySQL and I am trying to display both of them in a single JSP page.

I am using @RequestMapping to try to achieve this.

@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listFolders(Model model) {
    model.addAttribute("folders", new Folders());
    model.addAttribute("listFolders", this.foldersService.listFolders());
    return "person"; //name of the jsp page
}

@RequestMapping(value = "/folders", method = RequestMethod.GET)
public String listPersons(Model model) {
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person"; //name of the jsp page
}

I need to show both tables in the same JSP page, but if i try to access /folders i get erros because it wont recognise the person table.

actions in my JSP file:

<c:if test="${!empty listPersons}">

    Person ID
    Person Name
    Person Country

<c:forEach items="${listPersons}" var="person">

        ${person.id}
        ${person.name}
        ${person.country}

</c:forEach>

And:

    <c:if test="${!empty listFolders}">

    Folders ID
    Folders Parent

<c:forEach items="${listFolders}" var="person">

        ${folders.id}
        ${folders.parent}

</c:forEach>

Erros:

Jun 06, 2017 5:53:07 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/CitelumApp] threw exception [java.lang.IllegalStateException: Neither
BindingResult nor plain target object for bean name 'person' available as
request attribute] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'person' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>

My question is:
Is there a way to display two different SQL tables on the same JSP page?

Body:
a route is specified for one action. so you can not use @RequestMapping(value = "/persons", method = RequestMethod.GET) twice with the same value. please change persons to folders for example on listOfFolders.

@RequestMapping(value = "/folder", method = RequestMethod.GET)


问:
How do I execute a Java/Python program multiple times?
I am currently working on an assignment, where the task is to measure the execution time for a number of programs in both Python and Java, for the purpose of measuring and comparing performance for the two computer languages. I have 10 tests in total, in sets of 2; for every set, one test is written in Java and the corresponding one is written in Python, and so forth. I want to run every test multiple times, e.g. 100 times, and measure the time for every run. Then I'd like to compute the sum of the obtained execution time(s). How would I do this in Python/Java? I have tried writing a double for-loop like this:

```<code>for i in range(1, 100):
for j in range(1, 10000000):
# do integer division
</code>```

...but it doesn't seem to work. Also I'd like to do the same thing in Java. How would I do this?

答:
```<code>import time

for i in range(1,101):
    start = time.time()
    # do your thing
    print(int(time.time() - start))
</code>```

starts=time.time() starts the counter. and then print(int(time.time() - start)) will return the time taken in seconds.

For reference, use 101 in range(). the second paramter to range() is a "go up to" and not an include

Body:
I am currently working on an assignment, where the task is to measure the execution time for a number of programs in both Python and Java, for the purpose of measuring and comparing performance for the two computer languages. I have 10 tests in total, in sets of 2; for every set, one test is written in Java and the corresponding one is written in Python, and so forth. I want to run every test multiple times, e.g. 100 times, and measure the time for every run. Then I'd like to compute the sum of the obtained execution time(s). How would I do this in Python/Java? I have tried writing a double for-loop like this:

for i in range(1, 100):
for j in range(1, 10000000):
# do integer division

...but it doesn't seem to work. Also I'd like to do the same thing in Java. How would I do this?

Body:
import time

for i in range(1,101):
    start = time.time()
    # do your thing
    print(int(time.time() - start))

starts=time.time() starts the counter. and then print(int(time.time() - start)) will return the time taken in seconds.

For reference, use 101 in range(). the second paramter to range() is a "go up to" and not an include


问:
Angular2: Make a child routing path equals to the Root routing path is a good solution?
To make my question clear, let me use some images.
This is my project structure:

Thinking about code reuse, I wrote one component like this:

And at my app.module.ts, I wrote the routings like this:

Because the Landing Page of my application is also the root of the free-area, I wrote its routing path like the root routing path, which means, I set it as blank.

The routing is working fine, but is this a good practice? How could I set up the path of the Landing Page if it is not a good practice?

答:
The code looks ok. you need to add </p>

```<code>{path: '**', redirect:'', pathMatch:'full'}
</code>```

Body:
The code looks ok. you need to add

{path: '**', redirect:'', pathMatch:'full'}


问:
jQuery .find() method - searching within string converted to jquery object

var myHTML = '

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

';

var obj = $(myHTML).get(0);
var totalCount = $(obj).find('.infoWindowParagraph').length;

console.log('Total p.infoWindowParagraph tags in the FIRST mapInfoWindow div is : ' + totalCount);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

So I have a HTML string that is similar to the following, and I'm trying to get a count of the .infoWindowParagraph tags in the FIRST .mapInfoWindow div.  For whatever reason, it's not working as I expect and I'm not sure why.

HTML

```<code><div class="mapInfoWindow">
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
</div>
<div class="mapInfoWindow">
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
</div>
<div class="mapInfoWindow">
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
    <p class="infoWindowParagraph">DATA HERE</p>
</div>
</code>```

jQuery/JavaScript

```<code>var testObj = $([string from above]);
console.log(testObj.find('.mapInfoWindow').find('.infoWindowParagraph').length);

-- returns 0 every time should return 4
-- also tried below trying to focus on first index (first instance of mapInfoWindow div in object returned)

var testObj = $([string from above]).get(0).find('.infoWindowParagraph').length);

-- still returns 0
</code>```

update

Well damn, I got it working now.  Sorry SO for the time-wasting here, overlooked the obvious!

答:
You can try this:

var testObj = '

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

';

console.log($(testObj).first('.mapInfoWindow').children('.infoWindowParagraph').length);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
var myHTML = '

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

';

var obj = $(myHTML).get(0);
var totalCount = $(obj).find('.infoWindowParagraph').length;

console.log('Total p.infoWindowParagraph tags in the FIRST mapInfoWindow div is : ' + totalCount);

So I have a HTML string that is similar to the following, and I'm trying to get a count of the .infoWindowParagraph tags in the FIRST .mapInfoWindow div.  For whatever reason, it's not working as I expect and I'm not sure why.

HTML

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

DATA HERE

jQuery/JavaScript

var testObj = $([string from above]);
console.log(testObj.find('.mapInfoWindow').find('.infoWindowParagraph').length);

-- returns 0 every time should return 4
-- also tried below trying to focus on first index (first instance of mapInfoWindow div in object returned)

var testObj = $([string from above]).get(0).find('.infoWindowParagraph').length);

-- still returns 0

update

Well damn, I got it working now.  Sorry SO for the time-wasting here, overlooked the obvious!

Body:
You can try this:

var testObj = '<div class="mapInfoWindow"><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p></div><div class="mapInfoWindow"><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p></div><div class="mapInfoWindow"><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p><p class="infoWindowParagraph">DATA HERE</p></div>';

console.log($(testObj).first('.mapInfoWindow').children('.infoWindowParagraph').length);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Why does my code thinks that 60 is bigger than 135?

i want to get the bigger number and subtract by the smaller number (input's value) even tho they are in the wrong order when you put them into the input like -1 = inputX / 1 = inputY then 1 = greater and -1 smaller, it works with other numbers, but these kinda break it idk why tho what did I do wrong?
  why does it think 60 is bigger than 135? look at the img...

```<code><script type="text/javascript">
var x;
var y;
var big;
var small;
var result;
function calcT() {
    x = document.getElementById("inputX").value;
    y = document.getElementById("inputY").value;
    //result = x - y;
    if(x > y) {
      big = x;
      small = y;
       } else if(x < y) {
      big = y;
      small = x;
       }
    result = parseInt(big) - parseInt(small);
    document.getElementById("resultHere").innerHTML = result;

}
</code>```

答:
Please parse to integer your inputX and inputY before comparing.

It is treating inputX and inputY as string.

so '135' > '65' is false &&
'65' > '135' is true.

```<code> var x; var y; var big; var small; var result;
function calcT() {
 x = document.getElementById("inputX").value;
 y = document.getElementById("inputY").value; //result = x - y;
 x= parseInt(x); // Missing point <--
 y= parseInt(y); // Missing point <--
 if(x > y) { big = x; small = y;
 } else if(x < y) {
 big = y; small = x; }
 result = big - small;
 document.getElementById("resultHere").innerHTML = result;
</code>```

}

Body:
Please parse to integer your inputX and inputY before comparing.

It is treating inputX and inputY as string.

so '135' > '65' is false &&
'65' > '135' is true.

 var x; var y; var big; var small; var result;
function calcT() {
 x = document.getElementById("inputX").value;
 y = document.getElementById("inputY").value; //result = x - y;
 x= parseInt(x); // Missing point <--
 y= parseInt(y); // Missing point <--
 if(x > y) { big = x; small = y;
 } else if(x < y) {
 big = y; small = x; }
 result = big - small;
 document.getElementById("resultHere").innerHTML = result;

}


问:
Server A using xmlreader to read XML from xmlwriter on server B
I have two servers

Server A reads http://www.some-url.com/xmlwriter_src.php using

```<code>$reader = new XMLReader();
$reader->open('http://www.some-url.com/xmlwriter_src.php');
while ($reader->read())
{
  /* -- do something -- */
}
</code>```

Server B creates an xml stream

```<code>$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument("1.0");

$writer->startElement("records");
while(!$recordset->EOF)
{
  $writer->startElement($fieldname)
  $writer->text($recordset->fields[$fieldname]);
  $writer->endElement();
  $recordset->movenext();
}
</code>```

the xmlreader on server A keeps complaining that server B doesnt respond, even though I can see the xml result in the browser.

It takes less than a second to generate

If i copy the xml to a static file, the xmlreader outputs the file.

答:
Try writing whatever xmlReader reads on the disk and inspect the generated file. I have a hunch its either empty or invalid(incomplete) XML.
If i'm right, then you might have a timeout that expires sooner than the one you get in a real browser. Either that, or a connection that requires either connection-close or keepalive(i've seen servers broken like this).

Also, make sure you dont have a firewall on the server where the client runs that might block the xmlReader from talking to the xmlWriter:) Try iptables -L in the server console to check any firewall rules.

Edit: you might also need to call something like xmlReader->close(), or end() or whatever member you got there that closes the connection and signals the client that the transmission is over.

Body:
I have two servers

Server A reads http://www.some-url.com/xmlwriter_src.php using

$reader = new XMLReader();
$reader->open('http://www.some-url.com/xmlwriter_src.php');
while ($reader->read())
{
  /* -- do something -- */
}

Server B creates an xml stream

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument("1.0");

$writer->startElement("records");
while(!$recordset->EOF)
{
  $writer->startElement($fieldname)
  $writer->text($recordset->fields[$fieldname]);
  $writer->endElement();
  $recordset->movenext();
}

the xmlreader on server A keeps complaining that server B doesnt respond, even though I can see the xml result in the browser.

It takes less than a second to generate

If i copy the xml to a static file, the xmlreader outputs the file.


问:
PyQt 4 extracting all information from a QTableWidget into a Pandas Dataframe
I am wondering whether it is possible to extract all the data from a QTableWidget into a Pandas Dataframe.

At the moment I can only find information of how to extract information into a QTableView.

I understand that the QTable view is inherited by the QTableWidget but when I adapt the above solution with the code below it returns the error that 'QTableWidget' object has no attribute 'index'. I have not found any information of how to convert the QTableWidget into a QTableView

```<code>data = []
        for row in range(QtGui.QTableWidget.rowCount()):
          data.append([])
          for column in range(QtGui.QTableWidget.columnCount()):
            index = QtGui.QTableWidget.index(row, column)
            data[row].append(str(QtGui.QTableWidget.data(index).toString()))
</code>```

My end goal is to get the data into a Pandas dataframe which I think will be easy once the data list is populated; however I would be interested to know if there is a more direct approach to achieve this.

答:
Ok so I was able to put it into a dataset using: </p>

```<code>    data = []
    for row in allRows:
        newRow = []
        for column in xrange(8):
            newRow.append(str(QtGui.QTableWidget.item(row,column).text()))
        data.append(newRow)
</code>```

<p>This creates a new nested list with each item in the list representing a column in the row. </p>

Body:
I am wondering whether it is possible to extract all the data from a QTableWidget into a Pandas Dataframe.

At the moment I can only find information of how to extract information into a QTableView.

I understand that the QTable view is inherited by the QTableWidget but when I adapt the above solution with the code below it returns the error that 'QTableWidget' object has no attribute 'index'. I have not found any information of how to convert the QTableWidget into a QTableView

data = []
        for row in range(QtGui.QTableWidget.rowCount()):
          data.append([])
          for column in range(QtGui.QTableWidget.columnCount()):
            index = QtGui.QTableWidget.index(row, column)
            data[row].append(str(QtGui.QTableWidget.data(index).toString()))

My end goal is to get the data into a Pandas dataframe which I think will be easy once the data list is populated; however I would be interested to know if there is a more direct approach to achieve this.

Body:
Ok so I was able to put it into a dataset using:

    data = []
    for row in allRows:
        newRow = []
        for column in xrange(8):
            newRow.append(str(QtGui.QTableWidget.item(row,column).text()))
        data.append(newRow)

This creates a new nested list with each item in the list representing a column in the row.


答:
This does not work because T cannot be represented as some type that is at the intersection of String, Number, and Boolean.

If you want to restrict your type to a list of predefined types, sealed classes are a great soltuion.

```<code>sealed class MyData {
  class Bool(val data: Boolean) : MyData()
  class String(val data: String) : MyData()
  class Number(val data: Number) : MyData()
}

fun get(key: String): MyData = TODO()
</code>```

Title: How to represent multiple types (union types) when targeting JavaScript

Body:
What I would like to do is use a generic type that can be one of three other types.

Here's an example with a function:

fun <T> get(key: String) : T where T: String, T: Number, T: Boolean {}

The above code doesn't work, so how should I go about doing this?

Body:
This does not work because T cannot be represented as some type that is at the intersection of String, Number, and Boolean.

If you want to restrict your type to a list of predefined types, sealed classes are a great soltuion.

sealed class MyData {
  class Bool(val data: Boolean) : MyData()
  class String(val data: String) : MyData()
  class Number(val data: Number) : MyData()
}

fun get(key: String): MyData = TODO()


问:
Querying an SQL file into CSV
I have a SQL file with the following info:

```<code>CREATE TABLE 'people' (
'id' int(11) UNSIGNED NOT NULL,
'email' varchar(255) DEFAULT NULL,
'name' varchar(255) DEFAULT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO 'people' ('id', 'email', 'name') VALUES
(1, 'a@gmail.com', 'john doe'),
(2, 'b@gmail.com', 'jane doe'),
...
(1000, 'x@gmail.com', 'big cat');
</code>```

How can I query this people.sql file with a list of emails (one per line) in a text file and write the email and name pairings to a new csv?

答:
Like this: </p>

```<code>import pymysql.cursors
import pandas as pd

connection = pymysql.connect(host='DB_IP_or_localhost',
                             user='myUser',
                             password='myPassword',
                             db='InnoDB',
                             cursorclass=pymysql.cursors.DictCursor)

with connection.cursor() as cursor:
    sql = "SELECT email, name FROM people"
    df = pd.read_sql(sql, connection)
connection.close()

df.to_csv("people.csv", encoding="utf-8")
</code>```

Title: Querying an SQL file into CSV

Body:
I have a SQL file with the following info:

CREATE TABLE 'people' (
'id' int(11) UNSIGNED NOT NULL,
'email' varchar(255) DEFAULT NULL,
'name' varchar(255) DEFAULT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO 'people' ('id', 'email', 'name') VALUES
(1, 'a@gmail.com', 'john doe'),
(2, 'b@gmail.com', 'jane doe'),
...
(1000, 'x@gmail.com', 'big cat');

How can I query this people.sql file with a list of emails (one per line) in a text file and write the email and name pairings to a new csv?

Body:
Like this:

import pymysql.cursors
import pandas as pd

connection = pymysql.connect(host='DB_IP_or_localhost',
                             user='myUser',
                             password='myPassword',
                             db='InnoDB',
                             cursorclass=pymysql.cursors.DictCursor)

with connection.cursor() as cursor:
    sql = "SELECT email, name FROM people"
    df = pd.read_sql(sql, connection)
connection.close()

df.to_csv("people.csv", encoding="utf-8")


问:
PyPDF2 returning blank PDF after copy
```<code>def EncryptPDFFiles(password, directory):
    pdfFiles = []
    success = 0

    # Get all PDF files from a directory
    for folderName, subFolders, fileNames in os.walk(directory):
        for fileName in fileNames:
            if (fileName.endswith(".pdf")):
                pdfFiles.append(os.path.join(folderName, fileName))
    print("%s PDF documents found." % str(len(pdfFiles)))

    # Create an encrypted version for each document
    for pdf in pdfFiles:
        # Copy old PDF into a new PDF object
        pdfFile = open(pdf,"rb")
        pdfReader = PyPDF2.PdfFileReader(pdfFile)
        pdfWriter = PyPDF2.PdfFileWriter()
        for pageNum in range(pdfReader.numPages):
            pdfWriter.addPage(pdfReader.getPage(pageNum))
        pdfFile.close()

        # Encrypt the new PDF and save it
        saveName = pdf.replace(".pdf",ENCRYPTION_TAG)
        pdfWriter.encrypt(password)
        newFile = open(saveName, "wb")
        pdfWriter.write(newFile)
        newFile.close()
        print("%s saved to: %s" % (pdf, saveName))

        # Verify the the encrypted PDF encrypted properly
        encryptedPdfFile = open(saveName,"rb")
        encryptedPdfReader = PyPDF2.PdfFileReader(encryptedPdfFile)
        canDecrypt = encryptedPdfReader.decrypt(password)
        encryptedPdfFile.close()
        if (canDecrypt):
            print("%s successfully encrypted." % (pdf))
            send2trash.send2trash(pdf)
            success += 1

    print("%s of %s successfully encrypted." % (str(success),str(len(pdfFiles))))
</code>```

I am following along with Pythons Automate the Boring Stuff section. I've had off and on issues when doing the copy for a PDF document but as of right now everytime I run the program my copied PDF is all blank pages. There are the correct amount of pages of my newly encrypted PDF but they are all blank (no content on the pages). I've had this happen before but was not able to recreate. I've tried throwing in a sleep before closing my files. I'm not sure what the best practice for opening and closing files are in Python. For reference I'm using Python3.

答:
Try moving the pdfFile.close to the very end of your for loop.

```<code>for pdf in pdfFiles:
    #
    # {stuff}
    #
    if (canDecrypt):
        print("%s successfully encrypted." % (pdf))
        send2trash.send2trash(pdf)
        success += 1

    pdfFile.close()
</code>```

The thought is that the pdfFile needs to be available and open when the pdfWriter finally writes out, otherwise it cannot access the pages to write the new file.

Title: PyPDF2 returning blank PDF after copy

Body:
def EncryptPDFFiles(password, directory):
    pdfFiles = []
    success = 0

    # Get all PDF files from a directory
    for folderName, subFolders, fileNames in os.walk(directory):
        for fileName in fileNames:
            if (fileName.endswith(".pdf")):
                pdfFiles.append(os.path.join(folderName, fileName))
    print("%s PDF documents found." % str(len(pdfFiles)))

    # Create an encrypted version for each document
    for pdf in pdfFiles:
        # Copy old PDF into a new PDF object
        pdfFile = open(pdf,"rb")
        pdfReader = PyPDF2.PdfFileReader(pdfFile)
        pdfWriter = PyPDF2.PdfFileWriter()
        for pageNum in range(pdfReader.numPages):
            pdfWriter.addPage(pdfReader.getPage(pageNum))
        pdfFile.close()

        # Encrypt the new PDF and save it
        saveName = pdf.replace(".pdf",ENCRYPTION_TAG)
        pdfWriter.encrypt(password)
        newFile = open(saveName, "wb")
        pdfWriter.write(newFile)
        newFile.close()
        print("%s saved to: %s" % (pdf, saveName))

        # Verify the the encrypted PDF encrypted properly
        encryptedPdfFile = open(saveName,"rb")
        encryptedPdfReader = PyPDF2.PdfFileReader(encryptedPdfFile)
        canDecrypt = encryptedPdfReader.decrypt(password)
        encryptedPdfFile.close()
        if (canDecrypt):
            print("%s successfully encrypted." % (pdf))
            send2trash.send2trash(pdf)
            success += 1

    print("%s of %s successfully encrypted." % (str(success),str(len(pdfFiles))))

I am following along with Pythons Automate the Boring Stuff section. I've had off and on issues when doing the copy for a PDF document but as of right now everytime I run the program my copied PDF is all blank pages. There are the correct amount of pages of my newly encrypted PDF but they are all blank (no content on the pages). I've had this happen before but was not able to recreate. I've tried throwing in a sleep before closing my files. I'm not sure what the best practice for opening and closing files are in Python. For reference I'm using Python3.

Body:
Try moving the pdfFile.close to the very end of your for loop.

for pdf in pdfFiles:
    #
    # {stuff}
    #
    if (canDecrypt):
        print("%s successfully encrypted." % (pdf))
        send2trash.send2trash(pdf)
        success += 1

    pdfFile.close()

The thought is that the pdfFile needs to be available and open when the pdfWriter finally writes out, otherwise it cannot access the pages to write the new file.


问:
Selecting images inside the table and inside the div
How do I select the images below (@div class="this") without selecting the images above so that I can style it with CSS?</p>

```<code><table>
    <tr>
        <td><a href="../index.html"><img src="../home.png"></a></td> <!-- GO BACK TO HOMEPAGE -->
        <td><a href="########"><img src="../artist.png"></a></td> <!-- GO TO ARTIST -->
        <td><img src="../portfolio.png"></td>
        <td><img src="../contact.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../logo.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../greenmoralesgraphic.png"></td>
    </tr>
    <tr><div class="this">
        <td><img src="nostalgia.jpg" width="400px" height="400px"></td>
        <td><img src="pwersa.jpg" width="400px" height="400px"></td>
        <td><img src="tag_along.jpg" width="400px" height="400px"></td>
        <td><img src="tweet.jpg" width="400px" height="400px"></td>
        </div>
    </tr>
</table>
</code>```

答:
Use

```<code>.this img{
  border:1px solid #ddd;
}
</code>```

This will select the images inside the class .this.The styles applied like  this  will apply only to the images inside the .this class . The space is known as  descendant combinator.Read about descendant combinator here

.this img{
  border:1px solid #f00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <tr>
        <td><img src="../home.png"></td> <!-- GO BACK TO HOMEPAGE -->
        <td><img src="../artist.png"></td> <!-- GO TO ARTIST -->
        <td><img src="../portfolio.png"></td>
        <td><img src="../contact.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../logo.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../greenmoralesgraphic.png"></td>
    </tr>
    <tr>
        <td>
          <div class="this"><img src="nostalgia.jpg" width="400px" height="400px">
          <img src="pwersa.jpg" width="400px" height="400px">
          <img src="tag_along.jpg" width="400px" height="400px">
          <img src="tweet.jpg" width="400px" height="400px">
         </div>
       </td>
       <td> </td>
        <td></td>
        <td></td>

    </tr>
</table></code>```

And Change div tag inside the tr

  .this img{
      border:1px solid #f00;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

    <table>
        <tr>
            <td><img src="../home.png"></td> <!-- GO BACK TO HOMEPAGE -->
            <td><img src="../artist.png"></td> <!-- GO TO ARTIST -->
            <td><img src="../portfolio.png"></td>
            <td><img src="../contact.png"></td>
        </tr>
        <tr>
            <td colspan="8"><img src="../logo.png"></td>
        </tr>
        <tr>
            <td colspan="8"><img src="../greenmoralesgraphic.png"></td>
        </tr>
        <tr>
            <td>
              <div class="this">
                <img src="nostalgia.jpg" width="400px" height="400px">
             </div>
           </td>
           <td>
             <div class="this">
                <img src="pwersa.jpg" width="400px" height="400px">
             </div>

           </td>
            <td>
             <div class="this">
               <img src="tag_along.jpg" width="400px" height="400px">
             </div>
            </td>
            <td>
              <div class="this">
                   <img src="tweet.jpg" width="400px" height="400px">
              </div>
            </td>

        </tr>
    </table></code>```

Body:
Use

.this img{
  border:1px solid #ddd;
}

This will select the images inside the class .this.The styles applied like  this  will apply only to the images inside the .this class . The space is known as  descendant combinator.Read about descendant combinator here

.this img{
  border:1px solid #f00;
}

<table>
    <tr>
        <td><a href="../index.html"><img src="../home.png"></a></td> <!-- GO BACK TO HOMEPAGE -->
        <td><a href="########"><img src="../artist.png"></a></td> <!-- GO TO ARTIST -->
        <td><img src="../portfolio.png"></td>
        <td><img src="../contact.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../logo.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../greenmoralesgraphic.png"></td>
    </tr>
    <tr>
        <td>
          <div class="this"><img src="nostalgia.jpg" width="400px" height="400px">
          <img src="pwersa.jpg" width="400px" height="400px">
          <img src="tag_along.jpg" width="400px" height="400px">
          <img src="tweet.jpg" width="400px" height="400px">
         </div>
       </td>
       <td> </td>
        <td></td>
        <td></td>

    </tr>
</table>

And Change div tag inside the tr

  .this img{
      border:1px solid #f00;
    }

    <table>
        <tr>
            <td><a href="../index.html"><img src="../home.png"></a></td> <!-- GO BACK TO HOMEPAGE -->
            <td><a href="########"><img src="../artist.png"></a></td> <!-- GO TO ARTIST -->
            <td><img src="../portfolio.png"></td>
            <td><img src="../contact.png"></td>
        </tr>
        <tr>
            <td colspan="8"><img src="../logo.png"></td>
        </tr>
        <tr>
            <td colspan="8"><img src="../greenmoralesgraphic.png"></td>
        </tr>
        <tr>
            <td>
              <div class="this">
                <img src="nostalgia.jpg" width="400px" height="400px">
             </div>
           </td>
           <td>
             <div class="this">
                <img src="pwersa.jpg" width="400px" height="400px">
             </div>

           </td>
            <td>
             <div class="this">
               <img src="tag_along.jpg" width="400px" height="400px">
             </div>
            </td>
            <td>
              <div class="this">
                   <img src="tweet.jpg" width="400px" height="400px">
              </div>
            </td>

        </tr>
    </table>


问:
How to express in JSON schema all or none for multiple optional properties?
I want to express that all or none of optional properties are present. For example

```<code>{
}
</code>```

and

```<code>{
    "a" : 1,
    "b" : 2
}
</code>```

should be both valid, but

```<code>{
    "a" : 1
}
</code>```

and

```<code>{
    "b" : 2
}
</code>```

should be both invalid.

答:
Here a schema that satisfies the requirements:

```<code>{
    "type": "object",
    "properties": {
        "a": {
            "type": "integer"
        },
        "b": {
            "type": "integer"
        }
    },
    "oneOf": [{
        "required": ["a", "b"]
    }, {
        "not": {
            "anyOf": [{
                "required": ["a"]
            }, {
                "required": ["b"]
            }]
        }
    }],
    "additionalProperties": false
}
</code>```

An alternative would be to also express in the JSON that the properties belong together like

```<code>{
    "parent": {
        "a": 1,
        "b": 2
    }
}
</code>```

where parent is either present or not and if present, then always has a and b:

```<code>{
    "type": "object",
    "properties": {
        "parent": {
            "type": "object",
            "properties": {
                "a": {
                    "type": "integer"
                },
                "b": {
                    "type": "integer"
                }
            },
            "required": ["a", "b"],
            "additionalProperties": false
        }

    },
    "additionalProperties": false
}
</code>```

Body:
I want to express that all or none of optional properties are present. For example

{
}

and

{
    "a" : 1,
    "b" : 2
}

should be both valid, but

{
    "a" : 1
}

and

{
    "b" : 2
}

should be both invalid.

Body:
Here a schema that satisfies the requirements:

{
    "type": "object",
    "properties": {
        "a": {
            "type": "integer"
        },
        "b": {
            "type": "integer"
        }
    },
    "oneOf": [{
        "required": ["a", "b"]
    }, {
        "not": {
            "anyOf": [{
                "required": ["a"]
            }, {
                "required": ["b"]
            }]
        }
    }],
    "additionalProperties": false
}

An alternative would be to also express in the JSON that the properties belong together like

{
    "parent": {
        "a": 1,
        "b": 2
    }
}

where parent is either present or not and if present, then always has a and b:

{
    "type": "object",
    "properties": {
        "parent": {
            "type": "object",
            "properties": {
                "a": {
                    "type": "integer"
                },
                "b": {
                    "type": "integer"
                }
            },
            "required": ["a", "b"],
            "additionalProperties": false
        }

    },
    "additionalProperties": false
}


问:
How to check whether a column contains only identical elements in R?
Example data:

```<code>x <- matrix(c("Stack","Stack","Stack",
              "Overflow","Overflow","wolfrevO"),
            nrow=3,ncol=2)
</code>```

How can I check whether x[,1] contains entirely identical elements?

If x contains NAs, does this method still apply?

Thanks

答:
A comparison of the proposed methods:

```<code>x <- rep(1, 1000)
x[5] <- 0

microbenchmark::microbenchmark(
  all(duplicated(x)),
  length(unique(x)) == 1,
  dim(table(x)) == 1,
  all(x == x[1]),
  times = 1000)

Unit: microseconds
                   expr      min       lq        mean   median       uq      max neval cld
     all(duplicated(x))   19.594   21.461   24.688356   22.861   24.727   74.646  1000  b
 length(unique(x)) == 1   21.461   23.793   26.972993   25.193   26.127  156.755  1000  b
     dim(table(x)) == 1 1067.422 1090.282 1144.309131 1123.872 1154.197 2072.795  1000   c
         all(x == x[1])    3.267    4.199    4.629929    4.200    4.666   22.394  1000 a
</code>```

x is a column or a row. Matrix, data.frame or similar per row or column equality testing can be done with:

```<code>all(apply(X, 1, function(x){all(x == x[1])}))
</code>```

Body:
Example data:

x <- matrix(c("Stack","Stack","Stack",
              "Overflow","Overflow","wolfrevO"),
            nrow=3,ncol=2)

How can I check whether x[,1] contains entirely identical elements?

If x contains NAs, does this method still apply?

Thanks

Body:
A comparison of the proposed methods:

x <- rep(1, 1000)
x[5] <- 0

microbenchmark::microbenchmark(
  all(duplicated(x)),
  length(unique(x)) == 1,
  dim(table(x)) == 1,
  all(x == x[1]),
  times = 1000)

Unit: microseconds
                   expr      min       lq        mean   median       uq      max neval cld
     all(duplicated(x))   19.594   21.461   24.688356   22.861   24.727   74.646  1000  b
 length(unique(x)) == 1   21.461   23.793   26.972993   25.193   26.127  156.755  1000  b
     dim(table(x)) == 1 1067.422 1090.282 1144.309131 1123.872 1154.197 2072.795  1000   c
         all(x == x[1])    3.267    4.199    4.629929    4.200    4.666   22.394  1000 a

x is a column or a row. Matrix, data.frame or similar per row or column equality testing can be done with:

all(apply(X, 1, function(x){all(x == x[1])}))


问:
diffuse shaders cause vertical lines in 2d maps
vertical line tear in-game

Greetings! I've been using tiled and tiled2unity to design and import my maps into Unity with no problem, as long as I stick to the default tiled2Unity shader or the sprites>default shader. However, I've been trying to implement lighting into the project and thus have to change the shaders to some form of diffuse. When I change the tiled maps shaders from anything other than the two mentioned above, I get these vertical lines between tiles. I took a screenshot of the problem and have linked it to this page (the line is above and to the right of the player). The problem is especially obvious when the camera moves. I tried sprites>diffuse, standard, and mobiles variants, all with the same vertical lines appearing. But when I turn it back to sprites>default or tiled2Unity>default, the problem disappears entirely (as long as I have pixel snap enabled). What is happening? I've scoured the internet and haven't found any solutions.

答: Found a solution: using extrusion the problem disappears. Sadly I'll have to use a paid program to do this else I'll have to do every tile/sprite myself.</p>


问:
What dependency/repository for maven-jaxb-plugin?
in my pom.xml I've configured maven-jaxb-plugin but I'm getting a "A required plugin was not found: Plugin could not be found - check that the goal name is correct: Unable to download the artifact from any repository" because of it. My config is like this:

```<code><plugin>
    <groupId>com.sun.tools.xjc.maven2</groupId>
    <artifactId>maven-jaxb-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <generate-package>tld.mycompany.myproject.data.ws-schema</generate-package>
        <schemaDirectory>src/main/resources/ws/xsd</schemaDirectory>
    </configuration>
</plugin>
</code>```

In dependencies, I have added the following.

```<code><dependency>
    <groupId>maven-plugins</groupId>
    <artifactId>maven-jaxb-plugin</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.5</version>
</dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-xjc</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2</version>
</dependency>
</code>```

What am I missing? Why can't it find the correct artifacts?

Cheers

Nik

答:
You can find version 0.7.3 on the Java.net maven repository:

http://download.java.net/maven/2/

Body:
in my pom.xml I've configured maven-jaxb-plugin but I'm getting a "A required plugin was not found: Plugin could not be found - check that the goal name is correct: Unable to download the artifact from any repository" because of it. My config is like this:

<plugin>
    <groupId>com.sun.tools.xjc.maven2</groupId>
    <artifactId>maven-jaxb-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <generate-package>tld.mycompany.myproject.data.ws-schema</generate-package>
        <schemaDirectory>src/main/resources/ws/xsd</schemaDirectory>
    </configuration>
</plugin>

In dependencies, I have added the following.

<dependency>
    <groupId>maven-plugins</groupId>
    <artifactId>maven-jaxb-plugin</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.5</version>
</dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-xjc</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2</version>
</dependency>

What am I missing? Why can't it find the correct artifacts?

Cheers

Nik


问:
Javascript - How do I replace all spaces that are only between a number and letter
```<code>"5 Teams 7 Players" ====> 5Teams 7Players
"7 Individuals 8 Teams 8 Categories" ====> 7Individuals 8Teams 8Categories
</code>```

答:
Try this pattern (\d+)(\s+)(\w+)

Demo regex

var a="5 Teams 7 Players";
var b="7 Individuals 8 Teams 8 Categories";

console.log(a.replace(/(\d+)(\s+)(\w+)/g,'$1$3'))
console.log(b.replace(/(\d+)(\s+)(\w+)/g,'$1$3'))```


问:
Where Can I find the detailed API for Uber Eats?
I could find the API for Uber Rush in https://developer.uber.com,  but not for Uber EATS, where would this information lie?</p>

答:
There is not currently a publicly available API for UberEATS. Any news on that front would be announced on the Uber API developers blog.

Also, for non-technical or non-coding questions like these about Uber's API, it might be better to follow up with them directly on their community forum, rather than on StackOverflow. Thanks!


问:
How to remove duplicate values from dict?
I'm trying to remove duplicate values in my dict but its not working:

```<code>samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.iteritems():
      if value not in samples_antibiotics.values():
        samples_antibiotics[key] = value
print samples_antibiotics
</code>```

This prints:

```<code>{'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
</code>```

答:
There are better ways to do this as seen in the other posts. But to retain as much of your original code as possible while explaining why it doesn't work use this instead:

```<code>samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
for key,value in samples_antibiotics_with_duplicates.items():
    samples_antibiotics[key] = set(value)
print(samples_antibiotics)
</code>```

The problem is that you iterate through each key in the dictionary in your for loop (so only the 'S00541-09') and then you check if the value is in the values (which obviously it has to be). What I did was essentially iterate the values within the key itself.

Body:
I'm trying to remove duplicate values in my dict but its not working:

samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.iteritems():
      if value not in samples_antibiotics.values():
        samples_antibiotics[key] = value
print samples_antibiotics

This prints:

{'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}

Body:
There are better ways to do this as seen in the other posts. But to retain as much of your original code as possible while explaining why it doesn't work use this instead:

samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
samples_antibiotics = {}
for key,value in samples_antibiotics_with_duplicates.items():
    samples_antibiotics[key] = set(value)
print(samples_antibiotics)

The problem is that you iterate through each key in the dictionary in your for loop (so only the 'S00541-09') and then you check if the value is in the values (which obviously it has to be). What I did was essentially iterate the values within the key itself.


问:
Sort dates in descending order
I want to sort my object that has dates in descending order. Here is the code I use in my fragment -

```<code>int pos = adapter.contains(status.id);
if (pos == -1) {
    myobj = new MyAdapter.Mymyobj();
    myobj.status = status;
    adapter.addItem(myobj);
} else {
    myobj = adapter.getItem(pos);
    myobj.status = status;
}
convertStringToDate(myobj.status.getTimeInString());
sortDates.add(convertedDate);
Comparator<Date> cmp = Collections.reverseOrder(null);
Collections.sort(sortDates, cmp);

adapter.notifyDataSetChanged();

private Date convertStringToDate(final String dateString) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM. HH:mm");
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return convertedDate;
}
</code>```

The above code is not working..Nothing is happening actually. I want the list to be in descending order.
Should I do something in adapter as well?

答:
Your code as given either is incomplete or has compile errors that make it impossible to answer.

However, for one thing, I must ask why you think it necessary to convert dates to strings just to sort them, when the standard Date class already implements Comparable?

For another, your convertDateToString() method catches DateParseException and prints them where no user will see them, and carries on as though nothing had happened, which would probably cause an NPE later in the code.

Title: Sort dates in descending order

Body:
I want to sort my object that has dates in descending order. Here is the code I use in my fragment -

int pos = adapter.contains(status.id);
if (pos == -1) {
    myobj = new MyAdapter.Mymyobj();
    myobj.status = status;
    adapter.addItem(myobj);
} else {
    myobj = adapter.getItem(pos);
    myobj.status = status;
}
convertStringToDate(myobj.status.getTimeInString());
sortDates.add(convertedDate);
Comparator<Date> cmp = Collections.reverseOrder(null);
Collections.sort(sortDates, cmp);

adapter.notifyDataSetChanged();

private Date convertStringToDate(final String dateString) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM. HH:mm");
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return convertedDate;
}

The above code is not working..Nothing is happening actually. I want the list to be in descending order.
Should I do something in adapter as well?


问:
Angular 4: access template element in other component
I'm using Angular 4. I'm trying to access one component's template element inside another component. The only thing I've found that works (illustrated below) is not very 'Angular'.

Component #1 (which contains the template):

```<code>  @Component({
    template: `...<input type="text" id="txtUserName" />`
</code>```

Component #2 (which is getting the above component's template element value in a click event):

```<code>  (<HTMLInputElement>document.getElementById('txtUserName')).value;
</code>```

I've found countless snippets on ElementRef, ViewChild, etc., but none of them actually work for getting the template element's value.
Does anyone know of an Angular 4 approach that accomplishes the same thing I'm doing above?

答:
You can do this with FormGroups in Angular 4.

Component A

FormGroups allow you to define the form elements as features of the form, and then attach that description to a form.

Inside the Component A constructor

```<code> public constructor(build: FormBuilder) {
     this.form = build.group({
         username: build.control('')
     });
 }
</code>```

You can now use that form group in your template.

```<code><form [formGroup]="form">
    <component-b></component-b>
</form>
</code>```

If you place your child component inside a <form> that is using the FormGroup you can then access the control via dependency injection.

Component B

You can access the FormGroup via the directive in the constructor like this.

```<code>public constructor(public formGroupDir: FormGroupDirective) {
}
</code>```

You have to wait until your component is ready to access the username control.

```<code>public ngAfterContentInit(): void {
    let formGroup = this.formGroupDir.form;
    this.control = formGroup.get('username');
}
</code>```

In the child template you can now bind the input to the form group control.

```<code><input type="text" [formControl]="control"/>
</code>```

You are all set now. Component A will receive form change notifications from the child component via the FormGroup events.

Body:
I'm using Angular 4. I'm trying to access one component's template element inside another component. The only thing I've found that works (illustrated below) is not very 'Angular'.

Component #1 (which contains the template):

  @Component({
    template: `...<input type="text" id="txtUserName" />`

Component #2 (which is getting the above component's template element value in a click event):

  (<HTMLInputElement>document.getElementById('txtUserName')).value;

I've found countless snippets on ElementRef, ViewChild, etc., but none of them actually work for getting the template element's value.
Does anyone know of an Angular 4 approach that accomplishes the same thing I'm doing above?

Body:
You can do this with FormGroups in Angular 4.

Component A

FormGroups allow you to define the form elements as features of the form, and then attach that description to a form.

Inside the Component A constructor

 public constructor(build: FormBuilder) {
     this.form = build.group({
         username: build.control('')
     });
 }

You can now use that form group in your template.

<form [formGroup]="form">
    <component-b></component-b>
</form>

If you place your child component inside a <form> that is using the FormGroup you can then access the control via dependency injection.

Component B

You can access the FormGroup via the directive in the constructor like this.

public constructor(public formGroupDir: FormGroupDirective) {
}

You have to wait until your component is ready to access the username control.

public ngAfterContentInit(): void {
    let formGroup = this.formGroupDir.form;
    this.control = formGroup.get('username');
}

In the child template you can now bind the input to the form group control.

<input type="text" [formControl]="control"/>

You are all set now. Component A will receive form change notifications from the child component via the FormGroup events.


问:
Canvas tag in Drupal 8
I want to ask does anybody knows if there exists a canvas html tag in Drupal 8?

Im trying to make signature form field so I need a canvas. Is there anyway to render custom HTML in Drupal 8 module?

Thanks.

答:
Canvas tag exists in Drupal 8. To use canvas in your code you need to use html_tag type. I wrote the following to create a canvas in my form. You can find the documentation at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21HtmlTag.php/class/HtmlTag/8.2.x.

I hope this works for you.

```<code>$form['canvas']=array(
      '#type' => 'html_tag',
      '#tag' => 'canvas',
      '#attributes' => array(
                    'style'=>'border: 1px solid #000000;
                              width: 200;
                              height: 100;'
                            ),
      );
</code>```

Title: Canvas tag in Drupal 8

Body:
Canvas tag exists in Drupal 8. To use canvas in your code you need to use html_tag type. I wrote the following to create a canvas in my form. You can find the documentation at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21HtmlTag.php/class/HtmlTag/8.2.x.

I hope this works for you.

$form['canvas']=array(
      '#type' => 'html_tag',
      '#tag' => 'canvas',
      '#attributes' => array(
                    'style'=>'border: 1px solid #000000;
                              width: 200;
                              height: 100;'
                            ),
      );


问:
Conditional statement for Excel VBA code
I need a little help.  Let's start with the code:

```<code>Range("a1").AutoFilter Field:=1, Criteria1:="W1793-PAS (Agency)"
'exclude 1st row (titles)
With Intersect(Range("a1").CurrentRegion, _
               Range("2:60000")).SpecialCells(xlCellTypeVisible)
    .Rows.Delete
End With
ActiveSheet.ShowAllData
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False
</code>```

I need to create a conditional statement for the above code that will stop the procedure if there is no text matching Criteria1 (W1793-PAS (Agency)).  I don't want this to run if there is no rows with W1793-PAS (Agency) in it.

答:
Simply check if the Autofilter is returning anything or not by storing the
 filtered range in a Range object and then delete it

```<code>Dim rng As Range

'Remove any filters
ActiveSheet.AutoFilterMode = False

With Range("A1")
  .AutoFilter Field:=1, Criteria1:="W1793-PAS (Agency)"
  '~~> Set this here
  Set rng = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With

'Remove any filters
ActiveSheet.AutoFilterMode = False

'~~> Check if there were any filtered results and then delete
If Not rng Is Nothing Then rng.Delete
</code>```

Body:
I need a little help.  Let's start with the code:

Range("a1").AutoFilter Field:=1, Criteria1:="W1793-PAS (Agency)"
'exclude 1st row (titles)
With Intersect(Range("a1").CurrentRegion, _
               Range("2:60000")).SpecialCells(xlCellTypeVisible)
    .Rows.Delete
End With
ActiveSheet.ShowAllData
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False

I need to create a conditional statement for the above code that will stop the procedure if there is no text matching Criteria1 (W1793-PAS (Agency)).  I don't want this to run if there is no rows with W1793-PAS (Agency) in it.

Body:
Simply check if the Autofilter is returning anything or not by storing the
 filtered range in a Range object and then delete it

Dim rng As Range

'Remove any filters
ActiveSheet.AutoFilterMode = False

With Range("A1")
  .AutoFilter Field:=1, Criteria1:="W1793-PAS (Agency)"
  '~~> Set this here
  Set rng = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With

'Remove any filters
ActiveSheet.AutoFilterMode = False

'~~> Check if there were any filtered results and then delete
If Not rng Is Nothing Then rng.Delete


问:
Why does my code thinks that 60 is bigger than 135?

i want to get the bigger number and subtract by the smaller number (input's value) even tho they are in the wrong order when you put them into the input like -1 = inputX / 1 = inputY then 1 = greater and -1 smaller, it works with other numbers, but these kinda break it idk why tho what did I do wrong?
  why does it think 60 is bigger than 135? look at the img...

```<code><script type="text/javascript">
var x;
var y;
var big;
var small;
var result;
function calcT() {
    x = document.getElementById("inputX").value;
    y = document.getElementById("inputY").value;
    //result = x - y;
    if(x > y) {
      big = x;
      small = y;
       } else if(x < y) {
      big = y;
      small = x;
       }
    result = parseInt(big) - parseInt(small);
    document.getElementById("resultHere").innerHTML = result;

}
</code>```

答: You are comparing the values directly - this results in comparing the text '135' with the text '60'. Show should instead compare the integer values of your inputs - e. g. convert the inputs to number before the if statement using parseInt(...).</p>


答:
if you are trying to add css to all of the images you can in your css call it like this :

.this {

*css styles here *

}

Title: Selecting images inside the table and inside the div

Body: How do I select the images below (@div class="this") without selecting the images above so that I can style it with CSS?


问:
Setting constants in golang outside of function as how it's done in Python
In Python, we can declare any variable outside of a function. We can simply call

a = 'a string' or b = ['asd', 'sdf', 'dfg']

I'm learning golang and would like to do the same to simply create a variable and assign values to it.

Do I have to do it inside a func? does it have to be in func main?

so far I have

```<code>func main() {

  var A_LIST []string
  A_LIST = append(A_LIST, "str1", "str2")

  var B_LIST []string
  B_LIST = append(B_LIST, "str3", "str4")
}
</code>```

which can build and I can print out the two variables if I write a fmt.Println

but if I want to build this into a .so file so my python scripts can import it, is this the right thing to do?

EDIT (UPDATE): following the suggestion and writing out some code to explain what I'm intending to do

I want to have several lists to categorize my tags. In Python, it would look like:

```<code>tag_category1 = ['tag1', 'tag2', 'tag3']
tag_category2 = ['tag4', 'tag5', 'tag6']
</code>```

The function would take in a list of tags and categorize them.

```<code>tags = ['tag1', 'tag3', 'tag6', 'tag7']
new_tags = {}
for tag in tags:
    if tag in tag_category1:
        new_tag['category1'].append(tag)
    elif tag in tag_category2:
        new_tag['category2'].append(tag)
    else:
        new_tag['others'].append(tag)
return new_tags
</code>```

so the result should be

```<code>new_tags = {
    'category1': ['tag1', 'tag3'],
    'category2': ['tag6'],
    'others':['tag7']
}
</code>```

I wanna write this function in go, and, since this function was originally used in another python script, I want to be able to import it. For that python script, I still have issue finding some util libraries i use in go, so I have to remain using python.

答:
No, you don't have to declare variables inside a function. Though, you can't use append because append is a non-declaration statement, which you can't use outside a function. Instead, you can declare your variables using literals, in this case a slice literal, ie:

```<code>var A_LIST = []string{"str1", "str2"}
</code>```

You can see an example of this in the crypto.go package, beginning on line 42:

```<code>var digestSizes = []uint8{
    MD4:        16,
    ... //omitted for this post
    RIPEMD160:  20,
</code>```

}

See that it works in the playground

If you need to do more then just hard-code the values, this approach doesn't seem very viable. For anything more dynamic, you will need a function. This could be an init() function, main(), or any other function, as long as you are conscious of the scope of the variable when/where you declare it, and the order in which the variables/functions will be initialised/called.

Regarding the .so file and the appropriate place to declare these variable, I don't know. Try different ways and see what does/doesn't work, then try to figure out why.

Body:
In Python, we can declare any variable outside of a function. We can simply call

a = 'a string' or b = ['asd', 'sdf', 'dfg']

I'm learning golang and would like to do the same to simply create a variable and assign values to it.

Do I have to do it inside a func? does it have to be in func main?

so far I have

func main() {

  var A_LIST []string
  A_LIST = append(A_LIST, "str1", "str2")

  var B_LIST []string
  B_LIST = append(B_LIST, "str3", "str4")
}

which can build and I can print out the two variables if I write a fmt.Println

but if I want to build this into a .so file so my python scripts can import it, is this the right thing to do?

EDIT (UPDATE): following the suggestion and writing out some code to explain what I'm intending to do

I want to have several lists to categorize my tags. In Python, it would look like:

tag_category1 = ['tag1', 'tag2', 'tag3']
tag_category2 = ['tag4', 'tag5', 'tag6']

The function would take in a list of tags and categorize them.

tags = ['tag1', 'tag3', 'tag6', 'tag7']
new_tags = {}
for tag in tags:
    if tag in tag_category1:
        new_tag['category1'].append(tag)
    elif tag in tag_category2:
        new_tag['category2'].append(tag)
    else:
        new_tag['others'].append(tag)
return new_tags

so the result should be

new_tags = {
    'category1': ['tag1', 'tag3'],
    'category2': ['tag6'],
    'others':['tag7']
}

I wanna write this function in go, and, since this function was originally used in another python script, I want to be able to import it. For that python script, I still have issue finding some util libraries i use in go, so I have to remain using python.

Body:
No, you don't have to declare variables inside a function. Though, you can't use append because append is a non-declaration statement, which you can't use outside a function. Instead, you can declare your variables using literals, in this case a slice literal, ie:

var A_LIST = []string{"str1", "str2"}

You can see an example of this in the crypto.go package, beginning on line 42:

var digestSizes = []uint8{
    MD4:        16,
    ... //omitted for this post
    RIPEMD160:  20,

}

See that it works in the playground

If you need to do more then just hard-code the values, this approach doesn't seem very viable. For anything more dynamic, you will need a function. This could be an init() function, main(), or any other function, as long as you are conscious of the scope of the variable when/where you declare it, and the order in which the variables/functions will be initialised/called.

Regarding the .so file and the appropriate place to declare these variable, I don't know. Try different ways and see what does/doesn't work, then try to figure out why.


问:
How do I remove the line breaks around my <input> element?
I have the following HTML...

```<code><label for="addnewlocationpostcode">Postcode: </label>
<input type="text" id="addnewlocationpostcode" placeholder="Enter postcode" />
<button id="addnewlocationpostcodecheck" type="button" class="btn btn-primary inline"><span class="glyphicon glyphicon-search"></span></button>
</code>```

When this is displayed in the browser, all three elements are on separate lines. I want them all on one line.

Using Chrome's inspector, I can see that the margin of the input element seems to be full width, even though Chrome claims the margin is zero...

My (uneducated) guess is that if the margin is full width, the element has to be its own line.

However, if I type $("#addnewlocationpostcode").css("margin") into the console, it gives an output of "0px" which sounds like jQuery thinks the margin is zero.

I don't have any CSS set on any of these elements. The only CSS that is used on the page is the standard Bootstrap .css file that I downloaded from their site. Even if I had some custom CSS set, I still don't understand how Chrome shows the margin as being the full width of the container when I select the element, but jQuery reports it as zero.

I tried setting the margin manually using $("#addnewlocationpostcode").css("margin-right", "10px") and the like, but it didn't make any difference what value I used, it always looked the same.

Anyone able to explain what's going on? More to the point, how do I fix it so that all three elements are on one line?

答:
As said j08691, it seems that you are using bootstrap, then try to put the form-inline class to your <form> element.

```<code><form class="form-inline">
  <input type="text" id="addnewlocationpostcode" class="form-control" placeholder="Enter postcode" />
  <button id="addnewlocationpostcodecheck" type="button" class="btn btn-primary inline"><span class="glyphicon glyphicon-search"></span></button>
</form>
</code>```

Here is a jsfiddle: https://jsfiddle.net/e0c0mfnp/

Every details are here: http://getbootstrap.com/css/#forms

I hope it helped you ;)

Body:
I have the following HTML...

Postcode:
<input type="text" id="addnewlocationpostcode" placeholder="Enter postcode" />
<button id="addnewlocationpostcodecheck" type="button" class="btn btn-primary inline"></button>

When this is displayed in the browser, all three elements are on separate lines. I want them all on one line.

Using Chrome's inspector, I can see that the margin of the input element seems to be full width, even though Chrome claims the margin is zero...

My (uneducated) guess is that if the margin is full width, the element has to be its own line.

However, if I type $("#addnewlocationpostcode").css("margin") into the console, it gives an output of "0px" which sounds like jQuery thinks the margin is zero.

I don't have any CSS set on any of these elements. The only CSS that is used on the page is the standard Bootstrap .css file that I downloaded from their site. Even if I had some custom CSS set, I still don't understand how Chrome shows the margin as being the full width of the container when I select the element, but jQuery reports it as zero.

I tried setting the margin manually using $("#addnewlocationpostcode").css("margin-right", "10px") and the like, but it didn't make any difference what value I used, it always looked the same.

Anyone able to explain what's going on? More to the point, how do I fix it so that all three elements are on one line?

Body:
As said j08691, it seems that you are using bootstrap, then try to put the form-inline class to your <form> element.

<form class="form-inline">
  <input type="text" id="addnewlocationpostcode" class="form-control" placeholder="Enter postcode" />
  <button id="addnewlocationpostcodecheck" type="button" class="btn btn-primary inline"><span class="glyphicon glyphicon-search"></span></button>
</form>

Here is a jsfiddle: https://jsfiddle.net/e0c0mfnp/

Every details are here: http://getbootstrap.com/css/#forms

I hope it helped you ;)