问:
Error while using Elasticsearch with Spring Boot
I'm trying to implement Elasticsearch in a Spring boot app, I followed the steps described in the documentation and everything works fine when it comes to client integration (using the recommended Hight Level Rest Client), mapping or indexing.. But when I try to query the documents I get the following error:

```<code>java.lang.NumberFormatException: For input string: "-Je513EBi1vVkAiBdanX"
</code>```

My config:

```<code>@Configuration
@EnableElasticsearchRepositories
public class ElasticConfig extends AbstractElasticsearchConfiguration {

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration configuration = ClientConfiguration.localhost();
        RestHighLevelClient client = RestClients.create(configuration).rest();
        return client;
    }

    @Bean
    public ElasticsearchRestTemplate elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
}
</code>```

My repository:

```<code>@Repository
public interface UserRepository extends ElasticsearchRepository<User, Long> {
    List<User> findByName(String name);
}
</code>```

My Service:

```<code>public List<User> getUsers(String qry){
    return userRepository.findByName(qry);
}
</code>```

My Model:

```<code>@Document(indexName = "users")
public class User {

    @Id private Long id;
    private String name;
    private String username;
    private String avatar;
    private String bio;
    private boolean checked;

    public User() { }

    public User(
            @JsonProperty("id") Long id,
            @JsonProperty("name") String name,
            @JsonProperty("username") String username,
            @JsonProperty("avatar") String avatar,
            @JsonProperty("bio") String bio,
            @JsonProperty("checked") boolean checked) {
        this.id = id;
        this.name = name;
        this.username = username;
        this.avatar = avatar;
        this.bio = bio;
        this.checked = checked;
    }

    // Getters
    // Setters
}
</code>```

答:
Can you confirm the version of Spring Data and Elasticsearch you are using? In addition, I'm a bit concerned on the way you implemented your RestHighLevelClient. You refer to a localhost but what about the port?
Please find a snippet of working code below: </p>

```<code>    @Bean
public RestHighLevelClient elasticRestClient () {
    String[] httpHosts = httpHostsProperty.split(";");
    HttpHost[] httpHostsAsArray = new HttpHost[httpHosts.length];
    int index = 0;

    for (String httpHostAsString : httpHosts) {
        HttpHost httpHost = new HttpHost(httpHostAsString.split(":")[0], new Integer(httpHostAsString.split(":")[1]), "http");
        httpHostsAsArray[index++] = httpHost;
    }

    RestClientBuilder restClientBuilder = RestClient.builder(httpHostsAsArray)
            .setRequestConfigCallback(builder -> builder
                    .setConnectTimeout(connectTimeOutInMs)
                    .setSocketTimeout(socketTimeOutInMs)
            );

    return new RestHighLevelClient(restClientBuilder);
}
</code>```

Body:
I'm trying to implement Elasticsearch in a Spring boot app, I followed the steps described in the documentation and everything works fine when it comes to client integration (using the recommended Hight Level Rest Client), mapping or indexing.. But when I try to query the documents I get the following error:

java.lang.NumberFormatException: For input string: "-Je513EBi1vVkAiBdanX"

My config:

@Configuration
@EnableElasticsearchRepositories
public class ElasticConfig extends AbstractElasticsearchConfiguration {

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration configuration = ClientConfiguration.localhost();
        RestHighLevelClient client = RestClients.create(configuration).rest();
        return client;
    }

    @Bean
    public ElasticsearchRestTemplate elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
}

My repository:

@Repository
public interface UserRepository extends ElasticsearchRepository<User, Long> {
    List<User> findByName(String name);
}

My Service:

public List<User> getUsers(String qry){
    return userRepository.findByName(qry);
}

My Model:

@Document(indexName = "users")
public class User {

    @Id private Long id;
    private String name;
    private String username;
    private String avatar;
    private String bio;
    private boolean checked;

    public User() { }

    public User(
            @JsonProperty("id") Long id,
            @JsonProperty("name") String name,
            @JsonProperty("username") String username,
            @JsonProperty("avatar") String avatar,
            @JsonProperty("bio") String bio,
            @JsonProperty("checked") boolean checked) {
        this.id = id;
        this.name = name;
        this.username = username;
        this.avatar = avatar;
        this.bio = bio;
        this.checked = checked;
    }

    // Getters
    // Setters
}

Body:
Can you confirm the version of Spring Data and Elasticsearch you are using? In addition, I'm a bit concerned on the way you implemented your RestHighLevelClient. You refer to a localhost but what about the port?
Please find a snippet of working code below:

    @Bean
public RestHighLevelClient elasticRestClient () {
    String[] httpHosts = httpHostsProperty.split(";");
    HttpHost[] httpHostsAsArray = new HttpHost[httpHosts.length];
    int index = 0;

    for (String httpHostAsString : httpHosts) {
        HttpHost httpHost = new HttpHost(httpHostAsString.split(":")[0], new Integer(httpHostAsString.split(":")[1]), "http");
        httpHostsAsArray[index++] = httpHost;
    }

    RestClientBuilder restClientBuilder = RestClient.builder(httpHostsAsArray)
            .setRequestConfigCallback(builder -> builder
                    .setConnectTimeout(connectTimeOutInMs)
                    .setSocketTimeout(socketTimeOutInMs)
            );

    return new RestHighLevelClient(restClientBuilder);
}


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Way to replace NA string to Consecutive dates linux

Body:
This is CSV file that I got

2020-03-05,0,146541,118965,5766,88,35
2020-03-06,0,164740,136624,6284,108,42
MISSINGDATE,0,178189,151802,6767,118,44
2020-03-08,0,188518,162008,7134,130,50
2020-03-09,0,196618,171778,7382,166,51
MISSINGDATE,0,210144,184179,7513,247,54

I'm trying to change "MISSINGDATE" part in the column into an appropriate date that consequence with date in the previous line.

I was able to designate "MISSINGDATE" with sed command but didn't figure out to way to change it consequently.

when I did

sed -i "s/[MISSINGDATE]/[date that I want]//g" file

it only fixed NA date to date that I typed in...

the result that I want is

2020-03-05,0,146541,118965,5766,88,35
2020-03-06,0,164740,136624,6284,108,42
2020-03-07,0,178189,151802,6767,118,44
2020-03-08,0,188518,162008,7134,130,50
2020-03-09,0,196618,171778,7382,166,51
2020-03-10,0,210144,184179,7513,247,54

Body:
If gawk is your option, would you please try the following:

gawk '
BEGIN {
    FS = OFS = ","                              # set field separator
    prev_date = "1970-01-01"                    # initial value just in case
}
function nextdate(day, epoch) {
    gsub("-", " ", day)                         # replace "-" with " "
    epoch = mktime(day " 0 0 0")                # seconds since the epoch
    return strftime("%Y-%m-%d", epoch + 86400)  # add one day
}
{
    if ($1 == "MISSINGDATE" ) {                 # if the date is missing
        $1 = nextdate(prev_date)                # then use the prev_date + 1day
    }
    prev_date = $1                              # update prev_date
    print
}' file.csv

Result:

2020-03-05,0,146541,118965,5766,88,35
2020-03-06,0,164740,136624,6284,108,42
2020-03-07,0,178189,151802,6767,118,44
2020-03-08,0,188518,162008,7134,130,50
2020-03-09,0,196618,171778,7382,166,51
2020-03-10,0,210144,184179,7513,247,54


问:
Adding a UI animated framework component with jquery
I'm building a simple single-page website, and when I click a button on the page, I want to remove some content, display a loading spin bar (https://getmdl.io/components/index.html#loading-section), fetch data from an API, display the received data, and then remove the loading spinner.

However, when I try to use the material design lite spinner by adding it with jquery like so:

```<code>$("body").append("<div class=\"mdl-spinner mdl-js-spinner is-active\"></div>")
</code>```

it just gives me the word Loading and no animated spinner. Is there a flaw in my understanding, or does something else need to be added for it to work?

答:
Material must be initializing some script on load and it will update your spinner element. But when you add later from jquery it will not initialize script. So it doesn't work.

Here is one work around for your situation. Just add spinner div with display:none like
. And show/hide div as per your requirement.

I have performed show/hide on button click. You can customize it based on your requirement. Check below demo.

function ShowProgressBar() {
  $("#spinner").show();
  $("#show").hide();
  $("#hide").show();
}

function HideProgressBar() {
  $("#spinner").hide();
  $("#show").show();
  $("#hide").hide();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   </code>```

<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

  <input id="show" type="button" onclick="ShowProgressBar()" value="show" />
  <input id="hide" type="button" onclick="HideProgressBar()" value="hide" style="display:none;" />

```

Body:
I'm building a simple single-page website, and when I click a button on the page, I want to remove some content, display a loading spin bar (https://getmdl.io/components/index.html#loading-section), fetch data from an API, display the received data, and then remove the loading spinner.

However, when I try to use the material design lite spinner by adding it with jquery like so:

$("body").append("

")

it just gives me the word Loading and no animated spinner. Is there a flaw in my understanding, or does something else need to be added for it to work?

Body:
Material must be initializing some script on load and it will update your spinner element. But when you add later from jquery it will not initialize script. So it doesn't work.

Here is one work around for your situation. Just add spinner div with display:none like <div id="spinner" class="mdl-spinner mdl-js-spinner is-active" style="display:none;">. And show/hide div as per your requirement.

I have performed show/hide on button click. You can customize it based on your requirement. Check below demo.

function ShowProgressBar() {
  $("#spinner").show();
  $("#show").hide();
  $("#hide").show();
}

function HideProgressBar() {
  $("#spinner").hide();
  $("#show").show();
  $("#hide").hide();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Material Design Lite -->
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<!-- Material Design icon font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

<!-- MDL Spinner Component -->
<div id="spinner" class="mdl-spinner mdl-js-spinner is-active" style="display:none;"></div>

<div>
  <input id="show" type="button" onclick="ShowProgressBar()" value="show" />
  <input id="hide" type="button" onclick="HideProgressBar()" value="hide" style="display:none;" />
</div>


问:
why isnt my code printing out the highest and 1st runner up properly?
Main:

```<code>public class Main {

  private static String [] Countries={"UK", "Italy",
            "Germany", "Thailand","Denmark","Japan","Spain","Argentina"};
  static double average[] = new double[8];
  double[] results = new double[8];

  public static String getWinner(ArrayList<MissUniverse>alist){
    int winner = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() ) {
            winner= s;
        }
    }
    return alist.get(winner).getCountry();
  }

public static String firstRunnerUp(ArrayList<MissUniverse>alist){
    int firstrunnerUp =0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
            firstrunnerUp = s;
        }
    }
    return alist.get(firstrunnerUp).getCountry();

  }

 public static void main (String[] args){
   ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
 MissUniverse missUniverse[] = new MissUniverse[Countries.length];

        for(int i=0;i<Countries.length;i++)
        {
            missUniverse[i] = new MissUniverse(Countries[i]);
            missUniverse[i].getScore();
            alist.add(missUniverse[i]);
        }

   System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-10s",
                "Countries","1","2","3","4","5","6","7","8","Average");
    System.out.println();
    for (int i = 0; i < Countries.length; i++){
    System.out.printf("%-13s",Countries[i]);
    missUniverse[i].printInfo();
    System.out.printf("%5.1f", alist.get(i).average() );
    System.out.println();
    }
    System.out.println("The result is");
    System.out.println("Winner: Miss " + getWinner(alist) );
    System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );

  }
}
</code>```

MissUniverse:

```<code>class MissUniverse {
  public static int SIZE=8;
  private String country;
  private double[] score;

  public MissUniverse(String country){
    this.country = country;
    score = new double [SIZE];
  }

  public String getCountry(){
    return country;
  }

  public void getScore(){
      for (int i=0;i<score.length;i++)
        {
            score[i] = Math.random()*10;
        }
  }

  public void setCountry(String newCountry) {
    this.country = newCountry;
  }

 private int highest(){
  int i;
        double highest;
        highest = score[0];

        for (i = 0; i <score.length; i++)
        {
            if (highest < score [i])
            {
                highest = score[i] ;
            }
        }
        return i;
  }

  private int lowest(){
  int i;
        double lowest;
        lowest = score[0];
        for (i = 0; i <score.length; i++)
        {
            if (lowest > score [i])
            {
                lowest = score[i];
            }
        }
        return i;
  }

  public double average(){

    double sum = 0.0;
     for (int i = 0; i < score.length; i++){
        sum +=  score[i];
     }
    double average;
    average = (sum - score[lowest()-1] - score[highest()-1] )/ (score.length - 2);
    return average;
  }

  public void printInfo(){

      for(int i=0;i< score.length;i++){
      System.out.printf("%-5.1f",score[i]);
      }

  }
}
</code>```

Why is the output wrong?

output 1:

```<code>Countries      1    2    3    4    5    6    7    8    Average
UK           2.0  0.5  3.7  2.0  5.2  7.0  9.2  5.8    4.0
Italy        3.9  3.8  2.4  5.1  5.7  1.0  6.7  6.9    3.6
Germany      7.0  0.5  8.4  2.4  6.3  4.4  8.8  7.1    5.1
Thailand     6.9  8.7  3.9  4.7  4.9  3.5  4.7  9.4    4.7
Denmark      0.5  0.9  3.4  3.3  6.3  10.0 7.0  6.6    4.1
Japan        4.2  2.1  5.9  9.4  9.8  2.3  4.2  9.7    4.7
Spain        6.5  4.0  6.5  3.6  8.5  8.5  9.2  9.4    6.2
Argentina    0.4  6.6  6.5  2.3  2.6  4.5  5.6  3.7    4.1
The result is
Winner: Miss Argentina
1st Runner Up: Miss Spain
</code>```

its supposed to be winner: miss spain, runner up: miss germany.
but isnt the logic in getWinner(alist) and firstrunnerup(alist) correct?

output 2:

```<code>Countries      1    2    3    4    5    6    7    8    Average
UK           0.5  9.2  2.8  1.3  7.0  9.6  6.9  6.9    5.1
Italy        4.3  7.6  2.3  3.3  8.6  9.3  7.0  3.1    6.5
Germany      2.2  0.4  6.1  4.4  5.8  3.1  5.5  9.1    3.1
Thailand     1.7  7.1  6.2  9.5  7.9  4.9  0.8  8.3    5.0
Denmark      1.6  1.6  2.5  6.5  8.8  5.8  3.7  1.2    4.9
Japan        7.4  1.5  5.6  1.6  3.1  5.8  3.2  3.4    4.1
Spain        0.2  0.9  0.3  7.2  1.5  7.8  7.3  8.6    2.7
Argentina    9.1  8.9  0.3  5.1  2.6  8.8  4.3  5.1    5.7
The result is
Winner: Miss Argentina
1st Runner Up: Miss Italy
</code>```

its supposed to be:
winner:italy
runner up:argentina

can someone point me in the right direction?i think the mistake is supposed to be in the getwinner and firstrunnerup methods but i can't spot the mistake.

答:
You are comparing wrong variables in getWinner and firstRunnerUp. Replace the functions with the following ones:

```<code>
public static String getWinner(ArrayList<MissUniverse> alist){
    int winner = 0;
    double max = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > max) {
            max = alist.get(s).average();
            winner = s;
        }
    }
    return alist.get(winner).getCountry();
}

public static String firstRunnerUp(ArrayList<MissUniverse> alist){
    int firstrunnerUp = 0;
    double winner = 0;
    double max = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > max) {
            firstrunnerUp = winner;
            winner = s;
            max = alist.get(s).average();
        }
    }
    return alist.get(firstrunnerUp).getCountry();
}
</code>```

Body:
Main:

public class Main {

  private static String [] Countries={"UK", "Italy",
            "Germany", "Thailand","Denmark","Japan","Spain","Argentina"};
  static double average[] = new double[8];
  double[] results = new double[8];

  public static String getWinner(ArrayList<MissUniverse>alist){
    int winner = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() ) {
            winner= s;
        }
    }
    return alist.get(winner).getCountry();
  }

public static String firstRunnerUp(ArrayList<MissUniverse>alist){
    int firstrunnerUp =0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
            firstrunnerUp = s;
        }
    }
    return alist.get(firstrunnerUp).getCountry();

  }

 public static void main (String[] args){
   ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
 MissUniverse missUniverse[] = new MissUniverse[Countries.length];

        for(int i=0;i<Countries.length;i++)
        {
            missUniverse[i] = new MissUniverse(Countries[i]);
            missUniverse[i].getScore();
            alist.add(missUniverse[i]);
        }

   System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-5s%-10s",
                "Countries","1","2","3","4","5","6","7","8","Average");
    System.out.println();
    for (int i = 0; i < Countries.length; i++){
    System.out.printf("%-13s",Countries[i]);
    missUniverse[i].printInfo();
    System.out.printf("%5.1f", alist.get(i).average() );
    System.out.println();
    }
    System.out.println("The result is");
    System.out.println("Winner: Miss " + getWinner(alist) );
    System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );

  }
}

MissUniverse:

class MissUniverse {
  public static int SIZE=8;
  private String country;
  private double[] score;

  public MissUniverse(String country){
    this.country = country;
    score = new double [SIZE];
  }

  public String getCountry(){
    return country;
  }

  public void getScore(){
      for (int i=0;i<score.length;i++)
        {
            score[i] = Math.random()*10;
        }
  }

  public void setCountry(String newCountry) {
    this.country = newCountry;
  }

 private int highest(){
  int i;
        double highest;
        highest = score[0];

        for (i = 0; i <score.length; i++)
        {
            if (highest < score [i])
            {
                highest = score[i] ;
            }
        }
        return i;
  }

  private int lowest(){
  int i;
        double lowest;
        lowest = score[0];
        for (i = 0; i <score.length; i++)
        {
            if (lowest > score [i])
            {
                lowest = score[i];
            }
        }
        return i;
  }

  public double average(){

    double sum = 0.0;
     for (int i = 0; i < score.length; i++){
        sum +=  score[i];
     }
    double average;
    average = (sum - score[lowest()-1] - score[highest()-1] )/ (score.length - 2);
    return average;
  }

  public void printInfo(){

      for(int i=0;i< score.length;i++){
      System.out.printf("%-5.1f",score[i]);
      }

  }
}

Why is the output wrong?

output 1:

Countries      1    2    3    4    5    6    7    8    Average
UK           2.0  0.5  3.7  2.0  5.2  7.0  9.2  5.8    4.0
Italy        3.9  3.8  2.4  5.1  5.7  1.0  6.7  6.9    3.6
Germany      7.0  0.5  8.4  2.4  6.3  4.4  8.8  7.1    5.1
Thailand     6.9  8.7  3.9  4.7  4.9  3.5  4.7  9.4    4.7
Denmark      0.5  0.9  3.4  3.3  6.3  10.0 7.0  6.6    4.1
Japan        4.2  2.1  5.9  9.4  9.8  2.3  4.2  9.7    4.7
Spain        6.5  4.0  6.5  3.6  8.5  8.5  9.2  9.4    6.2
Argentina    0.4  6.6  6.5  2.3  2.6  4.5  5.6  3.7    4.1
The result is
Winner: Miss Argentina
1st Runner Up: Miss Spain

its supposed to be winner: miss spain, runner up: miss germany.
but isnt the logic in getWinner(alist) and firstrunnerup(alist) correct?

output 2:

Countries      1    2    3    4    5    6    7    8    Average
UK           0.5  9.2  2.8  1.3  7.0  9.6  6.9  6.9    5.1
Italy        4.3  7.6  2.3  3.3  8.6  9.3  7.0  3.1    6.5
Germany      2.2  0.4  6.1  4.4  5.8  3.1  5.5  9.1    3.1
Thailand     1.7  7.1  6.2  9.5  7.9  4.9  0.8  8.3    5.0
Denmark      1.6  1.6  2.5  6.5  8.8  5.8  3.7  1.2    4.9
Japan        7.4  1.5  5.6  1.6  3.1  5.8  3.2  3.4    4.1
Spain        0.2  0.9  0.3  7.2  1.5  7.8  7.3  8.6    2.7
Argentina    9.1  8.9  0.3  5.1  2.6  8.8  4.3  5.1    5.7
The result is
Winner: Miss Argentina
1st Runner Up: Miss Italy

its supposed to be:
winner:italy
runner up:argentina

can someone point me in the right direction?i think the mistake is supposed to be in the getwinner and firstrunnerup methods but i can't spot the mistake.

Body:
You are comparing wrong variables in getWinner and firstRunnerUp. Replace the functions with the following ones:

public static String getWinner(ArrayList<MissUniverse> alist){
    int winner = 0;
    double max = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > max) {
            max = alist.get(s).average();
            winner = s;
        }
    }
    return alist.get(winner).getCountry();
}

public static String firstRunnerUp(ArrayList<MissUniverse> alist){
    int firstrunnerUp = 0;
    double winner = 0;
    double max = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > max) {
            firstrunnerUp = winner;
            winner = s;
            max = alist.get(s).average();
        }
    }
    return alist.get(firstrunnerUp).getCountry();
}


答:
1) To count the number of instances inside each group which meets the condition per day.

```<code>library(data.table)
setDT(df)
df[, .(count = sum(status == 1)), .(timestamp, type)]

#    timestamp type count
#1: 05-01-2020    A     4
#2: 05-01-2020    B     1
#3: 06-01-2020    A     2
#4: 06-01-2020    B     0
#5: 07-01-2020    A     3
#6: 07-01-2020    B     2
#7: 08-01-2020    B     2
#8: 09-01-2020    B     2
#9: 11-01-2020    A     2
</code>```

You can remove the 0 counts if they are not needed.

2) To find the number of groups per day which meet the condition.

Create a new column (count_N) using rleid of type and status and for status = 1 count unique values for each timestamp and type.

```<code>df[, count_N := rleid(type, status), timestamp]
df[status == 1, .(count = uniqueN(count_N)), .(timestamp, type)]

#    timestamp type count
#1: 05-01-2020    A     1
#2: 05-01-2020    B     1
#3: 06-01-2020    A     1
#4: 07-01-2020    A     2
#5: 07-01-2020    B     1
#6: 08-01-2020    B     1
#7: 09-01-2020    B     2
#8: 11-01-2020    A     1
</code>```

Title: R datatable grouping based on condition and getting count based on the conditions

Body:
I have a data table like this :

timestamp           type    status
05-01-2020 12:07:08    A      1
05-01-2020 12:36:05    A      1
05-01-2020 13:34:25    A      1
05-01-2020 23:45:02    A      1
05-01-2020 23:55:02    B      1
05-01-2020 13:44:33    B      2
06-01-2020 01:07:08    A      1
06-01-2020 10:23:05    A      1
06-01-2020 12:11:08    A      2
06-01-2020 22:06:12    B      2
07-01-2020 00:01:05    A      2
07-01-2020 02:17:09    A      1
07-01-2020 12:36:05    B      1
07-01-2020 12:07:08    B      1
07-01-2020 12:36:05    A      1
07-01-2020 12:36:05    A      1
08-01-2020 12:36:05    B      2
08-01-2020 12:36:05    B      1
08-01-2020 12:36:05    B      1
09-01-2020 12:36:05    B      1
09-01-2020 12:07:08    B      2
09-01-2020 12:36:05    B      1
11-01-2020 12:07:08    A      1
11-01-2020 12:36:05    A      1

I am trying to group it on date and type using rleid().

dt <- dt[, group_id := rleid(as.IDate(timestamp),type,status = 1)][]

Now I want to get two counts.

One is to count the number of instances inside each group which meets the condition per day.

date         type  count
05-01-2020    A      4
05-01-2020    B      1
06-01-2020    A      2
07-01-2020    A      3
07-01-2020    B      2
08-01-2020    B      2
09-01-2020    B      2
11-01-2020    A      2

Second one is to find the number of groups per day which meet the condition.

date         type  count
05-01-2020    A      1
05-01-2020    B      1
06-01-2020    A      1
07-01-2020    A      2
07-01-2020    B      1
08-01-2020    B      1
09-01-2020    B      2
11-01-2020    A      1

Body:
1) To count the number of instances inside each group which meets the condition per day.

library(data.table)
setDT(df)
df[, .(count = sum(status == 1)), .(timestamp, type)]

#    timestamp type count
#1: 05-01-2020    A     4
#2: 05-01-2020    B     1
#3: 06-01-2020    A     2
#4: 06-01-2020    B     0
#5: 07-01-2020    A     3
#6: 07-01-2020    B     2
#7: 08-01-2020    B     2
#8: 09-01-2020    B     2
#9: 11-01-2020    A     2

You can remove the 0 counts if they are not needed.

2) To find the number of groups per day which meet the condition.

Create a new column (count_N) using rleid of type and status and for status = 1 count unique values for each timestamp and type.

df[, count_N := rleid(type, status), timestamp]
df[status == 1, .(count = uniqueN(count_N)), .(timestamp, type)]

#    timestamp type count
#1: 05-01-2020    A     1
#2: 05-01-2020    B     1
#3: 06-01-2020    A     1
#4: 07-01-2020    A     2
#5: 07-01-2020    B     1
#6: 08-01-2020    B     1
#7: 09-01-2020    B     2
#8: 11-01-2020    A     1


问:
How to use a single variable which can have multiple data types in C++
How can a variable have 2 data types? If "month" is a variable and it should be take from input with std::cin. What should I do so that the user can enter a string like "January" or enter an integer like 1?</p>

答:
In C++ 17 we got something called std::variant it is basicaly a type safe union
to use it you just declare the types you need:

```<code>std::variant<int, std::string> data;

data = "Hello!";
data = 13;
// No Compilation Issues
</code>```

The Hard Part Is When You Want To Retrieve The Data

```<code>std::string& text = std::get<std::string>(data):
int& number = std::get<int>(data);
</code>```

BUT MAKE SURE THE LAST THING YOU DEFINED IT AS IS THE TYPE YOU ARE TRYING TO RETRIEVE MEANING:

```<code>data = 13;
std::string& text = std::get<std::string>(data); // Bad Exception Error
</code>```

A better thing is to use std::get_if

```<code>if (auto temp = std::get_if<std::string>(&data);
    std::string& text = *temp; // do what ever you want
</code>```

I Hope this answerd Your Question Happy Coding!

Body:
In C++ 17 we got something called std::variant it is basicaly a type safe union
to use it you just declare the types you need:

std::variant<int, std::string> data;

data = "Hello!";
data = 13;
// No Compilation Issues

The Hard Part Is When You Want To Retrieve The Data

std::string& text = std::get<std::string>(data):
int& number = std::get<int>(data);

BUT MAKE SURE THE LAST THING YOU DEFINED IT AS IS THE TYPE YOU ARE TRYING TO RETRIEVE MEANING:

data = 13;
std::string& text = std::get<std::string>(data); // Bad Exception Error

A better thing is to use std::get_if

if (auto temp = std::get_if<std::string>(&data);
    std::string& text = *temp; // do what ever you want

I Hope this answerd Your Question Happy Coding!


问:
How do I do an IF in Microsoft SQL SELECT query?
I am an absolute beginner in SQL.
Example:
I want to do a query to select people whose names begin with X if the result is 0, I want to select people whose names begin with Y.

How do I do this? Thanks.

答:
May be this is a better solution:</p>

```<code>select * from table where name like 'X%'

if @@ROWCOUNT = 0
   select * from table where name like 'Y%'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
May be this is a better solution:

select * from table where name like 'X%'

if @@ROWCOUNT = 0
   select * from table where name like 'Y%'


问:
change value of dropdownlist based of another dropdwonlis using ajax jquery on Core MVC ASP.NET
```<code><div class="form-group">
    @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                       " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })
    <br />
    @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                       " -- Sélectionnez Local --", new { @class = "form-control" })

</div>
</code>```

I have list of Center and list of local :what i want is when i select Any dropdownlist of center other than local DropDownListFor local has to change.
Controller Action :

```<code>[HttpPost]
        public JsonResult GetLocalsList(int id)
        {
            List<Local> lstLocal= new List<Local>();
            lstLocal = objLocal.GetLocalsData(id).ToList();
            return Json(lstLocal);

        }
</code>```

and view :

```<code><div class="form-group">
    @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                       " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })
    <br />
    @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                       " -- Sélectionnez Local --", new { @class = "form-control" })

</div>
<script>
    $(document).ready(function () {
        var data = $(this).val();
        $.ajax({
            url: "@Url.Action("GetLocalsList")",
            type: "POST",
            contentType: 'application/x-www-form-urlencoded',
            data: data,
            dataType: "json",
            success: function (data) {
                console.log(data);
            $.each(data, function (index, row) {
                        $("#ddlLocal").append("<option value='" + row.id + "'>" + row.id + "</option>")
                    });
                   },
            error: function (req, status, error) {
                alert(error);
            }
        });
    });
    </script>
</code>```

答:
If you wan to  change value of dropdownlist based of another dropdwonlis,you use the method $(“”).change,and if you want to pass the data by ajax to controller,you can do liking the following code：

```<code><div class="form-group">
    @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                       " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })
    <br />
    @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                       " -- Sélectionnez Local --", new { @class = "form-control" })

</div>
@section scripts{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
        $("#ddlCentre").change(function () {
            $("#ddlLocal").empty().append('<option>-- Sélectionnez Local --</option>');
            var id = $(this).val();
            if (id != "") {
                $.ajax({
                url: "@Url.Action("GetLocalsList")",
                type: "POST",
                contentType: 'application/x-www-form-urlencoded',
                data: { 'id': id },
            dataType: "json",
            success: function (data) {
                console.log(data);
            $.each(data, function (index, row) {
                        $("#ddlLocal").append("<option value='" + row.id + "'>" + row.name + "</option>")
                    });
                   },
            error: function (req, status, error) {
                alert(error);
            }
        });
            }

        })
    </script>
}
</code>```

This is my controller:

```<code>public static List<Local> Locals = new List<Local> { new Local { Id = "1", Name = "Local1", CenterId = "1" }, new Local { Id = "2", Name = "Local2", CenterId = "2" } };
    public static List<Center> Centers = new List<Center> { new Center { Id = "1", Name = "Center1" }, new Center { Id = "2", Name = "Center2" } };
    public IActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public JsonResult GetLocalsList(int id)
    {

        List<Local> lstLocal = new List<Local>();
        lstLocal = Locals.Where(l =>l.CenterId==id.ToString()).ToList();
        return Json(lstLocal);

    }
    [HttpGet]
    public IActionResult GetLocalsList()
    {
        List<SelectListItem> lstLocal = new List<SelectListItem>();
        foreach (Center center in Centers) {
            lstLocal.Add(new SelectListItem { Value = center.Id, Text = center.Name });
        }
        ViewBag.ddlCentre = lstLocal;

        return View();

    }
</code>```

Body:
    @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                       " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })

    @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                       " -- Sélectionnez Local --", new { @class = "form-control" })

I have list of Center and list of local :what i want is when i select Any dropdownlist of center other than local DropDownListFor local has to change.
Controller Action :

[HttpPost]
        public JsonResult GetLocalsList(int id)
        {
            List<Local> lstLocal= new List<Local>();
            lstLocal = objLocal.GetLocalsData(id).ToList();
            return Json(lstLocal);

        }

and view :

    @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                       " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })

    @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                       " -- Sélectionnez Local --", new { @class = "form-control" })

Body:
If you wan to  change value of dropdownlist based of another dropdwonlis,you use the method $(“”).change,and if you want to pass the data by ajax to controller,you can do liking the following code：

<div class="form-group">
    @Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
                       " -- Sélectionnez Centre Commercial --", new { @class = "form-control" })
    <br />
    @Html.DropDownList("ddlLocal", new List<SelectListItem>(),
                       " -- Sélectionnez Local --", new { @class = "form-control" })

</div>
@section scripts{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
        $("#ddlCentre").change(function () {
            $("#ddlLocal").empty().append('<option>-- Sélectionnez Local --</option>');
            var id = $(this).val();
            if (id != "") {
                $.ajax({
                url: "@Url.Action("GetLocalsList")",
                type: "POST",
                contentType: 'application/x-www-form-urlencoded',
                data: { 'id': id },
            dataType: "json",
            success: function (data) {
                console.log(data);
            $.each(data, function (index, row) {
                        $("#ddlLocal").append("<option value='" + row.id + "'>" + row.name + "</option>")
                    });
                   },
            error: function (req, status, error) {
                alert(error);
            }
        });
            }

        })
    </script>
}

This is my controller:

public static List<Local> Locals = new List<Local> { new Local { Id = "1", Name = "Local1", CenterId = "1" }, new Local { Id = "2", Name = "Local2", CenterId = "2" } };
    public static List<Center> Centers = new List<Center> { new Center { Id = "1", Name = "Center1" }, new Center { Id = "2", Name = "Center2" } };
    public IActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public JsonResult GetLocalsList(int id)
    {

        List<Local> lstLocal = new List<Local>();
        lstLocal = Locals.Where(l =>l.CenterId==id.ToString()).ToList();
        return Json(lstLocal);

    }
    [HttpGet]
    public IActionResult GetLocalsList()
    {
        List<SelectListItem> lstLocal = new List<SelectListItem>();
        foreach (Center center in Centers) {
            lstLocal.Add(new SelectListItem { Value = center.Id, Text = center.Name });
        }
        ViewBag.ddlCentre = lstLocal;

        return View();

    }


问:
How to check mysql event status
How to check event scheduler status in MySQL database?

I want to know the running status of my event whether it is running or not?

答:
how to check event scheduler status

It can be ON or OFF (TRUE/FALSE, 1/0) and can be viewed by

```<code>SELECT @@GLOBAL.event_scheduler;
-- or
SELECT @@event_scheduler;
</code>```

for example.

i want to know the running status of my event whether it is running or not

This is absolutely another task. Event scheduler != Event.

Look at

```<code>SHOW PROCESSLIST;
</code>```

for your event executing thread row is present or not.

Title: How to check mysql event status

Body:
how to check event scheduler status

It can be ON or OFF (TRUE/FALSE, 1/0) and can be viewed by

SELECT @@GLOBAL.event_scheduler;
-- or
SELECT @@event_scheduler;

for example.

i want to know the running status of my event whether it is running or not

This is absolutely another task. Event scheduler != Event.

Look at

SHOW PROCESSLIST;

for your event executing thread row is present or not.


问:
How to install version 12 of nodejs
i am trying to install version 12 of nodejs with command
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash
but still getting version 8 of nodejs and also npm is not installed</p>

答:
the complete instructions for installing node from that distribution is two commands:

# install the source list, let apt-get install 'find' the nodejs package
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
```

<pre class="lang-sh prettyprint-override"><code># apt-get now knows about nodejs package
sudo apt-get install -y nodejs
</code>```

you'll find that when you follow these instructions, the script will print how to install yarn, and you should do that, also several commands (for adding sources, keys, and then installing the packages from those lists).

Suggested method

I would suggest using the n library, because it doesn't require any OS modification, like so:

```<code>sudo npm i -g n
sudo n 12
</code>```

Title: How to install version 12 of nodejs

Body:
the complete instructions for installing node from that distribution is two commands:

# install the source list, let apt-get install 'find' the nodejs package
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

# apt-get now knows about nodejs package
sudo apt-get install -y nodejs

you'll find that when you follow these instructions, the script will print how to install yarn, and you should do that, also several commands (for adding sources, keys, and then installing the packages from those lists).

Suggested method

I would suggest using the n library, because it doesn't require any OS modification, like so:

sudo npm i -g n
sudo n 12


问:
ReactJS: Expected onClick listener to be a function, instead got type string
I can't figure out why ReactJs is finding "string" instead of my click handler methods.

This is my code:

```<code>define(["react"], function(React) {

return React.createClass({

    pageUp: function() {
        console.log("go next page");
    },

    pageDown: function() {
        console.log("go prev page");
    },

    toggleMenu: function() {
        console.log("toggle menu");
        this.state.menuStatus = !this.menuStatus;
    },

    getInitialState: function() {
        return {
            // Toggle menu status; false -> closed | true -> opened
            menuStatus: false
        }
    },

    render: function() {
        var _this = this;
        return (
            <div className="overlay-nav">
                <ul className="up-down-arrows">
                    <li onClick="{this.pageUp}" className="arrow-up"><i className="fa fa-angle-up"></i></li>
                    <li onClick="{_this.pageDown.bind(_this)}" className="arrow-down"><i className="fa fa-angle-down"></i></li>
                </ul>

                <div onClick="{_this.toggleMenu}" className="toggleMenu"><i className="fa fa-bars"></i></div>
            </div>
        );
    }
});
</code>```

});

I already tried to use

```<code>var _this = _this
// ....
<li onClick="_this.pageUp" ...
</code>```

and binds like

```<code><li onClick="{this.pageUp.bind(this)}"
</code>```

But when I refresh the page, I always get this error:

The error I get is:

```<code>Error: Expected onClick listener to be a function, instead got type string(…)
</code>```

Any help is much appreciate.

tks

答:
Use like below</p>

```<code>onClick={this.functionName}
</code>```

Body:
I can't figure out why ReactJs is finding "string" instead of my click handler methods.

This is my code:

define(["react"], function(React) {

return React.createClass({

    pageUp: function() {
        console.log("go next page");
    },

    pageDown: function() {
        console.log("go prev page");
    },

    toggleMenu: function() {
        console.log("toggle menu");
        this.state.menuStatus = !this.menuStatus;
    },

    getInitialState: function() {
        return {
            // Toggle menu status; false -> closed | true -> opened
            menuStatus: false
        }
    },

    render: function() {
        var _this = this;
        return (

        );
    }
});

});

I already tried to use

var _this = _this
// ....
<li onClick="_this.pageUp" ...

and binds like

<li onClick="{this.pageUp.bind(this)}"

But when I refresh the page, I always get this error:

The error I get is:

Error: Expected onClick listener to be a function, instead got type string(…)

Any help is much appreciate.

tks

Body:
Use like below

onClick={this.functionName}


问:
How can I make Stream Writer overwrite a txt file in unity (c#)?
I'm trying to keep track of some information by using a text file. I want the text file to reset every time I write in it so that I don't get a bunch of old information. Is there any way for me to do this?

void WriteString(string text, string path) {
    StreamWriter writer = new StreamWriter(path, true);
    writer.Write(text);
    writer.Close();
}
```

答:
```<code>// Your Text File Path
string path = @"";

// The Text You Want To Write inside The File
string content = "";

// This Method Clears Whatever Text It Finds in the File and Writes the new Content (overwrites the text file)
File.WriteAllText(path, content);
</code>```


问:
edit of select option with multiple selecting option
Facing some issue with multiple selection for  type.

In my CRM script, I am storing data for customer visit details with number of sales persons how have visited there. Here is my visit table

```<code>visit_id | customer | visit_date
1        | 4        | 2020-05-16
2        | 3        | 2020-05-20
</code>```

and attended sales persons details i am storing in a table visit_attendees like this

```<code>id | visit_id | attendees
1  | 1        | 1
2  | 1        | 3
3  | 1        | 4
4  | 2        | 3
5  | 2        | 2
</code>```

here attendees ids i get from table sales_persons

```<code>sid | fname  | lname
1   | ABC    | CDS
2   | XYZ    | AAA
3   | ZZZ    |
4   | CDE    | H
</code>```

storing is not an issue. But while editing, i want to these values as selected and want to store only if extra is added or already presented is removed. I am not getting how to do it.

Now i am doing right about turn method like this

```<code><?php
$m1 = DB_query("SELECT sp.id, sp.fname, sp.lname, va.attendees FROM sales_persons sp INNER JOIN visit_attendees va ON sp.id=va.attendees WHERE va.visit_id=".$VisitID.""); ?>
<h4>Attendies</h4>
<select name="attendees[]" class="form-control select2 is-invalid" multiple="multiple" required>
<?php while($m2 = DB_fetch_array($m1)) { ?>
  <option value="<?php echo $m2['id'];?>" selected="selected"><?php echo $m2['fname'].' '.$m2['lname'];?></option>
<?php }
$st = "SELECT id, fname, lname FROM sales_persons";
$st1 = DB_query($st);
while($st2 = DB_fetch_array($st1)) {  ?>
  <option value="<?php echo $st2['id']; ?>"> <?php echo $st2['fname'].' '.$st2['lname']; ?> </option>
<?php } ?>
</select>
</code>```

and updating the table visit_attendees like this

```<code>if(isset($_POST['UpdateVisits']))
    {

$vid = DB_escape_string($_POST['visit_id']);
   $attendees = $_POST['attendees'];

//$l1 = "UPDATE visits SET ....";

$d1 = DB_query("DELETE FROM visit_attendeees WHERE visit_id=".$vid."");
    foreach($attendees as $attend)
{
$att =  "INSERT INTO visit_attendies(visit_id, attendees) VALUES(".$vid.", ".DB_escape_string($attend).")";
$att1 = DB_query($att);
}

}
</code>```

is there any other straight method to achieve this?

答:
I am not sure if you want to update your MySQL Table, but in case that you are not querying by these fields I would suggest you to save the attendees ids in a json instead of a single row for each one. That would mean you have only one row which to update and save many queries to the database.

Json is not the best option to save in MySQL but in case you are querying by id, not by attendees id that would pretty much do the trick for you.

That way you would need to save the attendees ids in array and then update them to the field like:

```<code>"UPDATE visit_attendies SET attendees = '".json_encode($attendies_arr)."' where visit_id = '".$vid."'"
</code>```

And then when you select them you would do json_decode and get id of attendees.

The field should be a text field.

Body:
Facing some issue with multiple selection for  type.

In my CRM script, I am storing data for customer visit details with number of sales persons how have visited there. Here is my visit table

visit_id | customer | visit_date
1        | 4        | 2020-05-16
2        | 3        | 2020-05-20

and attended sales persons details i am storing in a table visit_attendees like this

id | visit_id | attendees
1  | 1        | 1
2  | 1        | 3
3  | 1        | 4
4  | 2        | 3
5  | 2        | 2

here attendees ids i get from table sales_persons

sid | fname  | lname
1   | ABC    | CDS
2   | XYZ    | AAA
3   | ZZZ    |
4   | CDE    | H

storing is not an issue. But while editing, i want to these values as selected and want to store only if extra is added or already presented is removed. I am not getting how to do it.

Now i am doing right about turn method like this

<?php
$m1 = DB_query("SELECT sp.id, sp.fname, sp.lname, va.attendees FROM sales_persons sp INNER JOIN visit_attendees va ON sp.id=va.attendees WHERE va.visit_id=".$VisitID.""); ?>

Attendies

<select name="attendees[]" class="form-control select2 is-invalid" multiple="multiple" required>
<?php while($m2 = DB_fetch_array($m1)) { ?>
  <option value="<?php echo $m2['id'];?>" selected="selected"><?php echo $m2['fname'].' '.$m2['lname'];?></option>
<?php }
$st = "SELECT id, fname, lname FROM sales_persons";
$st1 = DB_query($st);
while($st2 = DB_fetch_array($st1)) {  ?>
  <option value="<?php echo $st2['id']; ?>"> <?php echo $st2['fname'].' '.$st2['lname']; ?> </option>
<?php } ?>
</select>

and updating the table visit_attendees like this

if(isset($_POST['UpdateVisits']))
    {

$vid = DB_escape_string($_POST['visit_id']);
   $attendees = $_POST['attendees'];

//$l1 = "UPDATE visits SET ....";

$d1 = DB_query("DELETE FROM visit_attendeees WHERE visit_id=".$vid."");
    foreach($attendees as $attend)
{
$att =  "INSERT INTO visit_attendies(visit_id, attendees) VALUES(".$vid.", ".DB_escape_string($attend).")";
$att1 = DB_query($att);
}

}

is there any other straight method to achieve this?

Body:
I am not sure if you want to update your MySQL Table, but in case that you are not querying by these fields I would suggest you to save the attendees ids in a json instead of a single row for each one. That would mean you have only one row which to update and save many queries to the database.

Json is not the best option to save in MySQL but in case you are querying by id, not by attendees id that would pretty much do the trick for you.

That way you would need to save the attendees ids in array and then update them to the field like:

"UPDATE visit_attendies SET attendees = '".json_encode($attendies_arr)."' where visit_id = '".$vid."'"

And then when you select them you would do json_decode and get id of attendees.

The field should be a text field.


问:
Get all notification messages (if any) when the app is opened using app icon
I was working with flutter and I managed to implement FCM push notification in the app. The FLUTTER_NOTIFICATION_CLICK click_action works fine.
But, I need to perform that similar action when the app is launched by clicking the app icon. Is there any method to do so?

Ultimate goal is to perform similar action when the app is launched by clicking the notification or by the app icon (from the app drawer). Please help me with this.

答:
If you click and launch from notification
You can listen that 'onLaunch' method in firebaseMessaging.configure
But from 'app icon' is no way as far as I know.</p>


问:
Apply function with outer taking the columns of two matrices as the elements of interest
Consider matrices d and r with dim(d) = J x D and dim(r) = J x R.
Let fun(a, b) be a function that takes two vectors of the same length and returns some number.

I want to treat the columns of d and r respectively as my units of interest and apply outer to them.

The following code accomplishes this by creating lists of the columns of d and r and then using both outer and sapply:

```<code>d.cols <- split(d, col(d))
r.cols <- split(r, col(r))
outer(d.cols, r.cols,
      function(x,y) {
           sapply(seq_along(x),
                 function(i) {
                     Fun(x[[i]], y[[i]]) })} )
</code>```

The code does what I want and is relatively efficient, but is clumsy and unclear.  Is there a better way to accomplish what I am trying to get at?

答:
You are pretty close. As described in this related question, all you need is the Vectorize() function to convert your Fun() function into a vectorized version:

```<code>VecFun <- Vectorize( Fun )
</code>```

Then you can simply do:

```<code>outer(d.cols, r.cols, VecFun )
</code>```

E.g. if you define

```<code>Fun <- function(a,b) sum(a+b)
</code>```

and r,d matrices are defined as follows:

```<code>J <- 5
D <- 3
R <- 4

d <- matrix( 1:(J*D), J, D)
r <- matrix( 1:(J*R), J, R)
</code>```

then you get this:

```<code>> outer(d.cols, r.cols, VecFun)

   1   2   3   4
1 30  55  80 105
2 55  80 105 130
3 80 105 130 155
</code>```

Body:
Consider matrices d and r with dim(d) = J x D and dim(r) = J x R.
Let fun(a, b) be a function that takes two vectors of the same length and returns some number.

I want to treat the columns of d and r respectively as my units of interest and apply outer to them.

The following code accomplishes this by creating lists of the columns of d and r and then using both outer and sapply:

d.cols <- split(d, col(d))
r.cols <- split(r, col(r))
outer(d.cols, r.cols,
      function(x,y) {
           sapply(seq_along(x),
                 function(i) {
                     Fun(x[[i]], y[[i]]) })} )

The code does what I want and is relatively efficient, but is clumsy and unclear.  Is there a better way to accomplish what I am trying to get at?

Body:
You are pretty close. As described in this related question, all you need is the Vectorize() function to convert your Fun() function into a vectorized version:

VecFun <- Vectorize( Fun )

Then you can simply do:

outer(d.cols, r.cols, VecFun )

E.g. if you define

Fun <- function(a,b) sum(a+b)

and r,d matrices are defined as follows:

J <- 5
D <- 3
R <- 4

d <- matrix( 1:(J*D), J, D)
r <- matrix( 1:(J*R), J, R)

then you get this:

> outer(d.cols, r.cols, VecFun)

   1   2   3   4
1 30  55  80 105
2 55  80 105 130
3 80 105 130 155


问:
Cookie “cookieName” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value on clearCookie
I have an express API with the following code in order to set a cookie:

```<code>...
res.setHeader("Access-Control-Allow-Origin", ip);
res.cookie(name, token, { maxAge: 30000, httpOnly: true, secure: false, sameSite: "Lax" });
...
</code>```

And this other to clear the cookie:

```<code>...
res.clearCookie(name);
...
</code>```

When I execute the second one, I got the following error message:
Cookie “cookieName” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value on clearCookie

Some details:

The error shows up only in Firefox, not in Chrome.

Before setting sameSite: "Lax", I received the error message twice, after setting the cookie as well as when clearing it. After setting sameSite to Lax, the problem only appeared when clearing the cookie.

Any help? Let me know if you need more details, versions, code...

答:
You are facing an HTTP issue. The general rule, that for setting or deleting cookie, you have to set all parameters same (except value and expiration time). The correct solution for your problem is described in the answer https://stackoverflow.com/a/20320610/941493 and in RFC 6265.

Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

Also it is written in the documentation of clearCookie:

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

So in your case call cookie command with expires in the past or clearCookie with the same parameters you used for creating cookie.

Body:
I have an express API with the following code in order to set a cookie:

...
res.setHeader("Access-Control-Allow-Origin", ip);
res.cookie(name, token, { maxAge: 30000, httpOnly: true, secure: false, sameSite: "Lax" });
...

And this other to clear the cookie:

...
res.clearCookie(name);
...

When I execute the second one, I got the following error message:
Cookie “cookieName” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value on clearCookie

Some details:

The error shows up only in Firefox, not in Chrome.

Before setting sameSite: "Lax", I received the error message twice, after setting the cookie as well as when clearing it. After setting sameSite to Lax, the problem only appeared when clearing the cookie.

Any help? Let me know if you need more details, versions, code...


问:
Why Looper.loop() does not block the Main thread
Looper's loop method is called inside the ActivityThread's main method and starts an infinite for loop which iterates over a message queue. When there is no more message in the queue then it calls nativePollOnce method which waits for the next message.
 So my questions are

1.if it waits for next message then the main thread will be blocked then how can it enqueue more message queue.

2.if it doesn't get blocked then it will consume the CPU cycle and others would not get a chance to add a message in the queue.
Please take into consideration that MessageQueue, Handler, Looper are on main thread and UI events and input events processed by the main thread.

Links

Why main thread's Looper.loop() doesn't block UI thread?

Why does Looper.loop() not block the UI thread

android - what is message queue native poll once in android?
Does an Android Looper thread use processing power?

答:
If it waits for next message then the main thread will be blocked then how can it enqueue more message queue?

The main thread only runs the main loop. Everything else runs within the main loop itself. So if this loop is waiting for new messages, there's no other code running on the main thread at all. This also means that it's not possible that any new message is enqueued from the main thread itself.

If it doesn't get blocked then it will consume the CPU cycle and others would not get a chance to add a message in the queue.
  Please take into consideration that MessageQueue, Handler, Looper are on main thread and UI events and input events processed by the main thread.

The main thread is blocking until a message is received. This blocking mechanism is implemented on the native layer, thus it's optimized for performance.

The MessageQueue and the Handler are only data structures not directly connected to any thread.


问:
Consider the following function:
```<code>int unknown(int n){

int i, j, k=0;
for (i=n/2; i<=n; i++)
    for (j=2; j<=n; j=j*2)
        k = k + n/2;
 return (k);

}
</code>```

The return value of the function is Θ(n^2logn).

My doubt: The time complexity of the function is Θ(nlogn) which i don't understand how it can be Θ(nlogn) because outer loop will execute exactly n/2 times and inner loop will execute logn times.

How time complexity is different than return value of this function, can someone explain me in simple language so i can visualize it.

答:
The time the function takes (as counted by the number of loop iterations) is approximately (n/2) * (lg n).

For each iteration, k is incremented by n/2.

So the time complexity is O(n lg n) and the return value of the function is n/2 times larger, or O(n^2 lg n).

Title: Consider the following function:

Body:
int unknown(int n){

int i, j, k=0;
for (i=n/2; i<=n; i++)
    for (j=2; j<=n; j=j*2)
        k = k + n/2;
 return (k);

}

The return value of the function is Θ(n^2logn).

My doubt: The time complexity of the function is Θ(nlogn) which i don't understand how it can be Θ(nlogn) because outer loop will execute exactly n/2 times and inner loop will execute logn times.

How time complexity is different than return value of this function, can someone explain me in simple language so i can visualize it.


问:
Git Submodule lost, able to retrieve?
I have a long-standing personal repository for "Resume/", holding my resume contents. I have also had a subdir "Resume/Cover Letter", holding my CV contents that had worked well.
I had created a second git repository inside "Resume/Cover Letter" awhile back, did not think much of it. Now these contents are gone! How can this be though, there is no .gitmodules in my 'Resume' project.

I can see all record  of the Cover Letter repo in the log for Resume/ -

History Example:

But the contents of "Resume/Cover Letter" is empty. Where did these files go? Can they be retrieved? Here is a useful illustration -

Example

Update

Doh! See the reference below, for clear warning not to do this -

答:
When you have a nested Git repository, your parent repo only records a gitlink (a special entry in the index)

So git add/git commit/git push done in the main repository does not add/commit/push files in the nested Git repository at all.

The same command done in the nested repo folder itself would have added/committed/pushed your files.

Title: Git Submodule lost, able to retrieve?


问:
How to dynamically create select options when using materialize css
I am reposing my question as I was able to solve some part of it and only need help on certain point.

I am able to populate rest of the table content dynamically except the <select> elements.

Because I am using Materialize css I am getting trouble creating it.

```<code>document.addEventListener('DOMContentLoaded', function(){

google.script.run.withSuccessHandler(getLeaveRosterData).loadRoster();
 var elems = document.querySelectorAll('select');
 var instances = M.FormSelect.init(elems);

});

let weeksArray = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

dataArray.forEach(function(ele)
{
  const tableRow = document.createElement("tr");

  var agentTD = document.createElement("td");
  agentTD.setAttribute("id", "agent"+ ele);
  var t = document.createTextNode(ele);
  agentTD.appendChild(t);

  var w1TD = document.createElement("td");
  w1TD.appendChild(createDropdown("w1-" + ele));

   // create td elements with unique ids
  var w2TD = document.createElement("td");
  w2TD.appendChild(createDropdown("w2-" + ele));

  tableRow.appendChild(agentTD);
  tableRow.appendChild(w1TD);
  tableRow.appendChild(w2TD);
  tbody.appendChild(tableRow);

});
function createDropdown(id) {
  //create a radio button
  var fragment = document.createDocumentFragment();
  var select = document.createElement('select');
  select.setAttribute("id", id);
  weeksArray.forEach(function (day) {
    select.options.add( new Option(day, day));
  });
  fragment.appendChild(select);
  return fragment;
}
</code>```

My select elements are day names.["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]. Any suggestion is welcomed.

答:
A note on Materialize CSS neding "initalization": https://materializecss.com/select.html

Initialization

You must initialize the select element as shown below. In addition, you will need a separate call for any dynamically generated select elements your page generates.

```<code>  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems, options);
  });

  // Or with jQuery

  $(document).ready(function(){
    $('select').formSelect();
  });
</code>```

You can either use the above code to do them all in bulk, or target each added select more individually.

The code you posted is missing some references to make it testable, but I've added those, but essentially does what you're looking for as-is. You can run this in-browser here to confirm the select lists are rendered.

let weeksArray = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

const dataArray = ['example 1', 'example 2'];
const tbody = document.querySelector('tbody');

dataArray.forEach(function(ele)
{
  const tableRow = document.createElement("tr");

  var agentTD = document.createElement("td");
  agentTD.setAttribute("id", "agent"+ ele);
  var t = document.createTextNode(ele);
  agentTD.appendChild(t);

  var w1TD = document.createElement("td");
  w1TD.appendChild(createDropdown("w1-" + ele));

   // create td elements with unique ids
  var w2TD = document.createElement("td");
  w2TD.appendChild(createDropdown("w2-" + ele));

  tableRow.appendChild(agentTD);
  tableRow.appendChild(w1TD);
  tableRow.appendChild(w2TD);
  tbody.appendChild(tableRow);

});
function createDropdown(id) {
  //create a radio button
  var fragment = document.createDocumentFragment();
  var select = document.createElement('select');
  select.setAttribute("id", id);
  weeksArray.forEach(function (day) {
    select.options.add( new Option(day, day));
  });
  fragment.appendChild(select);
  return fragment;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
  </tbody>
</table></code>```

Body:
I am reposing my question as I was able to solve some part of it and only need help on certain point.

I am able to populate rest of the table content dynamically except the <select> elements.

Because I am using Materialize css I am getting trouble creating it.

document.addEventListener('DOMContentLoaded', function(){

google.script.run.withSuccessHandler(getLeaveRosterData).loadRoster();
 var elems = document.querySelectorAll('select');
 var instances = M.FormSelect.init(elems);

});

let weeksArray = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

dataArray.forEach(function(ele)
{
  const tableRow = document.createElement("tr");

  var agentTD = document.createElement("td");
  agentTD.setAttribute("id", "agent"+ ele);
  var t = document.createTextNode(ele);
  agentTD.appendChild(t);

  var w1TD = document.createElement("td");
  w1TD.appendChild(createDropdown("w1-" + ele));

   // create td elements with unique ids
  var w2TD = document.createElement("td");
  w2TD.appendChild(createDropdown("w2-" + ele));

  tableRow.appendChild(agentTD);
  tableRow.appendChild(w1TD);
  tableRow.appendChild(w2TD);
  tbody.appendChild(tableRow);

});
function createDropdown(id) {
  //create a radio button
  var fragment = document.createDocumentFragment();
  var select = document.createElement('select');
  select.setAttribute("id", id);
  weeksArray.forEach(function (day) {
    select.options.add( new Option(day, day));
  });
  fragment.appendChild(select);
  return fragment;
}

My select elements are day names.["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]. Any suggestion is welcomed.

Body:
A note on Materialize CSS neding "initalization": https://materializecss.com/select.html

Initialization

You must initialize the select element as shown below. In addition, you will need a separate call for any dynamically generated select elements your page generates.

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems, options);
  });

  // Or with jQuery

  $(document).ready(function(){
    $('select').formSelect();
  });

You can either use the above code to do them all in bulk, or target each added select more individually.

The code you posted is missing some references to make it testable, but I've added those, but essentially does what you're looking for as-is. You can run this in-browser here to confirm the select lists are rendered.

let weeksArray = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

const dataArray = ['example 1', 'example 2'];
const tbody = document.querySelector('tbody');

dataArray.forEach(function(ele)
{
  const tableRow = document.createElement("tr");

  var agentTD = document.createElement("td");
  agentTD.setAttribute("id", "agent"+ ele);
  var t = document.createTextNode(ele);
  agentTD.appendChild(t);

  var w1TD = document.createElement("td");
  w1TD.appendChild(createDropdown("w1-" + ele));

   // create td elements with unique ids
  var w2TD = document.createElement("td");
  w2TD.appendChild(createDropdown("w2-" + ele));

  tableRow.appendChild(agentTD);
  tableRow.appendChild(w1TD);
  tableRow.appendChild(w2TD);
  tbody.appendChild(tableRow);

});
function createDropdown(id) {
  //create a radio button
  var fragment = document.createDocumentFragment();
  var select = document.createElement('select');
  select.setAttribute("id", id);
  weeksArray.forEach(function (day) {
    select.options.add( new Option(day, day));
  });
  fragment.appendChild(select);
  return fragment;
}

<table>
  <tbody>
  </tbody>
</table>


问:
Are Scala parallel collections better in some ways than the parallel collections already available in Java?
I've recently been learning about various libraries for concurrency in Java such as ConcurrentHashMap and the lovely non blocking one from Cliff Click

I don't know much about Scala but I've heard good things about the recent parallel collections library.

I'd like to know what are some major advantages that this library would give over Java based libraries?

答:
In addition to Rex Kerr's answer above about concurrent and parallel collections serving two different purposes, I would add that Java actually has a parallel array implementation by Doug Lea in the extra JSR 166 package - this collection allows bulk operations being performed on the array elements, while not being suitable for concurrent access without explicit synchronization. One big difference here is that Scala parallel collections have parallel implementations for other collections as well, and not just arrays. These are:

ParVector

ParRange

mutable.ParHashMap

mutable.ParHashSet

immutable.ParHashMap

immutable.ParHashSet

All of the sequential variants of these collections can be directly converted into their parallel counterparts (method par). Other sequential collections can be converted into some of the above collections in linear time with respect to collection size.

Some additional data structures are on the way for the future releases, including some parallel collections which will also allow concurrent access.


问:
If else not working in cypress it only going into if condition in cypress
cy.get('body').then(($body)=>{

```<code>    if($body.find('.field-validation-error'))
    {
        //cy.contains('Invalid username or password.').should('be.visible')
        cy.log('Invalid username or password.')
    }
     else if($body.find('#inspire > div.v-application--wrap > div:nth-child(1) > div.root-container.fill-height.fill-width > div.base-layout-main-content.box > div.row.content-wrapper.fill-width.fill-height > div.fill-height.body-right-wrapper.col-sm-12.col.col-xs-12.col-md-7.col-lg-8.col-xl-9 > div > div > div > div.px-4.col.col-12 > div > span')){

        cy.log('logged In')

     }
 })
</code>```

It is not working like if else do ....it is not going in else part, if the if() condition falis it should go into the else part but it not executing else() condition

答:
$body is a jquery instance so it will always return an object.

You can check: console.log(typeof $body.find('.field-validation-error'))

use:

```<code>if ($body.find('.field-validation-error').length)
</code>```

Body:
cy.get('body').then(($body)=>{

    if($body.find('.field-validation-error'))
    {
        //cy.contains('Invalid username or password.').should('be.visible')
        cy.log('Invalid username or password.')
    }
     else if($body.find('#inspire > div.v-application--wrap > div:nth-child(1) > div.root-container.fill-height.fill-width > div.base-layout-main-content.box > div.row.content-wrapper.fill-width.fill-height > div.fill-height.body-right-wrapper.col-sm-12.col.col-xs-12.col-md-7.col-lg-8.col-xl-9 > div > div > div > div.px-4.col.col-12 > div > span')){

        cy.log('logged In')

     }
 })

It is not working like if else do ....it is not going in else part, if the if() condition falis it should go into the else part but it not executing else() condition

Body:
$body is a jquery instance so it will always return an object.

You can check: console.log(typeof $body.find('.field-validation-error'))

use:

if ($body.find('.field-validation-error').length)


问:
mkdir and joinpath doesn't works in Google
```<code> save_dir = Path('/OpenPose_Pose_transfer/data/source/roy')
 save_dir.mkdir(exist_ok=True)

 img_dir = save_dir.joinpath('images')
 img_dir.mkdir(exist_ok=True)

 %cd ~/OpenPose_Pose_transfer/data/source/roy/
 %cd ~/OpenPose_Pose_transfer/data/source/images/
</code>```

No such file or directory: '/root/OpenPose_Pose_transfer/data/source/roy/'
/root/OpenPose_Pose_transfer
No such file or directory: '/root/OpenPose_Pose_transfer/data/source/images/'
/root/OpenPose_Pose_transfer

mkdir and joinpath do not work with Google Colab

答:
From pathlib docs:

If parents is true, any missing parents of this path are created as
  needed; they are created with the default permissions without taking
  mode into account (mimicking the POSIX mkdir -p command).

Since in your case the parents probably do not exist yet, specify the parents=True parameter to mkdir(). Also, the last line should be %cd /OpenPose_Pose_transfer/data/source/roy/images/ since images is a sub-directory of roy.

Also, since you are creating OpenPose_Pose_transfer directory at /, do not precede the path with ~ ( which expands to /root in Colab)

Changed code:

 from pathlib import Path
 save_dir = Path('/OpenPose_Pose_transfer/data/source/roy')
 save_dir.mkdir(parents=True, exist_ok=True)

 img_dir = save_dir.joinpath('images')
 img_dir.mkdir(exist_ok=True)

 %cd /OpenPose_Pose_transfer/data/source/roy/
 %cd /OpenPose_Pose_transfer/data/source/roy/images/
```

Body:
 save_dir = Path('/OpenPose_Pose_transfer/data/source/roy')
 save_dir.mkdir(exist_ok=True)

 img_dir = save_dir.joinpath('images')
 img_dir.mkdir(exist_ok=True)

 %cd ~/OpenPose_Pose_transfer/data/source/roy/
 %cd ~/OpenPose_Pose_transfer/data/source/images/

No such file or directory: '/root/OpenPose_Pose_transfer/data/source/roy/'
/root/OpenPose_Pose_transfer
No such file or directory: '/root/OpenPose_Pose_transfer/data/source/images/'
/root/OpenPose_Pose_transfer

mkdir and joinpath do not work with Google Colab


问:
React: Target container is not a DOM element
I am using react in rails. But when I run the app, I get an error: Uncaught Error: Target container is not a DOM element.

My index.jsx file looks like:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from "react-redux";
import thunk from "redux-thunk";
import reducers from "../bundles/HelloWorld/reducers/index.js";
import App from "../bundles/HelloWorld/components/App"
let store = createStore(reducers, applyMiddleware(thunk))

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
</code>```

Also, I using this in application.html.erb like this:

What could be the error behind this?

答:
Add an element with id='root' to the page e.g.

```<code>ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.body.appendChild(document.createElement("div"))
);
</code>```

render expects a DOM element as the second argument, which doesn't exist in your case. You could either set it on the page itself or generate it dynamically as shown above.

Body:
I am using react in rails. But when I run the app, I get an error: Uncaught Error: Target container is not a DOM element.

My index.jsx file looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from "react-redux";
import thunk from "redux-thunk";
import reducers from "../bundles/HelloWorld/reducers/index.js";
import App from "../bundles/HelloWorld/components/App"
let store = createStore(reducers, applyMiddleware(thunk))

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

Also, I using this in application.html.erb like this:

What could be the error behind this?

Body:
Add an element with id='root' to the page e.g.

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.body.appendChild(document.createElement("div"))
);

render expects a DOM element as the second argument, which doesn't exist in your case. You could either set it on the page itself or generate it dynamically as shown above.


问:
PHP Config --bindir
When using the following configure flags below, the following error is reported, why is this? Obviously the directory exists. This is a PHP 5.2.9 install on a 64bit CentOS 5.2 OS.

./phpconfig.scr: line 11: --bindir=/usr/bin: No such file or directory

'./configure' \

'--host=x86_64-redhat-linux-gnu' \

'--build=x86_64-redhat-linux-gnu' \

'--target=x86_64-redhat-linux' \

'--program-prefix=' \

'--prefix=/usr' \

'--exec-prefix=/usr' \

'--bindir=/usr/bin' \

'--sbindir=/usr/sbin' \

'--sysconfdir=/etc' \

'--datadir=/usr/share' \

'--includedir=/usr/include' \

'--libdir=/usr/lib64' \

'--libexecdir=/usr/libexec' \

'--localstatedir=/var' \

'--sharedstatedir=/usr/com' \

'--mandir=/usr/share/man' \

'--infodir=/usr/share/info' \

'--cache-file=../config.cache' \

'--with-libdir=lib64' \

'--with-config-file-path=/etc' \

'--with-config-file-scan-dir=/etc/php.d' \

'--disable-debug' \

'--with-pic' \

'--disable-rpath' \

'--without-pear' \

'--with-bz2' \

'--with-curl' \

'--with-exec-dir=/usr/bin' \

'--with-freetype-dir=/usr' \

'--with-png-dir=/usr' \

'--enable-gd-native-ttf' \

'--without-gdbm' \

'--with-gettext' \

'--with-gmp' \

'--with-iconv' \

'--with-jpeg-dir=/usr' \

'--with-openssl' \

'--with-png' \

'--with-pspell' \

'--with-expat-dir=/usr' \

'--with-pcre-regex=/usr' \

'--with-zlib' \

'--with-layout=GNU' \

'--enable-exif' \

'--enable-ftp' \

'--enable-magic-quotes' \

'--enable-sockets' \

'--enable-sysvsem' \

'--enable-sysvshm' \

'--enable-sysvmsg' \

'--enable-track-vars' \

'--enable-trans-sid' \

'--enable-yp' \

'--enable-wddx' \

'--with-kerberos' \

'--enable-ucd-snmp-hack' \

'--with-unixODBC=shared,/usr' \

'--enable-memory-limit' \

'--enable-shmop' \

'--enable-calendar' \

'--enable-dbx' \

'--enable-dio' \

'--without-mime-magic' \

'--without-sqlite' \

'--with-libxml-dir=/usr' \

'--with-xml' \

'--with-apxs2=/usr/sbin/apxs' \

'--without-mysql' \

'--without-gd' \

'--without-odbc' \

'--disable-dom' \

'--disable-dba' \

'--without-unixODBC' \

'--disable-pdo' \

'--disable-xmlreader' \

'--disable-xmlwriter' \

'--disable-json'

答:
Thanks for the responses. As it turns out the issue was with the script that was used to actually call ./configure. Within the script itself there was an extra space above the bindir config flag. So...

'--exec-prefix=/usr' \_<-The extra space indicated by the underscore.

'--bindir=/usr/bin' \

So the escape character was escaping a space and not a return.

ERRR.

Hopefully this will help someone else from loosing a afternoon trying to dig deeper than the obvious.

ContentLicense: CC BY-SA 2.5

Title: PHP Config --bindir

OwnerDisplayName: Sivart


问:
Removing grey bar above UINavigationController in a UITableView
I am creating a UITableView with a UINavigationController programmatically:

```<code>- (void) displayView:(int)intNewView{

    NSLog(@"%i", intNewView);
    [currentView.view removeFromSuperview];
    [currentView release];

    switch (intNewView) {
        ......

        case 5:
            vc = [[RootViewController alloc] init];
            currentView = [[UINavigationController alloc] initWithRootViewController:vc];
            [currentView setTitle:@"Events"];
            break;
    }

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:0.5];

    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                           forView:self.view
                             cache:YES];

    [self.view addSubview:currentView.view];

    [UIView commitAnimations];
}
</code>```

However when the view appears there is an annoying grey bar perched above the navigation controller, none of my other views suffer from this.  Just the view with the UITableView and NavigationController.

Any ideas whats causing this and how to remove it?

Thanks,

Jack

答:
When the UINavigationController is initialised, it does so expecting the iPhones status bar to be present at the top of the screen.  Therefore, the view is essentially moved down a little in order to accommodate this.  BUT, as my UINavigationController is inside my RootViewController, the UINavigationController does not have to accommodate for the status bar and so can be "moved up" the appropriate distance using the following line placed inside the viewDidLoad method of my RootViewController:

```<code>self.navigationController.view.frame = CGRectMake(0, -20, 320, 480);
</code>```

Now when the program runs, there is no grey bar/ grey space at the top of my view.

Thanks for all your help, pointed me in the right direction.

Jack

Body:
I am creating a UITableView with a UINavigationController programmatically:

- (void) displayView:(int)intNewView{

    NSLog(@"%i", intNewView);
    [currentView.view removeFromSuperview];
    [currentView release];

    switch (intNewView) {
        ......

        case 5:
            vc = [[RootViewController alloc] init];
            currentView = [[UINavigationController alloc] initWithRootViewController:vc];
            [currentView setTitle:@"Events"];
            break;
    }

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:0.5];

    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                           forView:self.view
                             cache:YES];

    [self.view addSubview:currentView.view];

    [UIView commitAnimations];
}

However when the view appears there is an annoying grey bar perched above the navigation controller, none of my other views suffer from this.  Just the view with the UITableView and NavigationController.

Any ideas whats causing this and how to remove it?

Thanks,

Jack

Body:
When the UINavigationController is initialised, it does so expecting the iPhones status bar to be present at the top of the screen.  Therefore, the view is essentially moved down a little in order to accommodate this.  BUT, as my UINavigationController is inside my RootViewController, the UINavigationController does not have to accommodate for the status bar and so can be "moved up" the appropriate distance using the following line placed inside the viewDidLoad method of my RootViewController:

self.navigationController.view.frame = CGRectMake(0, -20, 320, 480);

Now when the program runs, there is no grey bar/ grey space at the top of my view.

Thanks for all your help, pointed me in the right direction.

Jack


问:
Are changes in Input(() fields propagated to parent component?
My understanding is that I can pass data to child components using directive @Input(), and send data back to parent component using @Output() and with the appropriate emit. But I wasn't aware that changes data in the @Input() field would be sent to the parent. Is this correct?

I modified the component communication workbook to reproduce this https://input-params.stackblitz.io

Can you explain?

Thanks,

答:
Yes you can pass the data to the child component by using @Input(). This is reference binded, So when you change the value in the child that gets reflected in the parent component also.

Using @Output() you can send any data from the child to parent component. But as the data passed is reference binded, the value gets changed in parent even though you don't pass it back using @Output().

But if you want change the value only in child component and not get the changed value in parent component you can make another copy of your array and pass that to the child component using @Input().

You can make copy of the original array by using:

```<code>let inputArray = _.cloneDeep(this.originalArray)
</code>```

_ is the lodash library providing many such options.

To use lodash you have to add the below line in imports:

```<code>import * as _ from 'lodash';
</code>```

Body:
Yes you can pass the data to the child component by using @Input(). This is reference binded, So when you change the value in the child that gets reflected in the parent component also.

Using @Output() you can send any data from the child to parent component. But as the data passed is reference binded, the value gets changed in parent even though you don't pass it back using @Output().

But if you want change the value only in child component and not get the changed value in parent component you can make another copy of your array and pass that to the child component using @Input().

You can make copy of the original array by using:

let inputArray = _.cloneDeep(this.originalArray)

_ is the lodash library providing many such options.

To use lodash you have to add the below line in imports:

import * as _ from 'lodash';


问:
How to fix "Invalid beam file or no abstract code" error when debugging in Erlang/OTP?
I'm trying to simply use the debugger, however any method given in the docs causes Monitor > Module > Interpret > *.beam to return an error: ** Invalid beam file or no abstract code: "/path/z12.beam".

The methods to generate debug info I tried are:

Linux shell erlc +debug_info z12.erl

Erlang shell  > c(z12, [debug_info]).

Directly in the file compile:file(z12, [debug_info]).

However none of them seems to work. Is there a way to fix this?

答:
Actually you easily load the module using erl shell itself in which debugger was started.

```<code>c("erl_file_path",[debug_info]).
int:i("path/module_name").
</code>```

example:

```<code>12> c("/home/badri/hello.erl",[debug_info]).
{ok,hello}
15> int:i("/home/badri/hello").
{module,hello}
</code>```

Body:
Actually you easily load the module using erl shell itself in which debugger was started.

c("erl_file_path",[debug_info]).
int:i("path/module_name").

example:

12> c("/home/badri/hello.erl",[debug_info]).
{ok,hello}
15> int:i("/home/badri/hello").
{module,hello}


问:
Python/Pyspark iteration code (for AWS Glue ETL job)
I am using AWS Glue and you cannot read/write multiple dynamic frame without using an iteration. I made this code below but am struggling on 2 things:

Is "tableName" i.e. the filtered list of tables correct (all the tables I want to iterate on start with client_historical_*).

I am stuck on how to dynamically populate the Redshift table name using the mapping below.

Redshift mappings:

```<code>client_historical_ks --> table_01_a
client_historical_kg --> table_01_b
client_historical_kt --> table_01_c
client_historical_kf --> table_01_d
</code>```

Code:

```<code>client = boto3.client('glue',region_name='us-east-1')

databaseName = 'incomingdata'
tables = client.get_tables(DatabaseName = databaseName)
tableList = tables['TableList']

for table in tableList:
    start_prefix = client_historical_
    tableName = list(filter(lambda x: x.startswith(start_prefix), table['Name']))
    datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "incomingdata", table_name = tableName, transformation_ctx = "datasource0")
    datasink4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = datasource0, catalog_connection = "Redshift", connection_options = {"dbtable": "nameoftablehere", "database": "metadata"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink4")
</code>```

答:
You can create a mapping dictionary and then execute your code
You can also filter the tables outside of loop and then loop over only on required tables.</p>

```<code>mapping = {'client_historical_ks': 'table_01_a',
'client_historical_kg': 'table_01_b',
'client_historical_kt': 'table_01_c',
'client_historical_kf': 'table_01_d'}

client = boto3.client('glue',region_name='us-east-1')

databaseName = 'incomingdata'
tables = client.get_tables(DatabaseName = databaseName)
tableList = tables['TableList']
start_prefix = 'client_historical_'
tableNames = list(filter(lambda x: x.startswith(start_prefix), table['Name']))

for table in tableNames:
    target_table = mapping.get(table)
    datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "incomingdata", table_name = table, transformation_ctx = "datasource0")
    datasink4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = datasource0, catalog_connection = "Redshift", connection_options = {"dbtable": target_table, "database": "metadata"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink4")

</code>```

Body:
I am using AWS Glue and you cannot read/write multiple dynamic frame without using an iteration. I made this code below but am struggling on 2 things:

Is "tableName" i.e. the filtered list of tables correct (all the tables I want to iterate on start with client_historical_*).

I am stuck on how to dynamically populate the Redshift table name using the mapping below.

Redshift mappings:

client_historical_ks --> table_01_a
client_historical_kg --> table_01_b
client_historical_kt --> table_01_c
client_historical_kf --> table_01_d

Code:

client = boto3.client('glue',region_name='us-east-1')

databaseName = 'incomingdata'
tables = client.get_tables(DatabaseName = databaseName)
tableList = tables['TableList']

for table in tableList:
    start_prefix = client_historical_
    tableName = list(filter(lambda x: x.startswith(start_prefix), table['Name']))
    datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "incomingdata", table_name = tableName, transformation_ctx = "datasource0")
    datasink4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = datasource0, catalog_connection = "Redshift", connection_options = {"dbtable": "nameoftablehere", "database": "metadata"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink4")

Body:
You can create a mapping dictionary and then execute your code
You can also filter the tables outside of loop and then loop over only on required tables.

mapping = {'client_historical_ks': 'table_01_a',
'client_historical_kg': 'table_01_b',
'client_historical_kt': 'table_01_c',
'client_historical_kf': 'table_01_d'}

client = boto3.client('glue',region_name='us-east-1')

databaseName = 'incomingdata'
tables = client.get_tables(DatabaseName = databaseName)
tableList = tables['TableList']
start_prefix = 'client_historical_'
tableNames = list(filter(lambda x: x.startswith(start_prefix), table['Name']))

for table in tableNames:
    target_table = mapping.get(table)
    datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "incomingdata", table_name = table, transformation_ctx = "datasource0")
    datasink4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = datasource0, catalog_connection = "Redshift", connection_options = {"dbtable": target_table, "database": "metadata"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink4")


问:
Retrieving Kafka Producer config
Is there a way to collect Kafka Producer configs from the Kafka cluster?
I know that these settings are stored on the client itself.
I am interested at least in client.id and a collection of topics that the producer is publishing to.

答:
May be you can have a look into kafkacat.github url
We find it very helpful in troubleshooting, kafka issues.</p>

Title: Retrieving Kafka Producer config


答:
Inputs are normal variables, if you pass an object to an input angular passes its pointer, therefore parent and child components point to the same data and if you change inner parts of this data in a parent or in a child component it will be respected in both places, but if you reassign the property itself - it doesn't have the effect from child component, because it changes child pointer and next change detection cycle it will be set back to the parent value due to mismatched values.

If you pass a primitive to an input (string number boolean) it doesn't share the pointer and the effect isn't applicable.

Title: Are changes in Input(() fields propagated to parent component?

Body:
My understanding is that I can pass data to child components using directive @Input(), and send data back to parent component using @Output() and with the appropriate emit. But I wasn't aware that changes data in the @Input() field would be sent to the parent. Is this correct?

I modified the component communication workbook to reproduce this https://input-params.stackblitz.io

Can you explain?

Thanks,


问:
Is it possible to do stratified random sampling with strata from another dataset in SAS?
I'm trying to compare two datasets where an attribute is stratified differently. Is it possible to do stratified random sampling in one dataset but using the stratification of another? To clarify, an example:

Dataset A has 1M records, with the attribute color. The entire dataset has 50% blue 50% red.

Now I have another dataset, Dataset B, of 100k records with the same attribute, color, but with a 20% blue 80% red distribution.

Is it possible for me to conduct stratified random sampling on Dataset A so that I get 100k records with 20% blue and 80% red?

I don't have any code written yet, simple because I don't know where to start. I've looked at the documentation for proc surveyselect and it seems that it wouldn't be possible with that.

Right now, I'm looking to manually do it, where I'll cut Dataset A by color, and get a 20k random sample from the blue and 80k random sample from the red.

But given that in my real dataset, I want to stratify by 2 attributes with more than 2 levels, I would love to think that there's a more efficient way of doing this.

答:
You had been so close to your answer since you mentioned proc survey select. There is an example for you:

```<code>proc sort data = sashelp.class out = class;
    by sex;
run;

proc surveyselect data = class out = sample sampsize=(5 6) seed=0;
    strata sex;
run;
</code>```

And there are 5 obs with Sex = 'M' and 6 obs with Sex = 'F'.

Body:
You had been so close to your answer since you mentioned proc survey select. There is an example for you:

proc sort data = sashelp.class out = class;
    by sex;
run;

proc surveyselect data = class out = sample sampsize=(5 6) seed=0;
    strata sex;
run;

And there are 5 obs with Sex = 'M' and 6 obs with Sex = 'F'.


问:
How to redirect a page and disguise its url?
I need to do the following on my apache webserver :

Redirect any URL starting with :

```<code> http://mydomain1.com/archive
 to
 http://mydomain2.com/archive
</code>```

Is there a way using mod-rewrite or RewriteEngine to disguise that URL, so that the URL that appears in the browser is mydomain1.com ?   I don't want to give away the fact that we are switching servers.

答:
That's not possible using mod_rewrite. If host changes then it has to be an external redirect using R flag.

A possible workaround is to make server to server call from inside your code on mydomain1 to mydomain2. If using php you can use file_get_contents function to make this happen.

Body:
I need to do the following on my apache webserver :

Redirect any URL starting with :

 http://mydomain1.com/archive
 to
 http://mydomain2.com/archive

Is there a way using mod-rewrite or RewriteEngine to disguise that URL, so that the URL that appears in the browser is mydomain1.com ?   I don't want to give away the fact that we are switching servers.


问:
Convert PDF to image with high resolution
I'm trying to use the command line program convert to take a PDF into an image (JPEG or PNG). Here is one of the PDFs that I'm trying to convert.

I want the program to trim off the excess white-space and return a high enough quality image that the superscripts can be read with ease.

This is my current best attempt. As you can see, the trimming works fine, I just need to sharpen up the resolution quite a bit. This is the command I'm using:

```<code>convert -trim 24.pdf -resize 500% -quality 100 -sharpen 0x1.0 24-11.jpg
</code>```

I've tried to make the following conscious decisions:

resize it larger (has no effect on the resolution)

make the quality as high as possible

use the -sharpen (I've tried a range of values)

Any suggestions please on getting the resolution of the image in the final PNG/JPEG higher would be greatly appreciated!

答:
I have used pdf2image. A simple python library that works like charm.

First install poppler on non linux machine. You can just download the zip. Unzip in Program Files and add bin to Machine Path.

After that you can use pdf2image in python class like this:

```<code>from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
   inputfile,
   output_folder=outputpath,
   grayscale=True, fmt='jpeg')
</code>```

I am not good with python but was able to make exe of it.
Later you may use the exe with file input and output parameter. I have used it in C# and things are working fine.

Image quality is good. OCR works fine.

Edited:
Here is my another finding, You don't need to install Poppler for conversion.
Just make your converter.exe from Python and place it in binary bin folder of Poppler window.
I suppose it will work on azure aswell.

Body:
I'm trying to use the command line program convert to take a PDF into an image (JPEG or PNG). Here is one of the PDFs that I'm trying to convert.

I want the program to trim off the excess white-space and return a high enough quality image that the superscripts can be read with ease.

This is my current best attempt. As you can see, the trimming works fine, I just need to sharpen up the resolution quite a bit. This is the command I'm using:

convert -trim 24.pdf -resize 500% -quality 100 -sharpen 0x1.0 24-11.jpg

I've tried to make the following conscious decisions:

resize it larger (has no effect on the resolution)

make the quality as high as possible

use the -sharpen (I've tried a range of values)

Any suggestions please on getting the resolution of the image in the final PNG/JPEG higher would be greatly appreciated!

Body:
I have used pdf2image. A simple python library that works like charm.

First install poppler on non linux machine. You can just download the zip. Unzip in Program Files and add bin to Machine Path.

After that you can use pdf2image in python class like this:

from pdf2image import convert_from_path, convert_from_bytes
images_from_path = convert_from_path(
   inputfile,
   output_folder=outputpath,
   grayscale=True, fmt='jpeg')

I am not good with python but was able to make exe of it.
Later you may use the exe with file input and output parameter. I have used it in C# and things are working fine.

Image quality is good. OCR works fine.

Edited:
Here is my another finding, You don't need to install Poppler for conversion.
Just make your converter.exe from Python and place it in binary bin folder of Poppler window.
I suppose it will work on azure aswell.