问:
How to configure multiple cache in spring boot using hazelcast?
I am new to Hazelcast. I am trying to implement caching in my spring boot application. I have created a config class for hazlecast with two map configs(CacheObject and CacheList). I have two methods objectMethod() which returns a single employee Object and listMethod() which returns list of employee Objects.

I am using @cacheable annotation on objectMethod and listMethod. The problem is only the object cache is working the list cache is not working. When I run the program in debug mode the object cache is returns value without going into the method but list cache always executes the methods and gets the value from the database.

Am I missing any configuration or anything else?

I am using Spring boot version 2.1.3.RELEASE, Hazelcast version 3.11.1 and Hazelcast-spring version 3.11.1.

I tried spring actuator cache url to see the cache but I am only seeing CacheObject not CacheList.

```<code>http://localhost:8080/actuator/caches

{"cacheManagers":{"cacheManager":{"caches":{"CacheObject":{"target":"com.hazelcast.map.impl.proxy.MapProxyImpl"}}}}}
</code>```

config class

```<code>@Configuration
public class HazelcastCacheConfig {

    @Bean
    public Config cacheConfig() {
        return new Config().setInstanceName("hazelcast-instance")
                .addMapConfig(new MapConfig().setName("CacheObject")
                        .setMaxSizeConfig(new MaxSizeConfig(100, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
                        .setEvictionPolicy(EvictionPolicy.LRU).setTimeToLiveSeconds(86400))
                .addMapConfig(new MapConfig().setName("CacheList")
                        .setMaxSizeConfig(new MaxSizeConfig(100, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
                        .setEvictionPolicy(EvictionPolicy.LRU).setTimeToLiveSeconds(86400));
    }
</code>```

@cacheable annotation

```<code>@Cacheable(value="CacheList")
    public List<Employee> getEmployeeList(String a, String b, String b){
        //Query
        return employeeList;

    }
</code>```

```<code>@Cacheable(value="CacheObject")
    public Employee getEmployeeObject(String a, String b, String v) {

        //Query
         return employeeObject;
    }
</code>```

Employee class

```<code>public class Employee implements Serializable{

   private static final long serialVersionUID = 1L;
   private string a,
   private string b,
   private string c,
   private UUID d,
   private Map<String,String> e;
}
</code>```

答:
Are you using both caches in the same way? Cachable won't work if you are not working with proxy objects (don't use dependency injection).

Also, how did you configure your cache managers?

```<code>package test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.spring.cache.HazelcastCacheManager;
import com.hazelcast.test.TestHazelcastInstanceFactory;

@RunWith(SpringRunner.class)
@ContextConfiguration(
    classes= { CacheableTest.CacheConfig.class, CacheableTest.Repo.class }
    )
@EnableCaching
public class CacheableTest
{
  @Configuration
  public static class CacheConfig
  {
    @Bean
    public HazelcastInstance hzInstance() {
      return Hazelcast.newHazelcastInstance();
    }

    @Bean
    public CacheManager cacheManager(HazelcastInstance hzInstance) {
        return new HazelcastCacheManager(hzInstance);
    }
  }

  @Repository
  public static class Repo {

    public static int callCountA;
    public static int callCountB;

    @Cacheable("a")
    public String getA(String key) {
      ++callCountA;
      return key;
    }

    @Cacheable("b")
    public String getB(String key) {
      ++callCountB;
      return key;
    }

  }

  @Autowired
  public Repo repo;

  @Test
  public void test() {

    String key = "a";

    assertEquals(0, Repo.callCountA);
    System.out.println(repo.getA(key));
    System.out.println(repo.getA(key));
    assertEquals(1, Repo.callCountA);

    assertEquals(0, Repo.callCountB);
    System.out.println(repo.getB(key));
    System.out.println(repo.getB(key));
    assertEquals(1, Repo.callCountB);

  }
}
</code>```

Body:
I am new to Hazelcast. I am trying to implement caching in my spring boot application. I have created a config class for hazlecast with two map configs(CacheObject and CacheList). I have two methods objectMethod() which returns a single employee Object and listMethod() which returns list of employee Objects.

I am using @cacheable annotation on objectMethod and listMethod. The problem is only the object cache is working the list cache is not working. When I run the program in debug mode the object cache is returns value without going into the method but list cache always executes the methods and gets the value from the database.

Am I missing any configuration or anything else?

I am using Spring boot version 2.1.3.RELEASE, Hazelcast version 3.11.1 and Hazelcast-spring version 3.11.1.

I tried spring actuator cache url to see the cache but I am only seeing CacheObject not CacheList.

http://localhost:8080/actuator/caches

{"cacheManagers":{"cacheManager":{"caches":{"CacheObject":{"target":"com.hazelcast.map.impl.proxy.MapProxyImpl"}}}}}

config class

@Configuration
public class HazelcastCacheConfig {

    @Bean
    public Config cacheConfig() {
        return new Config().setInstanceName("hazelcast-instance")
                .addMapConfig(new MapConfig().setName("CacheObject")
                        .setMaxSizeConfig(new MaxSizeConfig(100, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
                        .setEvictionPolicy(EvictionPolicy.LRU).setTimeToLiveSeconds(86400))
                .addMapConfig(new MapConfig().setName("CacheList")
                        .setMaxSizeConfig(new MaxSizeConfig(100, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
                        .setEvictionPolicy(EvictionPolicy.LRU).setTimeToLiveSeconds(86400));
    }

@cacheable annotation

@Cacheable(value="CacheList")
    public List<Employee> getEmployeeList(String a, String b, String b){
        //Query
        return employeeList;

    }

@Cacheable(value="CacheObject")
    public Employee getEmployeeObject(String a, String b, String v) {

        //Query
         return employeeObject;
    }

Employee class

public class Employee implements Serializable{

   private static final long serialVersionUID = 1L;
   private string a,
   private string b,
   private string c,
   private UUID d,
   private Map<String,String> e;
}

Body:
Are you using both caches in the same way? Cachable won't work if you are not working with proxy objects (don't use dependency injection).

Also, how did you configure your cache managers?

package test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.spring.cache.HazelcastCacheManager;
import com.hazelcast.test.TestHazelcastInstanceFactory;

@RunWith(SpringRunner.class)
@ContextConfiguration(
    classes= { CacheableTest.CacheConfig.class, CacheableTest.Repo.class }
    )
@EnableCaching
public class CacheableTest
{
  @Configuration
  public static class CacheConfig
  {
    @Bean
    public HazelcastInstance hzInstance() {
      return Hazelcast.newHazelcastInstance();
    }

    @Bean
    public CacheManager cacheManager(HazelcastInstance hzInstance) {
        return new HazelcastCacheManager(hzInstance);
    }
  }

  @Repository
  public static class Repo {

    public static int callCountA;
    public static int callCountB;

    @Cacheable("a")
    public String getA(String key) {
      ++callCountA;
      return key;
    }

    @Cacheable("b")
    public String getB(String key) {
      ++callCountB;
      return key;
    }

  }

  @Autowired
  public Repo repo;

  @Test
  public void test() {

    String key = "a";

    assertEquals(0, Repo.callCountA);
    System.out.println(repo.getA(key));
    System.out.println(repo.getA(key));
    assertEquals(1, Repo.callCountA);

    assertEquals(0, Repo.callCountB);
    System.out.println(repo.getB(key));
    System.out.println(repo.getB(key));
    assertEquals(1, Repo.callCountB);

  }
}


来源: stackexchange

问:
How to fix Invalid parameter number in PDO
I got the "Invalid parameter number" when I use PDO

I try to see if parameters are OK, and they are

There's my code:

        //==== Méthode permettant d'obtenir le mdp de l'utilisateur
        public function getPassword($nom){
            try {
                $sql = "SELECT
                            `password`
                        FROM
                            personne
                        WHERE
                            `nom_personne` = :nom OR `nom_personne` = lcase(:nom)";

                $req = $this->bd->prepare($sql);
                $req->bindValue(':nom',strtoupper($nom));
                $req->execute();
                $tab = $req->fetch(PDO::FETCH_NUM);
                if ($tab !== "")
                    return $tab;
                else
                    return false;

            } catch (PDOException $e){
                die('
 Erreur : '. $e->getMessage().'
');
            }
        }
```

It should return the password for a user, but it return the error. Can someone help me please ?

答:
This solution is more simple:</p>

```<code>$sql = "SELECT
                            `password`
                        FROM
                            personne
                        WHERE
                            `nom_personne` = :nom";

$req = $this->bd->prepare($sql);
$req->execute(['nom' => $nom]);
return $req->fetchColumn();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I got the "Invalid parameter number" when I use PDO

I try to see if parameters are OK, and they are

There's my code:

        //==== Méthode permettant d'obtenir le mdp de l'utilisateur
        public function getPassword($nom){
            try {
                $sql = "SELECT
                            `password`
                        FROM
                            personne
                        WHERE
                            `nom_personne` = :nom OR `nom_personne` = lcase(:nom)";

                $req = $this->bd->prepare($sql);
                $req->bindValue(':nom',strtoupper($nom));
                $req->execute();
                $tab = $req->fetch(PDO::FETCH_NUM);
                if ($tab !== "")
                    return $tab;
                else
                    return false;

            } catch (PDOException $e){
                die('
 Erreur : '. $e->getMessage().'
');
            }
        }

It should return the password for a user, but it return the error. Can someone help me please ?

Body:
This solution is more simple:

$sql = "SELECT
                            `password`
                        FROM
                            personne
                        WHERE
                            `nom_personne` = :nom";

$req = $this->bd->prepare($sql);
$req->execute(['nom' => $nom]);
return $req->fetchColumn();


问:
Remove by _id in MongoDB console
In the MongoDB console how can I remove a record by id? Here's my collection :

```<code>[
  {
     "_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },
     "name" : "Gazza"
  },
  {
     "_id" : { "$oid" : "4d513345cc9374271b02ec6c" },
     "name" : "Dave",
     "adminOf" : { },
     "email" : "email@email.com"
  }
]
</code>```

And here are the commands I've tried that don't work :

```<code>db.test_users.remove( {"_id":{"$oid":new ObjectId("4d512b45cc9374271b02ec4f")}});
db.test_users.remove( {"_id":{"$oid":"4d513345cc9374271b02ec6c"}});
db.test_users.remove( {"_id":"4d512b45cc9374271b02ec4f"});
db.test_users.remove( {"_id":new ObjectId("4d512b45cc9374271b02ec4f")});
</code>```

Removing by name works :

```<code>db.test_users.remove( {"name":"Gazza"});
</code>```

This is in the browser shell on at mongodb.org if that makes any difference.

答:
Even though this post is outdated, collection.remove is deprecated! collection.delete_one should be used instead!

More information can be found here under #remove

Title: Remove by _id in MongoDB console

Body:
In the MongoDB console how can I remove a record by id? Here's my collection :

[
  {
     "_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },
     "name" : "Gazza"
  },
  {
     "_id" : { "$oid" : "4d513345cc9374271b02ec6c" },
     "name" : "Dave",
     "adminOf" : { },
     "email" : "email@email.com"
  }
]

And here are the commands I've tried that don't work :

db.test_users.remove( {"_id":{"$oid":new ObjectId("4d512b45cc9374271b02ec4f")}});
db.test_users.remove( {"_id":{"$oid":"4d513345cc9374271b02ec6c"}});
db.test_users.remove( {"_id":"4d512b45cc9374271b02ec4f"});
db.test_users.remove( {"_id":new ObjectId("4d512b45cc9374271b02ec4f")});

Removing by name works :

db.test_users.remove( {"name":"Gazza"});

This is in the browser shell on at mongodb.org if that makes any difference.


问:
Efficient algorithm to produce the n-way intersection of sorted arrays in C
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

```<code>while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j
</code>```

I am working with C, and I am after a clear explanation rather than code.

答:
I assume that all your arrays are sorted. Lets assume we have arrays A_1 to A_n. Have a counter for each array (thus, we have n counters i_1 to i_n, just like you did it for two arrays).

Now we introduce a minimum-heap, that contains the whole arrays in a manner such that the minimum array is that array with the currently lowest number pointed to by the corresponding pointer. This means, we can at each moment, retrieve the array with the currently lowest number pointed to.

Now, we extract the minimum array from the heap and remember it. We go on extracting the minimum array as long as the number pointed to stays the same. If we extract all arrays (i.e. if all arrays have the same currently lowest pointed to number), we know that this number is in the intersection. If not (i.e. if not all arrays do contain the same currently lowest pointed to number), we know that the number we are currently examining can not be in the intersection. Thus, we increment all counters to the arrays already extracted and put them back into the heap.

We do this until we find one array's pointer reaching the array's end. I'm sorry for the undetailed description, but I do not have enough time to work it out in more detail.

Edit.

If you have one array with very few elements, it might be useful to just binary-search the other arrays for these numbers or checking these numbers using a hash table.

ContentLicense: CC BY-SA 3.0

Body:
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j

I am working with C, and I am after a clear explanation rather than code.


问:
Unable to create project in Google Cloud: "Cloud Service disabled by admin. Please contact admin to restore service"
I try to create my first Google Project, and i got this error

Create Project: My Project

APPHOSTING_ADMIN Cloud Service disabled by admin. Please contact admin to restore service. com.google.apps.framework.request.StatusException:  generic::FAILED_PRECONDITION: APPHOSTING_ADMIN Cloud Service disabled by admin. Please contact admin to restore service

Anyone any idea?

I am the admin from the GSuite account. I had checked my permission stuff in my account and I don't think there is a place for me to disable me from using GCP.

答:
This response from Google support resolved the issue for us: </p>

```<code>To activate this service, please follow the steps:
1- Access the admin console and go to Apps -> Additional Google Services
2- Look for the service “Google Cloud Platform” and click on the box next to it
3- In to top right corner click in “ON”
4- Confirm you want to turn it on in the pop-up box.
</code>```

Body:
This response from Google support resolved the issue for us:

To activate this service, please follow the steps:
1- Access the admin console and go to Apps -> Additional Google Services
2- Look for the service “Google Cloud Platform” and click on the box next to it
3- In to top right corner click in “ON”
4- Confirm you want to turn it on in the pop-up box.


问:
Looping over the subsets of a dataframe based on two conditions
I have the following problem: I need to run each subset of a dataframe -based on the value of a variable- creating a new entries for another variable depending on 2 conditions.

The dataframe (dt3) is as follows: I have 4 variables (birth_year, last name –Name-, role in the household -role- and household -hh-). The whole set is divided or subsetted by the hh variable, which gathers all the individuals under the same household. For instances, in my example bellow, the first 4 rows belong to the household “1”. Also, under the variable role, only the head of the household is stated. The rest of roles are empty and must be derived, and this is what I’m trying to do. My first step is to assign the roles of "children". I was thinking of doing it by running a loop over the whole data set and over each subset (each hh value). Whenever each line has a person who has the same last name as the head of the household and whose birth year is at least 15 years later than the head’s, then this person is inferred as “children”.

The original dataframe is:

```<code>birth_year       Name           role        hh

1877        Snijders    Head ofhousehold    1
1885        Marteen     NA                  1
1897        Snijders    NA                  1
1892        Zelstra     NA                  1
1878        Kuipers     Head of household   2
1870        Marteen     NA                  2
1897        Wals        NA                  2
1900        Venstra     NA                  2
1900        Lippe       Head of household   3
1905        Flachs      NA                  3
1920        Lippe       NA                  3
1922        Lippe       NA                  3
</code>```

So, I need to run the whole set and each hh subset and perform the following two conditions:
a.  If the person’s name == the name of the head, and
b.  If the birth year of the person has a difference of 15 years or more with the head´s

Then this person is “children”.

So far I´ve been trying several things. As I’m placing the head role in the first row of each household then I was doing this:

a)
Nested loop, where I try to run the data set and then each hh. For each hh I run the conditions (by comparing each row’s name and birth year with those of the first line of the hh –the head-)

```<code>for (n in 1:unique(dt3$hh)){
  for (i in 1:length(which(dt3$hh==n)) ){
     mutate(dt3, role = ifelse( dt3$Name[[1,2]] == dt3$Name[[n,1]]
     & dt3$birth_year[[n,i]] > dt3$birth_year[[n,1]], "children","NoA"))
      }
  }
</code>```

Also b), I have tried to do the same, but with lists. I first Split dt3 by means of the hh variable

```<code>dt3 <- split(dt3, f = dt3$hh)
</code>```

And then

```<code>for (n in 1:dt3){
  mutate(dt3, role = ifelse( dt3$name [[n,i]] == dt3$name[[n,1]] &
        dt3$birth_year[[n,i]] > dt3$birth_year[[n,1]],"children","NoA"))
  }
</code>```

No success with the two solutions I was exploring, and what I was expecting is an outcomelike this:

```<code>birth_year       Name           role        hh

1877        Snijders    Head ofhousehold    1
1885        Marteen     NA                  1
1897        Snijders    children            1
1892        Zelstra     NA                  1
1878        Kuipers     Head of household   2
1870        Marteen     NA                  2
1897        Wals        NA                  2
1900        Venstra     NA                  2
1900        Lippe       Head of household   3
1905        Flachs      NA                  3
1920        Lippe       children            3
1922        Lippe       children            3
</code>```

Any tips will be welcome.

Thank you in advance

答:
You can first extract all "HeadOfHousehold", and merge them to your dt3 and then make the comparisons of name and birth year.

```<code>dt3 <- read.table(header=T, text="birth_year      Name           role        hh
1877        Snijders    HeadOfHousehold    1
1885        Marteen     NA                  1
1897        Snijders    NA                  1
1892        Zelstra     NA                  1
1878        Kuipers     HeadOfHousehold   2
1870        Marteen     NA                  2
1897        Wals        NA                  2
1900        Venstra     NA                  2
1900        Lippe       HeadOfHousehold   3
1905        Flachs      NA                  3
1920        Lippe       NA                  3
1922        Lippe       NA                  3", as.is = T)

tt <- with(dt3[!is.na(dt3$role) & dt3$role=="HeadOfHousehold",], data.frame(a=birth_year, b=Name, hh))
me <- merge(dt3, tt, all.x=T)
me$role[me$Name==me$b & me$birth_year > me$a+14] <- "children"
me[names(dt3)]

1        1877 Snijders HeadOfHousehold  1
2        1885  Marteen            <NA>  1
3        1897 Snijders        children  1
4        1892  Zelstra            <NA>  1
5        1878  Kuipers HeadOfHousehold  2
6        1870  Marteen            <NA>  2
7        1897     Wals            <NA>  2
8        1900  Venstra            <NA>  2
9        1900    Lippe HeadOfHousehold  3
10       1905   Flachs            <NA>  3
11       1920    Lippe        children  3
12       1922    Lippe        children  3
</code>```

Body:
I have the following problem: I need to run each subset of a dataframe -based on the value of a variable- creating a new entries for another variable depending on 2 conditions.

The dataframe (dt3) is as follows: I have 4 variables (birth_year, last name –Name-, role in the household -role- and household -hh-). The whole set is divided or subsetted by the hh variable, which gathers all the individuals under the same household. For instances, in my example bellow, the first 4 rows belong to the household “1”. Also, under the variable role, only the head of the household is stated. The rest of roles are empty and must be derived, and this is what I’m trying to do. My first step is to assign the roles of "children". I was thinking of doing it by running a loop over the whole data set and over each subset (each hh value). Whenever each line has a person who has the same last name as the head of the household and whose birth year is at least 15 years later than the head’s, then this person is inferred as “children”.

The original dataframe is:

birth_year       Name           role        hh

1877        Snijders    Head ofhousehold    1
1885        Marteen     NA                  1
1897        Snijders    NA                  1
1892        Zelstra     NA                  1
1878        Kuipers     Head of household   2
1870        Marteen     NA                  2
1897        Wals        NA                  2
1900        Venstra     NA                  2
1900        Lippe       Head of household   3
1905        Flachs      NA                  3
1920        Lippe       NA                  3
1922        Lippe       NA                  3

So, I need to run the whole set and each hh subset and perform the following two conditions:
a.  If the person’s name == the name of the head, and
b.  If the birth year of the person has a difference of 15 years or more with the head´s

Then this person is “children”.

So far I´ve been trying several things. As I’m placing the head role in the first row of each household then I was doing this:

a)
Nested loop, where I try to run the data set and then each hh. For each hh I run the conditions (by comparing each row’s name and birth year with those of the first line of the hh –the head-)

for (n in 1:unique(dt3$hh)){
  for (i in 1:length(which(dt3$hh==n)) ){
     mutate(dt3, role = ifelse( dt3$Name[[1,2]] == dt3$Name[[n,1]]
     & dt3$birth_year[[n,i]] > dt3$birth_year[[n,1]], "children","NoA"))
      }
  }

Also b), I have tried to do the same, but with lists. I first Split dt3 by means of the hh variable

dt3 <- split(dt3, f = dt3$hh)

And then

for (n in 1:dt3){
  mutate(dt3, role = ifelse( dt3$name [[n,i]] == dt3$name[[n,1]] &
        dt3$birth_year[[n,i]] > dt3$birth_year[[n,1]],"children","NoA"))
  }

No success with the two solutions I was exploring, and what I was expecting is an outcomelike this:

birth_year       Name           role        hh

1877        Snijders    Head ofhousehold    1
1885        Marteen     NA                  1
1897        Snijders    children            1
1892        Zelstra     NA                  1
1878        Kuipers     Head of household   2
1870        Marteen     NA                  2
1897        Wals        NA                  2
1900        Venstra     NA                  2
1900        Lippe       Head of household   3
1905        Flachs      NA                  3
1920        Lippe       children            3
1922        Lippe       children            3

Any tips will be welcome.

Thank you in advance

Body:
You can first extract all "HeadOfHousehold", and merge them to your dt3 and then make the comparisons of name and birth year.

dt3 <- read.table(header=T, text="birth_year      Name           role        hh
1877        Snijders    HeadOfHousehold    1
1885        Marteen     NA                  1
1897        Snijders    NA                  1
1892        Zelstra     NA                  1
1878        Kuipers     HeadOfHousehold   2
1870        Marteen     NA                  2
1897        Wals        NA                  2
1900        Venstra     NA                  2
1900        Lippe       HeadOfHousehold   3
1905        Flachs      NA                  3
1920        Lippe       NA                  3
1922        Lippe       NA                  3", as.is = T)

tt <- with(dt3[!is.na(dt3$role) & dt3$role=="HeadOfHousehold",], data.frame(a=birth_year, b=Name, hh))
me <- merge(dt3, tt, all.x=T)
me$role[me$Name==me$b & me$birth_year > me$a+14] <- "children"
me[names(dt3)]

1        1877 Snijders HeadOfHousehold  1
2        1885  Marteen            <NA>  1
3        1897 Snijders        children  1
4        1892  Zelstra            <NA>  1
5        1878  Kuipers HeadOfHousehold  2
6        1870  Marteen            <NA>  2
7        1897     Wals            <NA>  2
8        1900  Venstra            <NA>  2
9        1900    Lippe HeadOfHousehold  3
10       1905   Flachs            <NA>  3
11       1920    Lippe        children  3
12       1922    Lippe        children  3


问:
run a batch with parameters from visual studio
I'm trying to run a batch file with arguments, it should be dynamic but it does not work the way the I want it to.

I have some code with a specific directory that works, I want to make it more dynamic. I'm retrieving a directory from a textBox in visual studio.

```<code>String rep_source = textBox12.Text;
String attribute = textBox4.Text;
String rep_destination = textBox5.Text;
String poly_dest = textBox13.Text;
string SPECIFIC_DIRECTORY= textBox7.Text; //I want to use this for my code
string command = @"/c powershell -executionpolicy unrestricted C:\Folder1\Folder2\batchfile.Bat" + " " + rep_source + " " + poly_dest + " " + attribute + " " + rep_destination;
         System.Diagnostics.Process.Start("cmd.exe", command);
</code>```

thing code works but when I'm trying to the retrieved directory.

```<code> string command = @"/c powershell -executionpolicy unrestricted " +SPECIFIC_DIRECTORY +"\\batchfile.Bat" + " " + rep_source + " " + poly_dest + " " + attribute + " " + rep_destination;
</code>```

This would not compile and give me what I want.
i'm not even able to reach the batchfile itself.

答:
Try this:

String com = @"/c powershell -executionpolicy unrestricted C:\Folder1\Folder2\batchfile.Bat" + " " + rep_source + " " + poly_dest + " " + attribute + " " + rep_destination;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + com );
ProcessInfo.CreateNoWindow = true;
```

Body:
I'm trying to run a batch file with arguments, it should be dynamic but it does not work the way the I want it to.

I have some code with a specific directory that works, I want to make it more dynamic. I'm retrieving a directory from a textBox in visual studio.

String rep_source = textBox12.Text;
String attribute = textBox4.Text;
String rep_destination = textBox5.Text;
String poly_dest = textBox13.Text;
string SPECIFIC_DIRECTORY= textBox7.Text; //I want to use this for my code
string command = @"/c powershell -executionpolicy unrestricted C:\Folder1\Folder2\batchfile.Bat" + " " + rep_source + " " + poly_dest + " " + attribute + " " + rep_destination;
         System.Diagnostics.Process.Start("cmd.exe", command);

thing code works but when I'm trying to the retrieved directory.

 string command = @"/c powershell -executionpolicy unrestricted " +SPECIFIC_DIRECTORY +"\\batchfile.Bat" + " " + rep_source + " " + poly_dest + " " + attribute + " " + rep_destination;

This would not compile and give me what I want.
i'm not even able to reach the batchfile itself.


问:
Can't pass array to a sorting function(need to sort columns, not rows)
I need to use selection sort to sort a two-dimensional array. The problem is that I need to sort array's columns, not rows.
Here is how I allocate a two-dimensional array(to show the structure):

```<code>int** array = new int*[rows];
    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }
</code>```

Then I add some items into it. Here is my sorting function:

```<code>void selectionSort(int* arr, int n)
{
    int i, j, min_idx;

    for (i = 0; i < n; i++)
    {
        min_idx = i;
        for (j = i + 1; j < n; j++)
            if (arr[j] < arr[min_idx])
                min_idx = j;

        swap(&arr[min_idx], &arr[i]);
    }
}
</code>```

I'm not specifying swap since it is self-explanatory.

So, again, I need to sort every column of a matrix. For example:

Input:

5 3 1

2 0 9

4 2 6

Output:

2 0 1

4 2 6

5 3 9

Any ideas on how to do that? Right now I transpose the matrix twice and in-between transpositions I sort it, but I don't think it is a good option because of its slowness.

答:
You might template your function to have a getter of int:

```<code>template <typename F>
void selectionSort(F f, int size)
{
    for (int i = 0; i < size; i++)
    {
        int min_idx = i;
        for (int j = i + 1; j < size; j++)
            if (f(j) < f(min_idx))
                min_idx = j;

        swap(f(min_idx), f(i));
    }
}
</code>```

So, in one dimension, you have your old:

```<code>selectionSort([arr](int i) -> int&{ return arr[i]; }, n);
</code>```

and for column:

```<code>selectionSort([arr, j](int i) -> int&{ return arr[i][j]; }, n);
</code>```

Body:
I need to use selection sort to sort a two-dimensional array. The problem is that I need to sort array's columns, not rows.
Here is how I allocate a two-dimensional array(to show the structure):

int** array = new int*[rows];
    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

Then I add some items into it. Here is my sorting function:

void selectionSort(int* arr, int n)
{
    int i, j, min_idx;

    for (i = 0; i < n; i++)
    {
        min_idx = i;
        for (j = i + 1; j < n; j++)
            if (arr[j] < arr[min_idx])
                min_idx = j;

        swap(&arr[min_idx], &arr[i]);
    }
}

I'm not specifying swap since it is self-explanatory.

So, again, I need to sort every column of a matrix. For example:

Input:

5 3 1

2 0 9

4 2 6

Output:

2 0 1

4 2 6

5 3 9

Any ideas on how to do that? Right now I transpose the matrix twice and in-between transpositions I sort it, but I don't think it is a good option because of its slowness.

Body:
You might template your function to have a getter of int:

template <typename F>
void selectionSort(F f, int size)
{
    for (int i = 0; i < size; i++)
    {
        int min_idx = i;
        for (int j = i + 1; j < size; j++)
            if (f(j) < f(min_idx))
                min_idx = j;

        swap(f(min_idx), f(i));
    }
}

So, in one dimension, you have your old:

selectionSort([arr](int i) -> int&{ return arr[i]; }, n);

and for column:

selectionSort([arr, j](int i) -> int&{ return arr[i][j]; }, n);


问:
Inserting an optional word wrapping point using CSS
I am trying to format a quotation that has a reference at the end. My markup looks like this:

```<code><p class=quotation>
    "Your time is limited, so don't waste it living someone else's life.
    Don't be trapped by dogma – which is living with the results of
    other people's thinking."<span class=reference>Steve Jobs</span>
</p>
</code>```

I am inserting an em-dash before the span using the CSS ::before pseudo-element. However, the line breaks are a bit ugly. I would prefer to have no line breaks within the quotation itself, so my CSS currently looks like this:

```<code>.quotation .reference::before {
    content: '—';
}
.quotation .reference {
    white-space: nowrap;
}
</code>```

Unfortunately, this means that the last word (in this case, `thinking.") gets attached to the em-dash and breaks to the new line as well.

I want two things to happen:

when the reference fits on the same line as the end of the quotation, there should be no space before the dash

when the reference does not fit, the wrapping should be done before the em-dash

I have tried inserting a zero-width space with content: '\200B—';, but this seems to have no effect at all.

Is there any way of achieving this in pure CSS?

In this snippet, the div is resizable so you can see how the line break is not inserted.

.quotation .reference::before {
  content: '—';
}
.quotation .reference {
  white-space: nowrap;
}

/* make div resizable to see the effect */

div {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p class=quotation>
    "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking."<span class=reference>Steve Jobs</span>
  </p>
</div></code>```

答:
Simply make it inline-block to avoid the gets attached effect:

.quotation .reference::before {
  content: '—';
}
.quotation .reference {
  white-space: nowrap;
  display:inline-block;
}

/* make div resizable to see the effect */

div {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p class=quotation>
    "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking."<span class=reference>Steve Jobs</span>
  </p>
</div></code>```

Body:
I am trying to format a quotation that has a reference at the end. My markup looks like this:

    "Your time is limited, so don't waste it living someone else's life.
    Don't be trapped by dogma – which is living with the results of
    other people's thinking."Steve Jobs

I am inserting an em-dash before the span using the CSS ::before pseudo-element. However, the line breaks are a bit ugly. I would prefer to have no line breaks within the quotation itself, so my CSS currently looks like this:

.quotation .reference::before {
    content: '—';
}
.quotation .reference {
    white-space: nowrap;
}

Unfortunately, this means that the last word (in this case, `thinking.") gets attached to the em-dash and breaks to the new line as well.

I want two things to happen:

when the reference fits on the same line as the end of the quotation, there should be no space before the dash

when the reference does not fit, the wrapping should be done before the em-dash

I have tried inserting a zero-width space with content: '\200B—';, but this seems to have no effect at all.

Is there any way of achieving this in pure CSS?

In this snippet, the div is resizable so you can see how the line break is not inserted.

.quotation .reference::before {
  content: '—';
}
.quotation .reference {
  white-space: nowrap;
}

/* make div resizable to see the effect */

div {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 1em;
}

    "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking."Steve Jobs

Body:
Simply make it inline-block to avoid the gets attached effect:

.quotation .reference::before {
  content: '—';
}
.quotation .reference {
  white-space: nowrap;
  display:inline-block;
}

/* make div resizable to see the effect */

div {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 1em;
}

<div>
  <p class=quotation>
    "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking."<span class=reference>Steve Jobs</span>
  </p>
</div>


问:
How to run a program in python using pycharm
I made a program

```<code>FN=int(raw_input("Enter a number"))
SN = int(raw_input("Enter a number"))
TN = FN+SN
PRINT (TN)
</code>```

Please someone tell me how to run it in pycharm

also the error it showing is :
    Cannot run program "C:\
Users\Lenovo\PyCharmProjects\Untitled\venv\Scripts\python.exe"(in directory"C:\Users\Lenovo\PyCharmProjects\untitled"): Create process error = 2. The System cannot find the file specified

答: Try to Shift+F10 shortcut, or you can right click to the editor and select Run( name_of_your_file.py) section.

Body:
I made a program

FN=int(raw_input("Enter a number"))
SN = int(raw_input("Enter a number"))
TN = FN+SN
PRINT (TN)

Please someone tell me how to run it in pycharm

also the error it showing is :
    Cannot run program "C:\
Users\Lenovo\PyCharmProjects\Untitled\venv\Scripts\python.exe"(in directory"C:\Users\Lenovo\PyCharmProjects\untitled"): Create process error = 2. The System cannot find the file specified


答:
You can also use T-Regx library</p>

```<code><?php
pattern('Gold\s+([0-9.]+)\s+([0-9.]+)', 'i')->match($data)->forEach(function ($m) {
    print 'bid: ' . $m->group(1);
    print 'ask: ' . $m->group(2);
});
</code>```

Title: Regular Expression - PHP

Body:
I am using following PHP code

<?
    $data = file_get_contents('http://www.kitco.com/texten/texten.html');
    preg_match_all('/([A-Z]{3,5}\s+[0-9]{1,2},[0-9]{4}\s+([0-9.NA]{2,10}\s+){1,7})/si',$data,$result);

    $records = array();
    foreach($result[1] as $date) {
        $temp = preg_split('/\s+/',$date);
        $index = array_shift($temp);
        $index.= array_shift($temp);
        $records[$index] = implode(',',$temp);
    }
    print_R($records);
?>

To READ the following data

  --------------------------------------------------------------------------------
   London Fix          GOLD          SILVER       PLATINUM           PALLADIUM
                   AM       PM                  AM       PM         AM       PM
   --------------------------------------------------------------------------------
   Jun 03,2013   1396.75   1402.50   22.4300   1466.00   1487.00   749.00   755.00
   May 31,2013   1410.25   1394.50   22.5700   1471.00   1459.00   755.00   744.00
   --------------------------------------------------------------------------------

What i want to do is Read GOLD ( BID & ASK ) price from below table, can anyone help in the regular expression changes?

New York Spot Price
                MARKET IS CLOSED
            Will open in

----------------------------------------------------------------------
   Metals          Bid        Ask           Change        Low       High
   ----------------------------------------------------------------------
   Gold         1411.20     1412.20    +22.90  +1.65%    1390.10  1418.00
   Silver         22.74       22.84     +0.48  +2.13%      22.26    23.08
   Platinum     1495.00     1501.00    +41.00  +2.82%    1470.00  1511.00
   Palladium     756.00      761.00     +7.00  +0.93%     750.00   766.00
   ----------------------------------------------------------------------
   Last Update on Jun 03, 2013 at 17:14.58
   ----------------------------------------------------------------------

Body:
You can also use T-Regx library

<?php
pattern('Gold\s+([0-9.]+)\s+([0-9.]+)', 'i')->match($data)->forEach(function ($m) {
    print 'bid: ' . $m->group(1);
    print 'ask: ' . $m->group(2);
});


问:
Swift - Viewcontrollers not deinit when segue is performed
I am fairly new to the whole concept of memory management and ARC.

I've recently looked into it and found mixed success.

Firstly it should be noted that some ViewController do deinitialize but I am still learning and cleaning up my application.

However, a common pattern I have noticed is that when I use the line navigationController?.popViewController(animated: true) this does infact deinit a view controller, given if there are no strong references.

However, my issue is that when I use a segue and use performSegue(withIdentifier: "showDetail_Segue", sender: nil) the deinit method is never used/called. (I just have a print statement to indicate whether a view has been deinitalized). In most cases, when I perform a segue, I am passing data to another view controller and as a result, I use the following function override func prepare(for segue: UIStoryboardSegue, sender: Any?) {}.

I have tried to change my segue to navigationController?.pushViewController(VC, animated: true) but my application crashes.

Am I missing something here?

The ViewControllers that deinitliaze when the navigationController is popped also do not deinitialze when performing a segue programmatically.

Could someone please tell me what I'm doing wrong?

Thank you.

答:
Alright, if I understood you correctly, you might have a misunderstanding on how segues work

Segues cannot be used to go back to the previous viewController in stack

This is pretty important. If you use segues as a way of going back instead of using popViewController you're creating a new instance of the viewController you go back to so deinit is never called since the viewController is still in memory.

Essentially, something like this List -> Details -> List, where you just created another instance of the list with the segue.


问:
backward count in a numpy array
Let's suppose I have a series of integer values arranged in a numpy array like this.

```<code>nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])
</code>```

nan values should be filled with backward count from the first not null value to zero.

```<code>[3, 2, 1, 0, 5, 4, 3, 2, 1, 0]
</code>```

答:
```<code>import pandas as pd
import numpy as np
import math

arr = pd.Series([3,np.nan,np.nan,np.nan,5,np.nan,np.nan,np.nan,np.nan,np.nan])

for i in range(len(arr)):
    # Check if each element is "NaN"
    if math.isnan(arr[i]):
        # If NaN then take the previous element and subtract 1
        arr[i] = arr[i-1]-1

# print the final array
print(arr)
</code>```

Result:

```<code>0    3.0
1    2.0
2    1.0
3    0.0
4    5.0
5    4.0
6    3.0
7    2.0
8    1.0
9    0.0
dtype: float64
</code>```

Title: backward count in a numpy array

Body:
Let's suppose I have a series of integer values arranged in a numpy array like this.

nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])

nan values should be filled with backward count from the first not null value to zero.

[3, 2, 1, 0, 5, 4, 3, 2, 1, 0]

Body:
import pandas as pd
import numpy as np
import math

arr = pd.Series([3,np.nan,np.nan,np.nan,5,np.nan,np.nan,np.nan,np.nan,np.nan])

for i in range(len(arr)):
    # Check if each element is "NaN"
    if math.isnan(arr[i]):
        # If NaN then take the previous element and subtract 1
        arr[i] = arr[i-1]-1

# print the final array
print(arr)

Result:

0    3.0
1    2.0
2    1.0
3    0.0
4    5.0
5    4.0
6    3.0
7    2.0
8    1.0
9    0.0
dtype: float64


问:
Leaflet.js dynamic multiple maps on same page
I'm creating a web app where a user can upload their own maps and then they are displayed with Leaflet.js within Bootstrap nav tabs. This is within a Python Flask app.

I have got it to work, although only one maps settings for bounds, etc. are used. So say if I had a Westeros and Middle Earth map, the bounds calculated for the Middle Earth map would also be used for the Westeros map.

Here is my code:

```<code>$(document).ready(function(){
    {% for map_file in map_list %}
        var img = new Image();
        img.onload = function(){
            var h = img.height;
            var w = img.width;

            var map = L.map('{{ map_file[1] }}', {
                minZoom: 1,
                maxZoom: 5,
                center: [0,0],
                zoom:1,
                crs: L.CRS.Simple,
            });

            var southWest = map.unproject([0,h], map.getMaxZoom() -1);
            var northEast = map.unproject([w,0], map.getMaxZoom() -1);
            var bounds = new L.LatLngBounds(southWest, northEast);
            {% set map_img_dir = '/static/users/'+user+'/maps/'+map_file[0] %}
            var image = L.imageOverlay('{{ map_img_dir }}', bounds).addTo(map);
            map.setMaxBounds(bounds);
        }
        {% set map_img = 'users/'+user+'/maps/'+map_file[0] %}
        img.src = "{{ url_for('static', filename=map_img) }}"
    {% endfor %}
});
</code>```

(small note for context, map_list is a 2D list of files with and without their extensions, e.g. ['middle_earth.jpg','middle_earth'])

I have attributed this problem to map. I understand that with multiple maps I have seen use different map variables for the each map, however since the maps are being created dynamically and I am unsure of how many maps there will be, I am unsure of how I would be able to implement this.

I appreciate any help/advice.

EDIT: I solved it by using {{ map_file[1] }} as a variable name instead of img, so the variable names will be something like middle_earth or westeros. Another problem is that the zooms are not animated when I use the scroll wheel, it is very blocky and goes quite fast?

答:
I solved it by using {{ map_file[1] }} instead of the name img. Additionally, I added this, shown here:

```<code>{% set map_tab_id = map_file[1]+'-tab-id' %}
$("a[href='#{{ map_tab_id }}']").on('shown.bs.tab', function(e) {
    map.invalidateSize();
});
</code>```

After map.setMaxBounds(bounds); which solved the blocky/non animated zoom.

For completeness, this is the map tab panes which are within a jinja for loop:

```<code><div class="tab-pane fade" id="{{ map_tab_id }}" >
    <div id="{{ map_file[1] }}" style="width:500px; height:500px;"></div>
</div>
</code>```

Where map_tab_id is just map_file[1] (e.g. westeros or middle_earth) with '-tab-id' on the end.

Body:
I'm creating a web app where a user can upload their own maps and then they are displayed with Leaflet.js within Bootstrap nav tabs. This is within a Python Flask app.

I have got it to work, although only one maps settings for bounds, etc. are used. So say if I had a Westeros and Middle Earth map, the bounds calculated for the Middle Earth map would also be used for the Westeros map.

Here is my code:

$(document).ready(function(){
    {% for map_file in map_list %}
        var img = new Image();
        img.onload = function(){
            var h = img.height;
            var w = img.width;

            var map = L.map('{{ map_file[1] }}', {
                minZoom: 1,
                maxZoom: 5,
                center: [0,0],
                zoom:1,
                crs: L.CRS.Simple,
            });

            var southWest = map.unproject([0,h], map.getMaxZoom() -1);
            var northEast = map.unproject([w,0], map.getMaxZoom() -1);
            var bounds = new L.LatLngBounds(southWest, northEast);
            {% set map_img_dir = '/static/users/'+user+'/maps/'+map_file[0] %}
            var image = L.imageOverlay('{{ map_img_dir }}', bounds).addTo(map);
            map.setMaxBounds(bounds);
        }
        {% set map_img = 'users/'+user+'/maps/'+map_file[0] %}
        img.src = "{{ url_for('static', filename=map_img) }}"
    {% endfor %}
});

(small note for context, map_list is a 2D list of files with and without their extensions, e.g. ['middle_earth.jpg','middle_earth'])

I have attributed this problem to map. I understand that with multiple maps I have seen use different map variables for the each map, however since the maps are being created dynamically and I am unsure of how many maps there will be, I am unsure of how I would be able to implement this.

I appreciate any help/advice.

EDIT: I solved it by using {{ map_file[1] }} as a variable name instead of img, so the variable names will be something like middle_earth or westeros. Another problem is that the zooms are not animated when I use the scroll wheel, it is very blocky and goes quite fast?

Body:
I solved it by using {{ map_file[1] }} instead of the name img. Additionally, I added this, shown here:

{% set map_tab_id = map_file[1]+'-tab-id' %}
$("a[href='#{{ map_tab_id }}']").on('shown.bs.tab', function(e) {
    map.invalidateSize();
});

After map.setMaxBounds(bounds); which solved the blocky/non animated zoom.

For completeness, this is the map tab panes which are within a jinja for loop:

<div class="tab-pane fade" id="{{ map_tab_id }}" >
    <div id="{{ map_file[1] }}" style="width:500px; height:500px;"></div>
</div>

Where map_tab_id is just map_file[1] (e.g. westeros or middle_earth) with '-tab-id' on the end.


问:
Django how to group by multiple fields and sum
I am trying to perform multiple group_by's on my table with the fields same as the serializer below (last column is money)

```<code>class MoneySerializer(serializers.ModelSerializer):
money_sum = serializers.IntegerField()

class Meta:
    model =  my_models.Money
    fields = ('date', 'city', 'money_sum')
</code>```

My Query in my viewset is as follows

```<code>items = my_models.Money.objects.values('date', 'city').annotate(money_sum=Sum('money'))
</code>```

But with this, I'll have a group_by done for the city column, but I'll still have duplicates for the date field. I would like to group the rows such that it groups by all the same city values and all the same date values.

edit: my model

```<code>class Money(models.Model):
    date = models.DateField()
    city = models.models.CharField(max_length=200)
    money = models.DecimalField(decimal_places=2, max_digits=20)
</code>```

答:
You need to add an order_by [Django-doc] to force a GROUP BY here:

```<code>Money.objects.values('date', 'city').annotate(
    money_sum=Sum('money')
)<b>.order_by('date', 'city')</b></code>```

This will result in a QuerySet of dictionaries, like:

```<code><QuerySet [
    {'date': date(2019, 1, 1), 'city': 'Berlin', 'money_sum': 1425.00},
    {'date': date(2019, 1, 1), 'city': 'Vienna', 'money_sum': 1302.00},
    {'date': date(2019, 2, 9), 'city': 'Madrid', 'money_sum': 1789.00},
    {'date': date(2019, 6, 29), 'city': 'Vienna', 'money_sum': 2019.00}
]>
</code>```

Body:
I am trying to perform multiple group_by's on my table with the fields same as the serializer below (last column is money)

class MoneySerializer(serializers.ModelSerializer):
money_sum = serializers.IntegerField()

class Meta:
    model =  my_models.Money
    fields = ('date', 'city', 'money_sum')

My Query in my viewset is as follows

items = my_models.Money.objects.values('date', 'city').annotate(money_sum=Sum('money'))

But with this, I'll have a group_by done for the city column, but I'll still have duplicates for the date field. I would like to group the rows such that it groups by all the same city values and all the same date values.

edit: my model

class Money(models.Model):
    date = models.DateField()
    city = models.models.CharField(max_length=200)
    money = models.DecimalField(decimal_places=2, max_digits=20)

Body:
You need to add an order_by [Django-doc] to force a GROUP BY here:

Money.objects.values('date', 'city').annotate(
    money_sum=Sum('money')
).order_by('date', 'city')

This will result in a QuerySet of dictionaries, like:

<QuerySet [
    {'date': date(2019, 1, 1), 'city': 'Berlin', 'money_sum': 1425.00},
    {'date': date(2019, 1, 1), 'city': 'Vienna', 'money_sum': 1302.00},
    {'date': date(2019, 2, 9), 'city': 'Madrid', 'money_sum': 1789.00},
    {'date': date(2019, 6, 29), 'city': 'Vienna', 'money_sum': 2019.00}
]>


问:
NSManagedObject  hierarchy import and export
I'm on the run to make my NSMangedObjectClass profile im-/exportable.

I try it  this way

Exporting works correctly if I write the Relationships in NSArrays because NSSet doesn't have writeToFile implemented.

```<code>- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
//Profile
NSMutableDictionary *profileDict = [[self.selectedProfile dictionaryWithValuesForKeys:[[[self.selectedProfile entity] attributesByName] allKeys]] mutableCopy];
NSMutableArray *views = [NSMutableArray array];

//Views
for (View *view in selectedProfile.views) {
    NSMutableDictionary *viewDict = [[view dictionaryWithValuesForKeys:[[[view entity] attributesByName] allKeys]] mutableCopy];
    NSMutableArray *controls = [NSMutableArray array];
         //Much more for-loops
    [viewDict setObject:controls forKey:@"controls"];
    [views addObject:viewDict];
}

[profileDict setObject:views forKey:@"views"];

if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES])
    NSLog(@"Saved");
else
    NSLog(@"Not saved");
[profileDict release];
}
</code>```

But if want to import on the other side

```<code>- (Profile*) importProfileFromPath:(NSString *)path{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];

NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
[newProfile setValuesForKeysWithDictionary:profileDict];
}
</code>```

I get an exception, this doesn't confuse me cause Profile expects a NSSet and no NSArray.

[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException',

reason: '-[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0'

So I've got two problems:

On the one side, I can't write a NSSet to File.

On the other side is my Profile class expecting an NSSet.

So I tried to create a Category of NSSet which implements writeToFile

```<code>@implementation NSSet(Persistence)

- (BOOL)writeToFile:(NSString*)path atomically:(BOOL)flag{
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:self.count];
    for(id element in self)
        [temp addObject:element];
    return [temp writeToFile:path atomically:flag];
}

+ (id)setWithContentsOfFile:(NSString *)aPath{
    return [NSSet setWithArray:[NSArray arrayWithContentsOfFile:aPath]];
}
@end
</code>```

But my functions aren't called.

Is there a other way to write my NSSet or tell setValuesForKeysWithDictionary the Key "views" is a NSArray?

Or a easy Way to im-/export ManagedObjects?

答:
Got problems with the nested NSDictonarys, so i said goodbye to the dynamic way.
Here is my complete Solution to help others

ViewController to call the im/export functions

```<code>- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
    //Call the NSManagedobject function to export
    NSDictionary *profileDict = [self.selectedProfile dictionaryForExport];

    if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES])
        NSLog(@"Saved");
    else
        NSLog(@"Not saved");
}

- (void) importProfileFromPath:(NSString *)path{
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];

    //load dictonary from file
    NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
    //call the NSManagedObjects import function
    [newProfile importWithDictonary:profileDict context:context];

    NSError *error = nil;
    if (![context save:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}
</code>```

NSManagedObject functions i got a hierarchy so i put them in each of my NSManagedObjects

```<code>- (void) importWithDictonary:(NSDictionary*)dict context:(NSManagedObjectContext*)context{
    self.name = [dict objectForKey:@"name"];

    //Relationship
    for (NSDictionary *view in [dict objectForKey:@"views"]) {
        View *tempView = [NSEntityDescription insertNewObjectForEntityForName:@"View" inManagedObjectContext:context];
        [tempView importWithDictonary:view context:context];
        tempView.profile = self;
        [self addViewsObject:tempView];
    }
}

- (NSDictionary*) dictionaryForExport{
    //propertys
    NSMutableDictionary *dict = [[[self dictionaryWithValuesForKeys:[[[self entity] attributesByName] allKeys]] mutableCopy] autorelease];
    NSURL *objectID = [[self objectID] URIRepresentation];
    [dict setObject: [objectID absoluteString] forKey:@"objectID"];
    NSMutableArray *views = [NSMutableArray array];

    //relationship
    for (View *view in self.views) {
        [views addObject:[view dictionaryForExport]];
    }
    [dict setObject:views forKey:@"views"];
    return dict;
}
</code>```

not the most beautiful solution but it works :)

and i have still to figure out how to avoid duplicates in my n:m relationship

Thanks

Body:
I'm on the run to make my NSMangedObjectClass profile im-/exportable.

I try it  this way

Exporting works correctly if I write the Relationships in NSArrays because NSSet doesn't have writeToFile implemented.

- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
//Profile
NSMutableDictionary *profileDict = [[self.selectedProfile dictionaryWithValuesForKeys:[[[self.selectedProfile entity] attributesByName] allKeys]] mutableCopy];
NSMutableArray *views = [NSMutableArray array];

//Views
for (View *view in selectedProfile.views) {
    NSMutableDictionary *viewDict = [[view dictionaryWithValuesForKeys:[[[view entity] attributesByName] allKeys]] mutableCopy];
    NSMutableArray *controls = [NSMutableArray array];
         //Much more for-loops
    [viewDict setObject:controls forKey:@"controls"];
    [views addObject:viewDict];
}

[profileDict setObject:views forKey:@"views"];

if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES])
    NSLog(@"Saved");
else
    NSLog(@"Not saved");
[profileDict release];
}

But if want to import on the other side

- (Profile*) importProfileFromPath:(NSString *)path{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];

NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
[newProfile setValuesForKeysWithDictionary:profileDict];
}

I get an exception, this doesn't confuse me cause Profile expects a NSSet and no NSArray.

[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException',

reason: '-[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0'

So I've got two problems:

On the one side, I can't write a NSSet to File.

On the other side is my Profile class expecting an NSSet.

So I tried to create a Category of NSSet which implements writeToFile

@implementation NSSet(Persistence)

- (BOOL)writeToFile:(NSString*)path atomically:(BOOL)flag{
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:self.count];
    for(id element in self)
        [temp addObject:element];
    return [temp writeToFile:path atomically:flag];
}

+ (id)setWithContentsOfFile:(NSString *)aPath{
    return [NSSet setWithArray:[NSArray arrayWithContentsOfFile:aPath]];
}
@end

But my functions aren't called.

Is there a other way to write my NSSet or tell setValuesForKeysWithDictionary the Key "views" is a NSArray?

Or a easy Way to im-/export ManagedObjects?

Body:
Got problems with the nested NSDictonarys, so i said goodbye to the dynamic way.
Here is my complete Solution to help others

ViewController to call the im/export functions

- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
    //Call the NSManagedobject function to export
    NSDictionary *profileDict = [self.selectedProfile dictionaryForExport];

    if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES])
        NSLog(@"Saved");
    else
        NSLog(@"Not saved");
}

- (void) importProfileFromPath:(NSString *)path{
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];

    //load dictonary from file
    NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
    //call the NSManagedObjects import function
    [newProfile importWithDictonary:profileDict context:context];

    NSError *error = nil;
    if (![context save:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

NSManagedObject functions i got a hierarchy so i put them in each of my NSManagedObjects

- (void) importWithDictonary:(NSDictionary*)dict context:(NSManagedObjectContext*)context{
    self.name = [dict objectForKey:@"name"];

    //Relationship
    for (NSDictionary *view in [dict objectForKey:@"views"]) {
        View *tempView = [NSEntityDescription insertNewObjectForEntityForName:@"View" inManagedObjectContext:context];
        [tempView importWithDictonary:view context:context];
        tempView.profile = self;
        [self addViewsObject:tempView];
    }
}

- (NSDictionary*) dictionaryForExport{
    //propertys
    NSMutableDictionary *dict = [[[self dictionaryWithValuesForKeys:[[[self entity] attributesByName] allKeys]] mutableCopy] autorelease];
    NSURL *objectID = [[self objectID] URIRepresentation];
    [dict setObject: [objectID absoluteString] forKey:@"objectID"];
    NSMutableArray *views = [NSMutableArray array];

    //relationship
    for (View *view in self.views) {
        [views addObject:[view dictionaryForExport]];
    }
    [dict setObject:views forKey:@"views"];
    return dict;
}

not the most beautiful solution but it works :)

and i have still to figure out how to avoid duplicates in my n:m relationship

Thanks


问:
What does window.performance.getEntries() mean?
I thought that window.performance.getEntries() would match the number of requests according to Chromium's 'Network' tab, but that doesn't seem to be the case: http://i.stack.imgur.com/OfKtH.png. What am I missing?

答:
In my Case some Requests were missing, which occurred after the Page had finished loading.
The Networking Tab showed all Requests, but window.performance.getEntries() only Showed those who responded to the original Page Call (and not later actions on the Page). I believe performance.getEntries() and the Resource Timing API only concern themselves with the original building of the Page.


问:
Hadoop: start-dfs.sh permission denied
I am installing Hadoop on my laptop. SSH works fine, but I cannot start hadoop.

```<code>munichong@GrindPad:~$ ssh localhost
Welcome to Ubuntu 12.10 (GNU/Linux 3.5.0-25-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

0 packages can be updated.
0 updates are security updates.

Last login: Mon Mar  4 00:01:36 2013 from localhost

munichong@GrindPad:~$ /usr/sbin/start-dfs.sh
chown: changing ownership of `/var/log/hadoop/root': Operation not permitted
starting namenode, logging to /var/log/hadoop/root/hadoop-munichong-namenode-GrindPad.out
/usr/sbin/hadoop-daemon.sh: line 136: /var/run/hadoop/hadoop-munichong-namenode.pid: Permission denied
usr/sbin/hadoop-daemon.sh: line 135: /var/log/hadoop/root/hadoop-munichong-namenode-GrindPad.out: Permission denied
head: cannot open `/var/log/hadoop/root/hadoop-munichong-namenode-GrindPad.out' for reading: No such file or directory
localhost: chown: changing ownership of `/var/log/hadoop/root': Operation not permitted
localhost: starting datanode, logging to /var/log/hadoop/root/hadoop-munichong-datanode-GrindPad.out
localhost: /usr/sbin/hadoop-daemon.sh: line 135: /var/log/hadoop/root/hadoop-munichong-datanode-GrindPad.out: Permission denied
localhost: /usr/sbin/hadoop-daemon.sh: line 136: /var/run/hadoop/hadoop-munichong-datanode.pid: Permission denied
localhost: head: cannot open `/var/log/hadoop/root/hadoop-munichong-datanode-GrindPad.out' for reading: No such file or directory
localhost: chown: changing ownership of `/var/log/hadoop/root': Operation not permitted
localhost: starting secondarynamenode, logging to /var/log/hadoop/root/hadoop-munichong-secondarynamenode-GrindPad.out
localhost: /usr/sbin/hadoop-daemon.sh: line 136: /var/run/hadoop/hadoop-munichong-secondarynamenode.pid: Permission denied
localhost: /usr/sbin/hadoop-daemon.sh: line 135: /var/log/hadoop/root/hadoop-munichong-secondarynamenode-GrindPad.out: Permission denied
localhost: head: cannot open `/var/log/hadoop/root/hadoop-munichong-secondarynamenode-GrindPad.out' for reading: No such file or directory

munichong@GrindPad:~$ sudo /usr/sbin/start-dfs.sh
[sudo] password for munichong:
starting namenode, logging to /var/log/hadoop/root/hadoop-root-namenode-GrindPad.out
localhost: Permission denied (publickey,password).
localhost: Permission denied (publickey,password).
</code>```

I used "sudo". But the permission is still denied.

Is there anyone can help me?

Thanks in advance!

答:
R hadoop installation for permission denied issue, below command works for start-all.sh</p>

```<code>sudo chown -R hadoop /usr/local/hadoop/
</code>```

Title: Hadoop: start-dfs.sh permission denied

Body:
I am installing Hadoop on my laptop. SSH works fine, but I cannot start hadoop.

munichong@GrindPad:~$ ssh localhost
Welcome to Ubuntu 12.10 (GNU/Linux 3.5.0-25-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

0 packages can be updated.
0 updates are security updates.

Last login: Mon Mar  4 00:01:36 2013 from localhost

munichong@GrindPad:~$ /usr/sbin/start-dfs.sh
chown: changing ownership of `/var/log/hadoop/root': Operation not permitted
starting namenode, logging to /var/log/hadoop/root/hadoop-munichong-namenode-GrindPad.out
/usr/sbin/hadoop-daemon.sh: line 136: /var/run/hadoop/hadoop-munichong-namenode.pid: Permission denied
usr/sbin/hadoop-daemon.sh: line 135: /var/log/hadoop/root/hadoop-munichong-namenode-GrindPad.out: Permission denied
head: cannot open `/var/log/hadoop/root/hadoop-munichong-namenode-GrindPad.out' for reading: No such file or directory
localhost: chown: changing ownership of `/var/log/hadoop/root': Operation not permitted
localhost: starting datanode, logging to /var/log/hadoop/root/hadoop-munichong-datanode-GrindPad.out
localhost: /usr/sbin/hadoop-daemon.sh: line 135: /var/log/hadoop/root/hadoop-munichong-datanode-GrindPad.out: Permission denied
localhost: /usr/sbin/hadoop-daemon.sh: line 136: /var/run/hadoop/hadoop-munichong-datanode.pid: Permission denied
localhost: head: cannot open `/var/log/hadoop/root/hadoop-munichong-datanode-GrindPad.out' for reading: No such file or directory
localhost: chown: changing ownership of `/var/log/hadoop/root': Operation not permitted
localhost: starting secondarynamenode, logging to /var/log/hadoop/root/hadoop-munichong-secondarynamenode-GrindPad.out
localhost: /usr/sbin/hadoop-daemon.sh: line 136: /var/run/hadoop/hadoop-munichong-secondarynamenode.pid: Permission denied
localhost: /usr/sbin/hadoop-daemon.sh: line 135: /var/log/hadoop/root/hadoop-munichong-secondarynamenode-GrindPad.out: Permission denied
localhost: head: cannot open `/var/log/hadoop/root/hadoop-munichong-secondarynamenode-GrindPad.out' for reading: No such file or directory

munichong@GrindPad:~$ sudo /usr/sbin/start-dfs.sh
[sudo] password for munichong:
starting namenode, logging to /var/log/hadoop/root/hadoop-root-namenode-GrindPad.out
localhost: Permission denied (publickey,password).
localhost: Permission denied (publickey,password).

I used "sudo". But the permission is still denied.

Is there anyone can help me?

Thanks in advance!

Body:
R hadoop installation for permission denied issue, below command works for start-all.sh

sudo chown -R hadoop /usr/local/hadoop/


问:
Cookie::forget not working laravel 5.1
I'm trying to get Laravel 5.1 to delete my cookie, however it will not delete even though i'm returning it with my redirect.

```<code>return redirect('/voucher')->withCookie(Cookie::forget($cookie));
</code>```

Have I done something wrong?

答:
Recently I faced this issue while still on localhost but the issue was that I have written some code which weren't normal in my process of trying to overwrite the session config file.
Therefore
The default laravel

```<code>Cookie::queue(
   Cookie::forget('name')
      ) ;
</code>```

Should work perfectly fine if you have not done any changes on your
    session.php config file.
 Check it out and you should be good to go.
If you have made some changes try to ensure that your code conforms to standard and everything should work fine.

Title: Cookie::forget not working laravel 5.1

Body:
I'm trying to get Laravel 5.1 to delete my cookie, however it will not delete even though i'm returning it with my redirect.

return redirect('/voucher')->withCookie(Cookie::forget($cookie));

Have I done something wrong?

Body:
Recently I faced this issue while still on localhost but the issue was that I have written some code which weren't normal in my process of trying to overwrite the session config file.
Therefore
The default laravel

Cookie::queue(
   Cookie::forget('name')
      ) ;

Should work perfectly fine if you have not done any changes on your
    session.php config file.
 Check it out and you should be good to go.
If you have made some changes try to ensure that your code conforms to standard and everything should work fine.


问:
Convert list of tuple-1 of float to set of int
After querying a database, I get a result r of the following format:

```<code>r = [(123.0,), (456.0,), (789.0,)]
</code>```

That is a list of tuples, each with one item which is a float (that is actually an int).

I would like to convert that to a set of ints:

```<code>s = {123, 456, 789}
</code>```

I expected this to be a trivial map(), but I can't seem to write it. How do I tell map() I want to take the first element of the tuple?

I know that int(r[0][0]) gives me the first element of my set, int(r[1][0]) the second, int(r[2][0]) the third and so on, but how do I "industrialize" this?

答:
My program executes 2 jobs of 2 queries on separate databases (in order to compare the results): The queries of the first job return 35,694,726 records (tuples in the list).
The second job results in 47,176,395 tuples (in both lists).

In total there are 4 large lists to convert, giving some idea about the relative speed of the solutions.

All 3 solutions yield two set of 35,694,726 respectively 47,176,395 items. OK.

In each solution the first query result is treated faster than the second one. I guess one is better ordered than the other or something?

Here under, a result of "16.5/20.4/25.8/36.7" indicates that the first list of tuples was converted to a set in 16.5 seconds, that the second one took 20.4 seconds, third 25.5 and last 36.7 seconds.

Operator Lib Function   : 16.5/20.4/25.8/36.7

Using List Comprehension: 16.3/20.8/28.3/37.0

Map+Lambda              : 17.8/22.0/30.8/38.8

So there is a difference, but not much. The (concurrently executed) queries take 5 minutes, so a few seconds don't make a big difference, over all.

Map+Lambda is the slowest, as was predicted above. Since List Comprehension is a concise way of writing and does not need an import, that will be my solution of choice here.

Body:
After querying a database, I get a result r of the following format:

r = [(123.0,), (456.0,), (789.0,)]

That is a list of tuples, each with one item which is a float (that is actually an int).

I would like to convert that to a set of ints:

s = {123, 456, 789}

I expected this to be a trivial map(), but I can't seem to write it. How do I tell map() I want to take the first element of the tuple?

I know that int(r[0][0]) gives me the first element of my set, int(r[1][0]) the second, int(r[2][0]) the third and so on, but how do I "industrialize" this?


问:
Python Selenium: Unable to locate the element by Xpath
I am trying to click a save button via selenium, however, I am getting the error that it is unable to locate the element.

this is the html part of the website

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("xxx")

WebDriverWait(driver,10).until(EC.presence_of_element_located(driver.find_element_by_id("DivFlashViewerMain_SavePdfButtonIcon")))
driver.find_element_by_xpath('//*[@id="DivFlashViewerMain_SavePdfButtonIcon"]').click()
</code>```

This is the error I am getting:

NoSuchElementException: no such element: Unable to locate element:
  {"method":"id","selector":"DivFlashViewerMain_SavePdfButtonIcon"}

  (Session info: chrome=74.0.3729.169)   (Driver info:
  chromedriver=74.0.3729.6
  (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows
  NT 10.0.17763 x86_64)

答:
```<code>driver.find_elements_by_css_selector('[id="DivFlashViewerMain_SavePdfButtonIcon"]')[0].click()
</code>```

Seems like you are using a lot of functions, example for locating id="". Highly recommend trying css-selectors:
How to use querySelectorAll only for elements that have a specific attribute set?

Body:
I am trying to click a save button via selenium, however, I am getting the error that it is unable to locate the element.

this is the html part of the website

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("xxx")

WebDriverWait(driver,10).until(EC.presence_of_element_located(driver.find_element_by_id("DivFlashViewerMain_SavePdfButtonIcon")))
driver.find_element_by_xpath('//*[@id="DivFlashViewerMain_SavePdfButtonIcon"]').click()

This is the error I am getting:

NoSuchElementException: no such element: Unable to locate element:
  {"method":"id","selector":"DivFlashViewerMain_SavePdfButtonIcon"}

  (Session info: chrome=74.0.3729.169)   (Driver info:
  chromedriver=74.0.3729.6
  (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows
  NT 10.0.17763 x86_64)

Body:
driver.find_elements_by_css_selector('[id="DivFlashViewerMain_SavePdfButtonIcon"]')[0].click()

Seems like you are using a lot of functions, example for locating id="". Highly recommend trying css-selectors:
How to use querySelectorAll only for elements that have a specific attribute set?


问:
User Approval by email showing outputs but not updating records in database
I am currently working on a project where I need to get a user to sign up and then an email is sent to the website administrator's email with an approval link (containing the php page below, user email and sha512). When the approval link is clicked, it's meant to Update the table with the corresponding email and change isApproved to 1, but it does nothing other than printing the echos.

I tried changing the SQL commands, adding the ` around the names, looking it up on w3schools, stackoverflow and other forums and found nothing.

```<code><?php
    $hash = $_GET['h'];
    $email = $_GET['e'];

    if($hash == hash('sha512', 'ACCEPT')){
    $host = "redacted";
    $dbUsername = "redacted";
    $dbPassword = "redacted";
    $dbname = "redacted";
    //create connection
    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    if (mysqli_connect_error())
    {
        die('Connect Error('. mysqli_connect_errno().')'.mysqli_connect_error());
    }
    else
    {
        $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
        echo("approved");
    }
?>
</code>```

All I see when opening the website is "approved", which is what i expected, but the records in the database remain unchanged.

答:
That's because you are not running the query statement.

$sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email"; is a query which you wrote but did not executed it. You need to execute it using mysqli_query() method passing in the connection and query in parameters mysqli_query($conn, $sql);. You can read more about this here.

Updated Code:

```<code>   <?php
        $hash = $_GET['h'];
        $email = $_GET['e'];

        if($hash == hash('sha512', 'ACCEPT')){
        $host = "redacted";
        $dbUsername = "redacted";
        $dbPassword = "redacted";
        $dbname = "redacted";
        //create connection
        $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
        if (mysqli_connect_error())
        {
            die('Connect Error('. mysqli_connect_errno().')'.mysqli_connect_error());
        }
        else
        {
            $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
            mysqli_query($conn, $sql); // <------- Run SQL Query
            echo("approved");
        }
    ?>
</code>```

Body:
I am currently working on a project where I need to get a user to sign up and then an email is sent to the website administrator's email with an approval link (containing the php page below, user email and sha512). When the approval link is clicked, it's meant to Update the table with the corresponding email and change isApproved to 1, but it does nothing other than printing the echos.

I tried changing the SQL commands, adding the ` around the names, looking it up on w3schools, stackoverflow and other forums and found nothing.

<?php
    $hash = $_GET['h'];
    $email = $_GET['e'];

    if($hash == hash('sha512', 'ACCEPT')){
    $host = "redacted";
    $dbUsername = "redacted";
    $dbPassword = "redacted";
    $dbname = "redacted";
    //create connection
    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    if (mysqli_connect_error())
    {
        die('Connect Error('. mysqli_connect_errno().')'.mysqli_connect_error());
    }
    else
    {
        $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
        echo("approved");
    }
?>

All I see when opening the website is "approved", which is what i expected, but the records in the database remain unchanged.

Body:
That's because you are not running the query statement.

$sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email"; is a query which you wrote but did not executed it. You need to execute it using mysqli_query() method passing in the connection and query in parameters mysqli_query($conn, $sql);. You can read more about this here.

Updated Code:

   <?php
        $hash = $_GET['h'];
        $email = $_GET['e'];

        if($hash == hash('sha512', 'ACCEPT')){
        $host = "redacted";
        $dbUsername = "redacted";
        $dbPassword = "redacted";
        $dbname = "redacted";
        //create connection
        $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
        if (mysqli_connect_error())
        {
            die('Connect Error('. mysqli_connect_errno().')'.mysqli_connect_error());
        }
        else
        {
            $sql = "UPDATE `User` SET `isApproved`='1' WHERE `User`.`email`=$email";
            mysqli_query($conn, $sql); // <------- Run SQL Query
            echo("approved");
        }
    ?>


问:
How to apply glow effect on image android
I want to apply these types of glow effects on image view https://codepen.io/aundrekerr/pen/GtLul

In my app, I want to apply on https://prnt.sc/nu06gt
Is there a way to make the header on the Home listing kind of animate subtly like a gloss over w/ the pattern we have?  Like, have it on the angle of the lines.

```<code>  I have tried with facebook shimmer effect but it's not look like what I want
   https://facebook.github.io/shimmer-android/
</code>```

答:
first create a shape with some whit/grey gradient as a shine drawable

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
           <gradient
            android:angle="135"
            android:centerColor="#AAffffff"
            android:endColor="#00ffffff"
            android:startColor="#00ffffff"
            android:type="linear" />
</shape>
</code>```

and then you will add this drawable to your layout as overlay of you menu icon

```<code> <ImageView
        android:id="@+id/shine"
        android:layout_width="icon_width"
        android:layout_marginLeft="-50dp"
        android:layout_height="icon_height"
        android:src="@drawable/shine_effect" />
</code>```

Note that the width and height of the shine ImageView should had the same width and height as you menu icon .

and then in your logic side create an animation

```<code>    Animation animation = new TranslateAnimation(0, img.getWidth()+shine.getWidth(),0, 0); //img is menu icon , shine is gradient drawable
    animation.setDuration(550);
    animation.setFillAfter(false);
    animation.setInterpolator(new AccelerateDecelerateInterpolator());
    shine.startAnimation(animation);
</code>```

edit

i have updated the gradient example to make it fit your requirement and now to achieve the rest of the requirement you should add 2 another animation.

animation one with a duration of 225 that start with the main animation that increase size and alpha value (fade out effect) .

animation two with a duration of 225 that start with the end of animation one that decrease the size and alpha value (fade in effect)

hope you understand my example

Body:
I want to apply these types of glow effects on image view https://codepen.io/aundrekerr/pen/GtLul

In my app, I want to apply on https://prnt.sc/nu06gt
Is there a way to make the header on the Home listing kind of animate subtly like a gloss over w/ the pattern we have?  Like, have it on the angle of the lines.

  I have tried with facebook shimmer effect but it's not look like what I want
   https://facebook.github.io/shimmer-android/

Body:
first create a shape with some whit/grey gradient as a shine drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
           <gradient
            android:angle="135"
            android:centerColor="#AAffffff"
            android:endColor="#00ffffff"
            android:startColor="#00ffffff"
            android:type="linear" />
</shape>

and then you will add this drawable to your layout as overlay of you menu icon

 <ImageView
        android:id="@+id/shine"
        android:layout_width="icon_width"
        android:layout_marginLeft="-50dp"
        android:layout_height="icon_height"
        android:src="@drawable/shine_effect" />

Note that the width and height of the shine ImageView should had the same width and height as you menu icon .

and then in your logic side create an animation

    Animation animation = new TranslateAnimation(0, img.getWidth()+shine.getWidth(),0, 0); //img is menu icon , shine is gradient drawable
    animation.setDuration(550);
    animation.setFillAfter(false);
    animation.setInterpolator(new AccelerateDecelerateInterpolator());
    shine.startAnimation(animation);

edit

i have updated the gradient example to make it fit your requirement and now to achieve the rest of the requirement you should add 2 another animation.

animation one with a duration of 225 that start with the main animation that increase size and alpha value (fade out effect) .

animation two with a duration of 225 that start with the end of animation one that decrease the size and alpha value (fade in effect)

hope you understand my example


问:
How to fix this NullPointerException on executeQuery?
I Have a NullPointerException on the executeQuery of my simple sql statement; I think the problem come from the connection to sqlite but i cant figure it out...

My java method :

```<code>    public Connection connect() throws SQLException {
    Connection conn = null;
    try {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:sqlite:sakila.db.sqlite3";
        conn = DriverManager.getConnection(url);
        System.out.println("Connection to SQLite has been established.");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    Statement stmt = conn.createStatement();
    String sql = "SELECT * FROM FILM LIMIT 10";
    stmt.executeQuery(sql);
    return conn;
}
</code>```

And this is the result from the console

```<code>Connection to SQLite has been established.
Exception in thread "main" java.lang.NullPointerException
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at Connect.connect(Connect.java:33)
at Main.main(Main.java:10)
</code>```

Thanks in advance

答: looks like you're closing connection right before using it. Try to move statement + executeQuery inside the try-catch</p>

Body:
I Have a NullPointerException on the executeQuery of my simple sql statement; I think the problem come from the connection to sqlite but i cant figure it out...

My java method :

    public Connection connect() throws SQLException {
    Connection conn = null;
    try {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:sqlite:sakila.db.sqlite3";
        conn = DriverManager.getConnection(url);
        System.out.println("Connection to SQLite has been established.");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    Statement stmt = conn.createStatement();
    String sql = "SELECT * FROM FILM LIMIT 10";
    stmt.executeQuery(sql);
    return conn;
}

And this is the result from the console

Connection to SQLite has been established.
Exception in thread "main" java.lang.NullPointerException
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at Connect.connect(Connect.java:33)
at Main.main(Main.java:10)

Thanks in advance


问:
if user pastes 32 characters into the license text-box first split textbox
if user pastes 32 characters into the license text-box first split textbox, the method  will place 8 characters into each of the 4 text boxes

see
i have 4 text box ... max length (8)

```<code><input type = "text" size = "8" maxlength="32" name = "LicenseNumber1"
id="LicenseNumber1">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber2"
id="LicenseNumber2">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber3"
id="LicenseNumber3">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber4"
id="LicenseNumber4">
</code>```

& my license is 32 characters like 06e1823681f48e2f013904403b33ff08
now if i paste the whole 32 character in my first test box i.e. LicenseNumber1 then i

want other three textbox wil be automatic fill bcause(8*4=32)

答:
Here's a starting point. It works in all major browsers. You may want to extend it to handle input in the other three input boxes.

Code:

```<code>var inputs = [
    document.getElementById("LicenseNumber1"),
    document.getElementById("LicenseNumber2"),
    document.getElementById("LicenseNumber3"),
    document.getElementById("LicenseNumber4")
];

function handleInput(input) {
    var allText = input.value, inputToFocus = input;
    for (var i = 0, len = inputs.length; i < len; ++i) {
        if (allText.length > 0) {
            inputs[i].value = allText.slice(0, 8);
            inputToFocus = inputs[i];
            allText = allText.slice(8);
        }
    }
    window.setTimeout(function() {
        inputToFocus.focus();
    }, 1);
}

// IE 9 and non-IE
inputs[0].oninput = function() {
    handleInput(this);
};

// IE <= 8
var handlingValueChange = false;

inputs[0].onpropertychange = function() {
    if (window.event.propertyName == "value" && !handlingValueChange) {
        handlingValueChange = true;
        handleInput(this);
        handlingValueChange = false;
    }
};
</code>```

jsFiddle:

http://jsfiddle.net/DGzCx/6/

Body:
if user pastes 32 characters into the license text-box first split textbox, the method  will place 8 characters into each of the 4 text boxes

see
i have 4 text box ... max length (8)

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber1"
id="LicenseNumber1">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber2"
id="LicenseNumber2">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber3"
id="LicenseNumber3">

<input type = "text" size = "8" maxlength="32" name = "LicenseNumber4"
id="LicenseNumber4">

& my license is 32 characters like 06e1823681f48e2f013904403b33ff08
now if i paste the whole 32 character in my first test box i.e. LicenseNumber1 then i

want other three textbox wil be automatic fill bcause(8*4=32)

Body:
Here's a starting point. It works in all major browsers. You may want to extend it to handle input in the other three input boxes.

Code:

var inputs = [
    document.getElementById("LicenseNumber1"),
    document.getElementById("LicenseNumber2"),
    document.getElementById("LicenseNumber3"),
    document.getElementById("LicenseNumber4")
];

function handleInput(input) {
    var allText = input.value, inputToFocus = input;
    for (var i = 0, len = inputs.length; i < len; ++i) {
        if (allText.length > 0) {
            inputs[i].value = allText.slice(0, 8);
            inputToFocus = inputs[i];
            allText = allText.slice(8);
        }
    }
    window.setTimeout(function() {
        inputToFocus.focus();
    }, 1);
}

// IE 9 and non-IE
inputs[0].oninput = function() {
    handleInput(this);
};

// IE <= 8
var handlingValueChange = false;

inputs[0].onpropertychange = function() {
    if (window.event.propertyName == "value" && !handlingValueChange) {
        handlingValueChange = true;
        handleInput(this);
        handlingValueChange = false;
    }
};

jsFiddle:

http://jsfiddle.net/DGzCx/6/


问:
vmware workstation 15 player: Device/Credential Guard not compatible issue even disable it
My host is running Windows 10 enterprise. I got the vmware workstation 15 player issue: Device/Credential Guard not compatible issue when launching a VM.

I googled and and I followed the instructions https://learn.microsoft.com/en-us/windows/security/identity-protection/credential-guard/credential-guard-manage on disabling the device/credential guard, but still not working. I also tried https://www.youtube.com/watch?v=CGpv2Dvzyeg and it's the same issue. I read the stackoverflow posts related to this issue like VMware Workstation and Device/Credential Guard are not compatible but still does not help.

Any ideas why? I have no idea what to do next. Please help!!

答:
On my windows 10 1903 may 2019 update system with vmware player 15.1.0 [ or workstation ] installed i'll get this error from time to time when attempting to start vmplayer.exe [ or vmware.exe ].

The reason is not because of a device/credential guard compatibility issue that was resolved in earlier vmware player and workstation releases.  The reason is because i've forgotten to reboot system with the hyperv-v hypervisor disabled at boot.

As was noted in comments to your question by @magicandre1981 one solution is to uninstall the hyper-v feature and reboot. An alternative, especially if you need hyper-v at other times for vm or docker containers or phone emulator purpose,s is to just temporarily disable its hypervisor component.

This is accomplished using commands that have been been mentioned in other SO threads on this subject that must be run from a "Run as administrator" command prompt or powershell command line window.

```<code>hyper-v hypervisor disable = bcdedit /set hypervisorlaunchtype off
hyper-v hypervisor enable = bcdedit /set hypervisorlaunchtype auto
check if hyper-v hypervisor is enabled at boot = bcdedit /enum
</code>```

The last command will show hypervisorlaunchtype    Auto when its enabled at boot and hypervisorlaunchtype    Off when its disabled which is the state you need to use vmware player [ or workstation ].

If you are someone who maintains an open customized "Run as administrator" command prompt or powershell command line window at all the time you can optionally setup the following aliases / macros to simplify executing the above commands.

```<code>doskey hpvEnb = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype auto ^& echo.^&echo now reboot to enable hyper-v hypervisor )
doskey hpvDis = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype off ^& echo.^&echo now reboot to disable hyper-v hypervisor )
doskey bcdL = bcdedit /enum ^& echo.^&echo now see boot configuration data store {current} boot loader settings
</code>```

With the above in place you just type "hpvenb" [ hypervisor enabled at boot ], "hpvdis" [ hypervisor disabled at boot ] and "bcdl" [ boot configuration devices list ] commands to execute the on, off, list commands.

Body:
On my windows 10 1903 may 2019 update system with vmware player 15.1.0 [ or workstation ] installed i'll get this error from time to time when attempting to start vmplayer.exe [ or vmware.exe ].

The reason is not because of a device/credential guard compatibility issue that was resolved in earlier vmware player and workstation releases.  The reason is because i've forgotten to reboot system with the hyperv-v hypervisor disabled at boot.

As was noted in comments to your question by @magicandre1981 one solution is to uninstall the hyper-v feature and reboot. An alternative, especially if you need hyper-v at other times for vm or docker containers or phone emulator purpose,s is to just temporarily disable its hypervisor component.

This is accomplished using commands that have been been mentioned in other SO threads on this subject that must be run from a "Run as administrator" command prompt or powershell command line window.

hyper-v hypervisor disable = bcdedit /set hypervisorlaunchtype off
hyper-v hypervisor enable = bcdedit /set hypervisorlaunchtype auto
check if hyper-v hypervisor is enabled at boot = bcdedit /enum

The last command will show hypervisorlaunchtype    Auto when its enabled at boot and hypervisorlaunchtype    Off when its disabled which is the state you need to use vmware player [ or workstation ].

If you are someone who maintains an open customized "Run as administrator" command prompt or powershell command line window at all the time you can optionally setup the following aliases / macros to simplify executing the above commands.

doskey hpvEnb = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype auto ^& echo.^&echo now reboot to enable hyper-v hypervisor )
doskey hpvDis = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype off ^& echo.^&echo now reboot to disable hyper-v hypervisor )
doskey bcdL = bcdedit /enum ^& echo.^&echo now see boot configuration data store {current} boot loader settings

With the above in place you just type "hpvenb" [ hypervisor enabled at boot ], "hpvdis" [ hypervisor disabled at boot ] and "bcdl" [ boot configuration devices list ] commands to execute the on, off, list commands.