问:
How to download a text data set from a website
I am interesting in a yeast dataset from UCI (please see the link). The data is saved in text formula. I would like to load it into Rstudio. I saved it in office word (copy and paste). Then, I tried to load it into R studio but I got unclear words instead of the data.

https://archive.ics.uci.edu/ml/datasets/Yeast

Any help please?

答:
Grabbing the data is pretty easy; you can just pass the file URL directly to read.table. Getting the names is a lot more work, as they're buried in a text file. If you like, you can extract them with regex:

library(tidyverse)

yeast <- read.table('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.data', stringsAsFactors = FALSE)

l <- readLines('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.names')
l <- l[(grep('^7', l) + 1):(grep('^8', l) - 1)]
l <- l[grep('\\d\\..*:', l)]

names(yeast) <- make.names(c(sub('.*\\d\\.\\s+(.*):.*', '\\1', l), 'class'))

str(yeast)
#> 'data.frame':    1484 obs. of  10 variables:
#>  $ Sequence.Name: chr  "ADT1_YEAST" "ADT2_YEAST" "ADT3_YEAST" "AAR2_YEAST" ...
#>  $ mcg          : num  0.58 0.43 0.64 0.58 0.42 0.51 0.5 0.48 0.55 0.4 ...
#>  $ gvh          : num  0.61 0.67 0.62 0.44 0.44 0.4 0.54 0.45 0.5 0.39 ...
#>  $ alm          : num  0.47 0.48 0.49 0.57 0.48 0.56 0.48 0.59 0.66 0.6 ...
#>  $ mit          : num  0.13 0.27 0.15 0.13 0.54 0.17 0.65 0.2 0.36 0.15 ...
#>  $ erl          : num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
#>  $ pox          : num  0 0 0 0 0 0.5 0 0 0 0 ...
#>  $ vac          : num  0.48 0.53 0.53 0.54 0.48 0.49 0.53 0.58 0.49 0.58 ...
#>  $ nuc          : num  0.22 0.22 0.22 0.22 0.22 0.22 0.22 0.34 0.22 0.3 ...
#>  $ class        : chr  "MIT" "MIT" "MIT" "NUC" ...
```

...or just copy them all out by hand.

Body:
Grabbing the data is pretty easy; you can just pass the file URL directly to read.table. Getting the names is a lot more work, as they're buried in a text file. If you like, you can extract them with regex:

library(tidyverse)

yeast <- read.table('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.data', stringsAsFactors = FALSE)

l <- readLines('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.names')
l <- l[(grep('^7', l) + 1):(grep('^8', l) - 1)]
l <- l[grep('\\d\\..*:', l)]

names(yeast) <- make.names(c(sub('.*\\d\\.\\s+(.*):.*', '\\1', l), 'class'))

str(yeast)
#> 'data.frame':    1484 obs. of  10 variables:
#>  $ Sequence.Name: chr  "ADT1_YEAST" "ADT2_YEAST" "ADT3_YEAST" "AAR2_YEAST" ...
#>  $ mcg          : num  0.58 0.43 0.64 0.58 0.42 0.51 0.5 0.48 0.55 0.4 ...
#>  $ gvh          : num  0.61 0.67 0.62 0.44 0.44 0.4 0.54 0.45 0.5 0.39 ...
#>  $ alm          : num  0.47 0.48 0.49 0.57 0.48 0.56 0.48 0.59 0.66 0.6 ...
#>  $ mit          : num  0.13 0.27 0.15 0.13 0.54 0.17 0.65 0.2 0.36 0.15 ...
#>  $ erl          : num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
#>  $ pox          : num  0 0 0 0 0 0.5 0 0 0 0 ...
#>  $ vac          : num  0.48 0.53 0.53 0.54 0.48 0.49 0.53 0.58 0.49 0.58 ...
#>  $ nuc          : num  0.22 0.22 0.22 0.22 0.22 0.22 0.22 0.34 0.22 0.3 ...
#>  $ class        : chr  "MIT" "MIT" "MIT" "NUC" ...

...or just copy them all out by hand.


来源: stackexchange

问:
How can I print the possible combinations of a list in Python?
My list is:

```<code>groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
</code>```

So I want to print all the unique combinations of teams that will play each other:

```<code>Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay
</code>```

Can I do this with a for loop?

答:
Whenever you're thinking of permutations, combinations, Cartesian products, etc, think of the itertools library; it's standard to Python. And if it's not in there have a look at sympy.

```<code>>>> from itertools import combinations
>>> for c in combinations(groupA, 2):
...     '{} Vs. {}'.format(*c)
...
'Russia Vs. Egypt'
'Russia Vs. Saudi Arabia'
'Russia Vs. Uruguay'
'Egypt Vs. Saudi Arabia'
'Egypt Vs. Uruguay'
'Saudi Arabia Vs. Uruguay'
</code>```

format is a nice alternative for output too.

ContentLicense: CC BY-SA 3.0

Body:
My list is:

groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

So I want to print all the unique combinations of teams that will play each other:

Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay

Can I do this with a for loop?

Body:
Whenever you're thinking of permutations, combinations, Cartesian products, etc, think of the itertools library; it's standard to Python. And if it's not in there have a look at sympy.

>>> from itertools import combinations
>>> for c in combinations(groupA, 2):
...     '{} Vs. {}'.format(*c)
...
'Russia Vs. Egypt'
'Russia Vs. Saudi Arabia'
'Russia Vs. Uruguay'
'Egypt Vs. Saudi Arabia'
'Egypt Vs. Uruguay'
'Saudi Arabia Vs. Uruguay'

format is a nice alternative for output too.


问:
Storing Access Token and Refresh Token on Xamarin
I have a WebApi 2 using ASP.Net Identity. I want to consume this in a Xamarin application, I'm struggling to find a straight answer to this question:

How can i store the Access Token and Refresh token on the device using Xamarin, similar to Cookies or Session state in ASP.NET?

I'm able to make the call to get these tokens, but i'm new to Xamarin and can't work out how to save them on the device so the user doesn't need to constantly login.

The targets devices are Windows, iOS and Android

答:
We can use Xamarin.Auth to store data in the account store like below.

Storing Account Information

```<code>public void SaveCredentials (string userName, string password)
{
  if (!string.IsNullOrWhiteSpace (userName) && !string.IsNullOrWhiteSpace (password)) {
    Account account = new Account {
      Username = userName
    };
    account.Properties.Add ("Password", password);
    AccountStore.Create ().Save (account, App.AppName);
  }
}
</code>```

Retrieving Account Information

```<code>public string UserName {
  get {
    var account = AccountStore.Create ().FindAccountsForService (App.AppName).FirstOrDefault ();
    return (account != null) ? account.Username : null;
  }
}

public string Password {
  get {
    var account = AccountStore.Create ().FindAccountsForService (App.AppName).FirstOrDefault ();
    return (account != null) ? account.Properties ["Password"] : null;
  }
}
</code>```

Body:
We can use Xamarin.Auth to store data in the account store like below.

Storing Account Information

public void SaveCredentials (string userName, string password)
{
  if (!string.IsNullOrWhiteSpace (userName) && !string.IsNullOrWhiteSpace (password)) {
    Account account = new Account {
      Username = userName
    };
    account.Properties.Add ("Password", password);
    AccountStore.Create ().Save (account, App.AppName);
  }
}

Retrieving Account Information

public string UserName {
  get {
    var account = AccountStore.Create ().FindAccountsForService (App.AppName).FirstOrDefault ();
    return (account != null) ? account.Username : null;
  }
}

public string Password {
  get {
    var account = AccountStore.Create ().FindAccountsForService (App.AppName).FirstOrDefault ();
    return (account != null) ? account.Properties ["Password"] : null;
  }
}


问:
Boto3 ec2 describe_instances always returns empty
I have a very simple sandbox I'm trying to get to work so I can use it in a bigger application:

```<code>ec2_client = boto3.client(
    'ec2',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY)

response = ec2_client.describe_instances()
print(response)
</code>```

and it results in...

```<code>{
  'Reservations': [],
  'ResponseMetadata': {
    'RequestId': '2c28e8aa-da6d-4ca4-8ea7-f672518cac9f',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'content-type': 'text/xml;charset=UTF-8',
      'transfer-encoding': 'chunked',
      'vary': 'Accept-Encoding',
      'date': 'Thu, 07 Dec 2017 16:44:30 GMT',
      'server': 'AmazonEC2'
  },
  'RetryAttempts': 0}
}
</code>```

But the problem is no matter how many times I run this Reservations is ALWAYS empty :(.

In AWS consonle I can CLEARLLY see an instance is running...

I tried starting more instances, restarting the instances I had running. I put my initial script in a loop and ran it on repeat while I did this looking for any sign of the Reservations array actually having data.

I double checked that my aws ACCESS_KEY and SECRET_KEY are both correct and pointing to the correct account. They are.

I have no clue why this is. Its so simple and should be working. I'm new to AWS so any help is appreciated.

答:
Seems that you forgot to add the region.

Set the region when creating your client

```<code>ec2_client = boto3.client(
  'ec2',
  aws_access_key_id=ACCESS_KEY,
  aws_secret_access_key=SECRET_KEY,
  region_name=REGION_NAME
)

response = ec2_client.describe_instances()
print(response)
</code>```

If your EC2 instances are in Oregon, you can do region_name='us-west-2'

Hard coding credentials is not recommended. You can configure your profiles using the awscli and then reference it in your code.

```<code>session = boto3.Session(profile_name='dev')
# Any clients created from this session will use credentials
# from the [dev] section of ~/.aws/credentials.
ec2_client = session.client('ec2')
</code>```

You can read more about Boto3 credentials Boto3 Credentials

Body:
I have a very simple sandbox I'm trying to get to work so I can use it in a bigger application:

ec2_client = boto3.client(
    'ec2',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY)

response = ec2_client.describe_instances()
print(response)

and it results in...

{
  'Reservations': [],
  'ResponseMetadata': {
    'RequestId': '2c28e8aa-da6d-4ca4-8ea7-f672518cac9f',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'content-type': 'text/xml;charset=UTF-8',
      'transfer-encoding': 'chunked',
      'vary': 'Accept-Encoding',
      'date': 'Thu, 07 Dec 2017 16:44:30 GMT',
      'server': 'AmazonEC2'
  },
  'RetryAttempts': 0}
}

But the problem is no matter how many times I run this Reservations is ALWAYS empty :(.

In AWS consonle I can CLEARLLY see an instance is running...

I tried starting more instances, restarting the instances I had running. I put my initial script in a loop and ran it on repeat while I did this looking for any sign of the Reservations array actually having data.

I double checked that my aws ACCESS_KEY and SECRET_KEY are both correct and pointing to the correct account. They are.

I have no clue why this is. Its so simple and should be working. I'm new to AWS so any help is appreciated.

Body:
Seems that you forgot to add the region.

Set the region when creating your client

ec2_client = boto3.client(
  'ec2',
  aws_access_key_id=ACCESS_KEY,
  aws_secret_access_key=SECRET_KEY,
  region_name=REGION_NAME
)

response = ec2_client.describe_instances()
print(response)

If your EC2 instances are in Oregon, you can do region_name='us-west-2'

Hard coding credentials is not recommended. You can configure your profiles using the awscli and then reference it in your code.

session = boto3.Session(profile_name='dev')
# Any clients created from this session will use credentials
# from the [dev] section of ~/.aws/credentials.
ec2_client = session.client('ec2')

You can read more about Boto3 credentials Boto3 Credentials


问:
How to remove elements in a vector that match some element in another vector
I want to remove elements in a vector v2 that match the elements in another vector v1, where each element in v1 has a corresponding element in v2 but not vice versa.

My idea is to use std::vector::erase, std::remove_if and std::find like this:

```<code>std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

v2.erase(
  std::remove_if(v2.begin(), v2.end()
  , [&v1](auto& item)
  {
    return std::find(v1.begin(), v1.end(), item) != v1.end();
  })
);
</code>```

Which works.  However, I wonder if I could do without matching those that have already been matched as this is a 1:1 relationship when going from v1 -> v2.  v1 will be blown away afterwards, so it can be modified.

答:
Sort v1.  Use std equal range to find elements in it.  Use that with your remove-erase idiom code (with a bugfix).

This is O((M+N)lg N)

```<code>std::sort( v1.begin(), v1.end() );
auto removed=std::remove_if(
  v2.begin(), v2.end(),
  [&v1](auto& item)
  {
    auto r= std::equal_range(v1.begin(), v1.end(), item);
    return r.first!=r.second;
  }
);
v2.erase(removed, v2.end());
</code>```

note that you forgot .end in your erase call, which is a common serious error when doing remove-erase.

Editing the source vector to eliminate elements is not worth it if you have a reasonable number of entries, barring extremely fancy data structures.

Body:
I want to remove elements in a vector v2 that match the elements in another vector v1, where each element in v1 has a corresponding element in v2 but not vice versa.

My idea is to use std::vector::erase, std::remove_if and std::find like this:

std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

v2.erase(
  std::remove_if(v2.begin(), v2.end()
  , [&v1](auto& item)
  {
    return std::find(v1.begin(), v1.end(), item) != v1.end();
  })
);

Which works.  However, I wonder if I could do without matching those that have already been matched as this is a 1:1 relationship when going from v1 -> v2.  v1 will be blown away afterwards, so it can be modified.

Body:
Sort v1.  Use std equal range to find elements in it.  Use that with your remove-erase idiom code (with a bugfix).

This is O((M+N)lg N)

std::sort( v1.begin(), v1.end() );
auto removed=std::remove_if(
  v2.begin(), v2.end(),
  [&v1](auto& item)
  {
    auto r= std::equal_range(v1.begin(), v1.end(), item);
    return r.first!=r.second;
  }
);
v2.erase(removed, v2.end());

note that you forgot .end in your erase call, which is a common serious error when doing remove-erase.

Editing the source vector to eliminate elements is not worth it if you have a reasonable number of entries, barring extremely fancy data structures.


问:
Import data to ragged array
As an exercise, I have build a simple program that, given a text file of N lowercase words and whitespaces, populates a ragged array char *en[N].

It works without great problems, apart for one: it populates the ragged array with only the last word of the input.

```<code>#include<stdio.h>
#include<ctype.h>

int main(int argc, char *argv[]){
    int i = 0, j = 0;
    char *en[100];
    char temp[20];

    FILE *p = fopen(argv[1], "r");
    char single;

    while((single = fgetc(p)) != EOF){
        if(!isspace(single))          /* Temporary store a single word */
            temp[i++] = single;
        else{
            temp[i] = '\0';
            en[j++] = temp;           /* Save stored word in ragged array */
            i = 0;
        }
    }

    printf("%s\n", en[0]);    /* Return the same than en[1] and en[99] */
    printf("%s\n", en[1]);
    printf("%s\n", en[99]);

    return 0;
}
</code>```

I cannot understand why it goes down to the end of the input file. I am unable of detecting major issues that could suggest a wrong approach.

Edit:

The reasoning behind my approach was that an array of *char can be initialized with this form:

```<code>p[0] = "abc";
</code>```

reasoning that I wrongly tried to translate in the error above, that @coderredoc brilliantly caught. As far as the dimensions of single words and inputs are concerned, I admit I did not put many attention in them. The exercise is centered on a different topic. In any case, thanks a lot your your valuable suggestions!

答:
You just found out the awesomeness of pointers, congratulations!

Seriously, char *en[100] is an array of pointers. en[j++] = temp; assigns the pointer to the first value of temp to a pointer at en[j++]. And you do this over and over again. No surprise that you end up with an array of pointers, all of which point to the same array temp, which holds the contents of the last word.

What to learn from this: a pointer merely points to some memory, and no memory copying happens when you do en[j++] = temp;. You have to allocate the memory yourself and copy temp to that new memory yourself.

Title: Import data to ragged array

Body:
As an exercise, I have build a simple program that, given a text file of N lowercase words and whitespaces, populates a ragged array char *en[N].

It works without great problems, apart for one: it populates the ragged array with only the last word of the input.

#include<stdio.h>
#include<ctype.h>

int main(int argc, char *argv[]){
    int i = 0, j = 0;
    char *en[100];
    char temp[20];

    FILE *p = fopen(argv[1], "r");
    char single;

    while((single = fgetc(p)) != EOF){
        if(!isspace(single))          /* Temporary store a single word */
            temp[i++] = single;
        else{
            temp[i] = '\0';
            en[j++] = temp;           /* Save stored word in ragged array */
            i = 0;
        }
    }

    printf("%s\n", en[0]);    /* Return the same than en[1] and en[99] */
    printf("%s\n", en[1]);
    printf("%s\n", en[99]);

    return 0;
}

I cannot understand why it goes down to the end of the input file. I am unable of detecting major issues that could suggest a wrong approach.

Edit:

The reasoning behind my approach was that an array of *char can be initialized with this form:

p[0] = "abc";

reasoning that I wrongly tried to translate in the error above, that @coderredoc brilliantly caught. As far as the dimensions of single words and inputs are concerned, I admit I did not put many attention in them. The exercise is centered on a different topic. In any case, thanks a lot your your valuable suggestions!


问:
R Pull From FTP Starts Failing
Recently had this issue crop up. I pull from an FTP on a bi-monthly schedule into R using a URL string as such:

url <- "ftp://User:Pass@ftp.myftp.com/"

I use RCurl syntax to pull fill names and then loop through each name, pulling with read.csv with a URL as such:

myData <- read.csv("ftp://User:Pass@ftp.myftp.com/mycsv.csv")

This worked two months ago, but has started failing today. It could potentially be something has changed in my FTP, but if I drop the above URL in an internet browser, it prompts me to download the file.

Python is able to pull the file, so I feel like I am left with something has changed in R, which I have since updated to 3.4.2 and update RStudio to the current version.

The specific error I get is:

```<code>Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : InternetOpenUrl failed: ''
</code>```

I'm going to attempt to install a downgraded version of RStudio and R to what was 2 months ago to see if this solves it. But in the mean time, any ideas? Is this happening for anyone else? It could even by my IT department potentially putting up some kind of firewall. Really scratching my head here.

Thanks in advance.

EDIT: Looks like fread from data.table succeeds. I don't have a clue why read.csv has started failing, however.

答:
After going down the debug chain, it seems that I need to set this option to get resolve my issue:

```<code>options(url.method = "libcurl")
</code>```

The other option:

```<code>options(download.file.method="libcurl")
</code>```

Only addresses the download.file function, and not the file function, which read.csv was calling. The former addresses file.

Title: R Pull From FTP Starts Failing

Body:
Recently had this issue crop up. I pull from an FTP on a bi-monthly schedule into R using a URL string as such:

url <- "ftp://User:Pass@ftp.myftp.com/"

I use RCurl syntax to pull fill names and then loop through each name, pulling with read.csv with a URL as such:

myData <- read.csv("ftp://User:Pass@ftp.myftp.com/mycsv.csv")

This worked two months ago, but has started failing today. It could potentially be something has changed in my FTP, but if I drop the above URL in an internet browser, it prompts me to download the file.

Python is able to pull the file, so I feel like I am left with something has changed in R, which I have since updated to 3.4.2 and update RStudio to the current version.

The specific error I get is:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : InternetOpenUrl failed: ''

I'm going to attempt to install a downgraded version of RStudio and R to what was 2 months ago to see if this solves it. But in the mean time, any ideas? Is this happening for anyone else? It could even by my IT department potentially putting up some kind of firewall. Really scratching my head here.

Thanks in advance.

EDIT: Looks like fread from data.table succeeds. I don't have a clue why read.csv has started failing, however.

Body:
After going down the debug chain, it seems that I need to set this option to get resolve my issue:

options(url.method = "libcurl")

The other option:

options(download.file.method="libcurl")

Only addresses the download.file function, and not the file function, which read.csv was calling. The former addresses file.


问:
XGboost wheel for Win 7 and 32 bit and python 3.4
Is there a simple wheel for XGboost  ML library available somewhere for Win 7 and 32 bit and python 3.4  as I couldnt find on http://www.lfd.uci.edu/~gohlke/pythonlibs/#xgboost and wouldn't wanna go the Vis c++ compiler make dlls route ??
Though wheel for python 35 and 36 are available there

Thanks

答:
Download xgboost from https://www.lfd.uci.edu/~gohlke/pythonlibs/#xgboost and change the python version to 3.4.
For instance xgboost‑0.6+20171121‑cp35‑cp35m‑win_amd64.whl becomes xgboost‑0.6+20171121‑cp34‑cp34m‑win_amd64.whl.

It works for me with python 3.4.2 and xgboost‑0.6+20171121‑cp35‑cp35m‑win_amd64.whl.


问:
activate bash with AIX
I am working with AIX and logged in with a user that is not able to autocomplete directory paths and filenames. First I have to commit bashin putty then I can use tabulator-key to autocomplete directory paths.

What do I have to do that I do not need to commit bash command? Maybe I have to set an entry to a special file? Thanks in advance!

答:
Just did this on AIX 7.1.1.0 ! The command is:

```<code>chsh <username> /bin/bash
</code>```

followed by a restart of the SSH session.

Done.

Title: activate bash with AIX

Body:
Just did this on AIX 7.1.1.0 ! The command is:

chsh <username> /bin/bash

followed by a restart of the SSH session.

Done.


问:
Aggregation of fields inside nested type field
I want to aggregate keyword type field which lies inside a nested type field. The mapping for nested field is as below:

```<code>"Nested_field" : {
    "type" : "nested",
    "properties" : {
        "Keyword_field" : {
            "type" : "keyword"
        }
    }
}
</code>```

And the part of query which I am using to aggregate is as below:

```<code>"aggregations": {
    "Nested_field": {
        "aggregations": {
            "Keyword_field": {
                "terms": {
                    "field": "Nested_field.Keyword_field"
                }
            }
        },
        "filter": {
            "bool": {}
        }
    },
}
</code>```

But this is not returning correct aggregation. Even though there are Keyword_field value existing docs, the query returns 0 buckets. So, there is something wrong in my aggregation query. Can anyone help me to find what's wrong?

答:
I think you need to provide a nested path in there. This worked in ES 5, but it looks like you're using 6 based on the "aggregations" vs "aggs", so let me know if it doesn't work and I'll scrap this answer. Give this a try:</p>

```<code>{
    "aggregations": {
        "nested_level": {
            "nested": {
                "path": "Nested_field"
            },
            "aggregations": {
                "keyword_field": {
                    "terms": {
                        "field": "Nested_field.Keyword_field"
                    }
                }
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to aggregate keyword type field which lies inside a nested type field. The mapping for nested field is as below:

"Nested_field" : {
    "type" : "nested",
    "properties" : {
        "Keyword_field" : {
            "type" : "keyword"
        }
    }
}

And the part of query which I am using to aggregate is as below:

"aggregations": {
    "Nested_field": {
        "aggregations": {
            "Keyword_field": {
                "terms": {
                    "field": "Nested_field.Keyword_field"
                }
            }
        },
        "filter": {
            "bool": {}
        }
    },
}

But this is not returning correct aggregation. Even though there are Keyword_field value existing docs, the query returns 0 buckets. So, there is something wrong in my aggregation query. Can anyone help me to find what's wrong?

Body:
I think you need to provide a nested path in there. This worked in ES 5, but it looks like you're using 6 based on the "aggregations" vs "aggs", so let me know if it doesn't work and I'll scrap this answer. Give this a try:

{
    "aggregations": {
        "nested_level": {
            "nested": {
                "path": "Nested_field"
            },
            "aggregations": {
                "keyword_field": {
                    "terms": {
                        "field": "Nested_field.Keyword_field"
                    }
                }
            }
        }
    }
}


问:
The Run Destination is not valid Xcode
I am using Xcode 5 and when I try to run my app on iOS 6 simulator I am getting the following error.

```<code> The scheme 'Appname' contains no buildables that can be built for the
`SDKs` supported by the run destination iPhone Retina (4-inch). Make sure your
targets all specify `SDKs` that are supported by this version of `Xcode`.
</code>```

Base SDK is set to iOS SDK 7.0.
iOS deployment target is set to iOS 6.0

答: I had exactly same issues, however after restarting My (Xcode 9.2) IDE the issue disappeared!</p>

Title: The Run Destination is not valid Xcode

Body:
I am using Xcode 5 and when I try to run my app on iOS 6 simulator I am getting the following error.

 The scheme 'Appname' contains no buildables that can be built for the
`SDKs` supported by the run destination iPhone Retina (4-inch). Make sure your
targets all specify `SDKs` that are supported by this version of `Xcode`.

Base SDK is set to iOS SDK 7.0.
iOS deployment target is set to iOS 6.0


问:
Having issues interpreting json inside php and passing it to mysql
I am new to php and I am not sure how to debug this.

I am trying to pass json to a php page and then send that data to mySQL.

I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.

Here is my javascript code:

```<code> var request = new XMLHttpRequest();
                  request.open('POST', 'http://website/saveF.php', true);
                  request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                  request.send(bInfo);
</code>```

This is taking information in and passing it to a php file to then be added to a mySQL database.

Here is my php code:

This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.

```<code>//as long as the connection is good then we keep it live.
include_once "head.php";

if ($conn->connect_error) {
    die("connection failed: " . $conn->connect_error);
}

//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);

//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.

    while($i < $totalNum){
        $var0 = $input[$i][0];
        $var1 = $input[$i][1];
        $var2 = $input[$i][2];
        $var3 = $input[$i][3];
        $var4 = $input[$i][4];
        $var5 = $input[$i][5];
        $var6 = $input[$i][6];

        if($var1 == "Not Listed") {
            $sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
        }else{

            //here we set the information into the database.
           $sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
    }

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $i++;
    }
</code>```

答:
First, note that this line:

```<code>$input = filter_var($postThings, FILTER_SANITIZE_STRING);
</code>```

Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.

Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).

http://php.net/manual/en/mysqli.real-escape-string.php

Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.

Body:
I am new to php and I am not sure how to debug this.

I am trying to pass json to a php page and then send that data to mySQL.

I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.

Here is my javascript code:

 var request = new XMLHttpRequest();
                  request.open('POST', 'http://website/saveF.php', true);
                  request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                  request.send(bInfo);

This is taking information in and passing it to a php file to then be added to a mySQL database.

Here is my php code:

This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.

//as long as the connection is good then we keep it live.
include_once "head.php";

if ($conn->connect_error) {
    die("connection failed: " . $conn->connect_error);
}

//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);

//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.

    while($i < $totalNum){
        $var0 = $input[$i][0];
        $var1 = $input[$i][1];
        $var2 = $input[$i][2];
        $var3 = $input[$i][3];
        $var4 = $input[$i][4];
        $var5 = $input[$i][5];
        $var6 = $input[$i][6];

        if($var1 == "Not Listed") {
            $sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
        }else{

            //here we set the information into the database.
           $sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
    }

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "
" . $conn->error;
        }

        $i++;
    }

Body:
First, note that this line:

$input = filter_var($postThings, FILTER_SANITIZE_STRING);

Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.

Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).

http://php.net/manual/en/mysqli.real-escape-string.php

Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.


问:
How can we clear the search field of a responsive table?
We can add search to a table defined using TabularTables and make it caseSensitive, smart and enterOnly. However, I don't see an option to clear the search field on table/page reload. Any idea how I can clear search?

In the table 'stateSave' is set to true and can't be turned off because I would like page size and sorting to be saved across page reloads.

https://github.com/aldeed/meteor-tabular#customizing-search-behavior

答:
Update onRendered or onDestroyed template handler to clear the search value from datatable's state and redraw.

https://datatables.net/reference/api/search()

```<code>Template.your_template_name.onDestroyed(function() {
  var table = $('#your_datatable_id').DataTable({
    'retrieve': true
  });
  if (table.search() !== "") {
    return table.search("").draw();
  }
});
</code>```

Body:
Update onRendered or onDestroyed template handler to clear the search value from datatable's state and redraw.

https://datatables.net/reference/api/search()

Template.your_template_name.onDestroyed(function() {
  var table = $('#your_datatable_id').DataTable({
    'retrieve': true
  });
  if (table.search() !== "") {
    return table.search("").draw();
  }
});


问:
Transfer files using checksums only?
Would it be possible to transfer large files using only a system of checksums, and then reconstruct the original file by calculations?

Say that you transfer the MD5 checksum of a file and the size of the file. By making a "virtual file" and calculating it's checksum, trying every single bit combination, you should eventually "reach" the original file. But on the way you would also get a lot of "collisions" where the checksum also match.

So we change the first byte of the original file to some specified value, calculate the checksum again, and send this too. If we make the same substitution in the virtual file we can test each "collision" to see if it still matches. This should narrow it down a bit, and we can do this several times.

Of course, the computing power to do this would be enormous. But is it theoretically possible, and how many checksums would you need to transfer something (say 1mb)? Or would perhaps the amount of data needed to transfer the checksums almost as large as the file, making it pointless?

答: I think what you are thinking of is in fact an interesting topic, but you haven't hit upon the right method. If I can try and rephrase your question, you are asking if there is a way to apply a function to some data, transmit the result of the function, and then reconstruct the original data from the terser function result. For a single MD5 checksum the answer is no, but with other functions, provided you are willingly to send several function results, it is possible. In general this area of research is called compressed sensing. Sometimes exact reconstruction is possible, but more often it is used as a lossy compression scheme for images and other visual or sound data. </p>

ContentLicense: CC BY-SA 2.5

Title: Transfer files using checksums only?


问:
While converting UTC date to local date giving wrong time
I have UTC date /Date(1512624687600)/

I want to convert it into local time but its giving me 2017-12-07 09:31 PM Indian Standard Time etc. I had tried different types to get solution (local time). Please find my code below:

```<code>$scope.UtcToLocal = function(utcTime){
var milli = parseInt(utcTime.replace(/\/Date\((-?\d+)\)\//, '$1'));
alert(milli);

var fromDate = moment(utcTime).format("YYYY-MM-DD hh:mm A");
alert(fromDate);

var gmtDateTime = moment.utc(fromDate, "YYYY-MM-DD h:mm A");
alert(gmtDateTime);

var local = gmtDateTime.local().format('YYYY-MMM-DD h:mm A');
return local;
</code>```

I am using Moment.js code to demonstrate the above codes.

答: UTC date time always give universal time of your region. most probably it will give you 4 hours later or earlier time. If you want get local time, then you need to use DateTime.Now in case of asp.net mvc</p>

Body:
I have UTC date /Date(1512624687600)/

I want to convert it into local time but its giving me 2017-12-07 09:31 PM Indian Standard Time etc. I had tried different types to get solution (local time). Please find my code below:

$scope.UtcToLocal = function(utcTime){
var milli = parseInt(utcTime.replace(/\/Date\((-?\d+)\)\//, '$1'));
alert(milli);

var fromDate = moment(utcTime).format("YYYY-MM-DD hh:mm A");
alert(fromDate);

var gmtDateTime = moment.utc(fromDate, "YYYY-MM-DD h:mm A");
alert(gmtDateTime);

var local = gmtDateTime.local().format('YYYY-MMM-DD h:mm A');
return local;

I am using Moment.js code to demonstrate the above codes.


问:
Django-filters how to pass current user from view inside FilterSet?
I have a filter where I need to access the request.user. However, Django-filter does not pass it. I was able to figure out possible FilterSet configuration.
But how to pass current user from view inside FilterSet?

filters.py

```<code>class TransationsListFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(TransationsListFilter, self).__init__(*args, **kwargs)

    transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs {'placeholder': 'DD/MM/YYYY'}))
    class Meta:
        model = Transations
        fields = ['transaction_date']

    @property
        def qs(self):
        return super(TransationsListFilter, self).filter(user=user)
</code>```

views.py

```<code>class TransactionsList(PagedFilteredTableView):
    model = Transations
    table_class = TransactionsTable
    filter_class = TransationsListFilter
    formhelper_class = TransationsFormHelper
</code>```

models.py

```<code>class Transations(models.Model):
    transaction_date = models.DateField(default=datetime.now, blank=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        default = 0
   )
</code>```

答:
I solved my problem with django-crum plugin.
 Here is my final code(other files are the same):

filters.py

```<code>import django_filters
from django_filters import DateFromToRangeFilter
from django_filters.widgets import RangeWidget
from .models import Transations,Account
from crum import get_current_user

class TransationsListFilter(django_filters.FilterSet):
    transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'DD/MM/YYYY'}))
    class Meta:
        model = Transations
        fields = ['transaction_date']

    @property
    def qs(self):
        parent = super(TransationsListFilter, self).qs
        return parent.filter(user=get_current_user())
</code>```

Body:
I have a filter where I need to access the request.user. However, Django-filter does not pass it. I was able to figure out possible FilterSet configuration.
But how to pass current user from view inside FilterSet?

filters.py

class TransationsListFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(TransationsListFilter, self).__init__(*args, **kwargs)

    transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs {'placeholder': 'DD/MM/YYYY'}))
    class Meta:
        model = Transations
        fields = ['transaction_date']

    @property
        def qs(self):
        return super(TransationsListFilter, self).filter(user=user)

views.py

class TransactionsList(PagedFilteredTableView):
    model = Transations
    table_class = TransactionsTable
    filter_class = TransationsListFilter
    formhelper_class = TransationsFormHelper

models.py

class Transations(models.Model):
    transaction_date = models.DateField(default=datetime.now, blank=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        default = 0
   )

Body:
I solved my problem with django-crum plugin.
 Here is my final code(other files are the same):

filters.py

import django_filters
from django_filters import DateFromToRangeFilter
from django_filters.widgets import RangeWidget
from .models import Transations,Account
from crum import get_current_user

class TransationsListFilter(django_filters.FilterSet):
    transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'DD/MM/YYYY'}))
    class Meta:
        model = Transations
        fields = ['transaction_date']

    @property
    def qs(self):
        parent = super(TransationsListFilter, self).qs
        return parent.filter(user=get_current_user())


问:
d3 radial tree highlight path
I just have a quick question regarding changing the color of a path of a stroke of the stock radial tree by Mike Bostock

https://bl.ocks.org/mbostock/4063550

For example, if I can change the color of sub links such as:

```<code>var link = g.selectAll(".link")
    .data(root.descendants().slice(1))
    .enter().append("path")
      .attr("class", "link")
      .style("fill", "none")
      .attr("d", function(d) {
        return "M" + project(d.x, d.y)
            + "C" + project(d.x, (d.y + d.parent.y) / 2)
            + " " + project(d.parent.x, (d.y + d.parent.y) / 2)
            + " " + project(d.parent.x, d.parent.y);
      });

    link.attr('stroke', function(d) {
       if (d.id.startsWith("Root.Item1")){
          return "#386eff";
        }

        if (d.id.startsWith("Root.Item2")){
          return "#45cbf2";
        }
        else return '#70f2ad';
        });
</code>```

This will change all the link colors for data that starts with Root.Item2

I.e. Root.Item2.Child1 and Root.Item2.Child2

will have the same color.

However, what If I wish to highlight the paths for Root.Item2.Child2 only and leave the other links the same color?

The concept is something like highlight the path that starts with Root and ends in Child2?

Thanks

答:
I was able to figure this out in a roundabout way by checking the d.children of the node. Not sure if it's ideal but it works if anyone else wishes to do something similar.</p>

```<code>if (d.id.startsWith("Root.Item2")) {
                for (var i = 0; i < d.children.length; i++ ) {
                    if (d.id.startsWith("Root.Item2.Child1") |
                    ) {
                        return "red";
                    }
                }
</code>```

Title: d3 radial tree highlight path

Body:
I just have a quick question regarding changing the color of a path of a stroke of the stock radial tree by Mike Bostock

https://bl.ocks.org/mbostock/4063550

For example, if I can change the color of sub links such as:

var link = g.selectAll(".link")
    .data(root.descendants().slice(1))
    .enter().append("path")
      .attr("class", "link")
      .style("fill", "none")
      .attr("d", function(d) {
        return "M" + project(d.x, d.y)
            + "C" + project(d.x, (d.y + d.parent.y) / 2)
            + " " + project(d.parent.x, (d.y + d.parent.y) / 2)
            + " " + project(d.parent.x, d.parent.y);
      });

    link.attr('stroke', function(d) {
       if (d.id.startsWith("Root.Item1")){
          return "#386eff";
        }

        if (d.id.startsWith("Root.Item2")){
          return "#45cbf2";
        }
        else return '#70f2ad';
        });

This will change all the link colors for data that starts with Root.Item2

I.e. Root.Item2.Child1 and Root.Item2.Child2

will have the same color.

However, what If I wish to highlight the paths for Root.Item2.Child2 only and leave the other links the same color?

The concept is something like highlight the path that starts with Root and ends in Child2?

Thanks

Body:
I was able to figure this out in a roundabout way by checking the d.children of the node. Not sure if it's ideal but it works if anyone else wishes to do something similar.

if (d.id.startsWith("Root.Item2")) {
                for (var i = 0; i < d.children.length; i++ ) {
                    if (d.id.startsWith("Root.Item2.Child1") |
                    ) {
                        return "red";
                    }
                }


问:
Fortran - two-branch IF statement from old (1972) code
Greetings.  Does anyone know what this Fortran IF statement is doing?

```<code>IF(IJJ-2) ,409,411
</code>```

I don't think it's a typo because there are a few other in the same program.  I assumed it was a standard arithmetic IF that simply defaulted the "less than 0" branch to the next exectutbale statement, but I'm not sure about that.  I think this code was hosted on a CDC 6600 around 1970-1972.  I looked through the FORTRAN 77 subset standard but it specifies all three statement lables must be supplied. Any advice is most appreciated.

答:
I think the destination line numbers were for less than, equal to, and greater than zero.
This doesn't look like standard fortran, but at a guess the missing line numbers will
drop through to the next statement.</p>

Body:
Greetings.  Does anyone know what this Fortran IF statement is doing?

IF(IJJ-2) ,409,411

I don't think it's a typo because there are a few other in the same program.  I assumed it was a standard arithmetic IF that simply defaulted the "less than 0" branch to the next exectutbale statement, but I'm not sure about that.  I think this code was hosted on a CDC 6600 around 1970-1972.  I looked through the FORTRAN 77 subset standard but it specifies all three statement lables must be supplied. Any advice is most appreciated.


问:
How to update the ionic lib of my project from 1.3.1 to 1.3.5? ionic lib update doesn't work
I need to update the ionic lib of my project but when I try  'ionic lib update' I have the next error

```<code>    This command has been deprecated.  All resources are currently available in NPM and we recommend that you use NPM to manage these.
More information is available here: https://github.com/driftyco/ionic-cli/wiki/Migrating-to-NPM-from-bower

Local Ionic version: 1.3.1  (/Users/esteban.salazar/Projects/Proteccion/ProteccionApp/www/lib/ionic/version.json)
Invalid version: undefined
</code>```

Ionic info output

Your system information:

Cordova CLI: 6.3.1

  Ionic CLI Version: 2.2.1 .

  Ionic App Lib Version: 2.2.0 .

  ios-deploy version: 1.9.0 .

  ios-sim version: 5.0.8 .

  OS: macOS Sierra .

  Node Version: v6.11.2 .

  Xcode version: Xcode 9.1 Build version 9B55

答: I have to manually update with npm install ionic@version-you-want

Body:
I need to update the ionic lib of my project but when I try  'ionic lib update' I have the next error

    This command has been deprecated.  All resources are currently available in NPM and we recommend that you use NPM to manage these.
More information is available here: https://github.com/driftyco/ionic-cli/wiki/Migrating-to-NPM-from-bower

Local Ionic version: 1.3.1  (/Users/esteban.salazar/Projects/Proteccion/ProteccionApp/www/lib/ionic/version.json)
Invalid version: undefined

Ionic info output

Your system information:

Cordova CLI: 6.3.1

  Ionic CLI Version: 2.2.1 .

  Ionic App Lib Version: 2.2.0 .

  ios-deploy version: 1.9.0 .

  ios-sim version: 5.0.8 .

  OS: macOS Sierra .

  Node Version: v6.11.2 .

  Xcode version: Xcode 9.1 Build version 9B55


问:
Vuejs 2: Unable to switch between tabbed form
I am using Vue2 for buidling a tab-based form. I am using in my main.js

import VueFormWizard from 'vue-form-wizard'

import 'vue-form-wizard/dist/vue-form-wizard.min.css'

Vue.use(VueFormWizard)

import VeeValidate from 'vee-validate'

Vue.use(VeeValidate)

The file AddUser.vue comprises of the following code:

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>

 <div class="wrapper" id="add-user-wrapper">

  <section class="content">
   <form-wizard @on-complete="onComplete"
             shape="tab"
                      color="#3498db"
                      error-color="#a94442">
                <h2 slot="title">Add a New User</h2>
             <tab-content title="User Details" :before-change="validateFirstTab">
              <div class="row">
               <div class="col-md-12">
                 <div class="col-md-4">
                   <div class="form-group">
                                <label class="control-label">Name</label>
                                <input v-model="user.name" v-validate data-vv-rules="required|alpha_spaces" data-vv-delay="500" data-vv-as="Name" class="form-control" :class="{'input': true, 'is-danger': errors.has('name') }" type="text" placeholder="Enter Name" name="name" autofocus="true" />
                          <i v-show="errors.has('name')" class="fa fa-warning"></i>
                          <span v-show="errors.has('name')" class="help is-danger">{{ errors.first('name') }}</span>
                   </div>
                             </div>
                                </form-wizard>
                                </section>
                                </div>
                                <template></code>```

The problem that I am facing is whenever I am trying to validate the input field it is getting validated correctly but throwing an error on console: "cannot read property then of undefined" while switching to the new tab. I searched through the communities only to get back a solution of returning a Promise with resolve(true) always but still unfortunately, even with a valid input in the first tab, I am unable to switch to the next tab(code not given in the html below).

Can someone help me out in this regard as to what or how should be the approach? As I am quite new to Vue, please let me know if you need any further details

答:
A return value is missing in the validator promise. vue-form-wizard beforeChange function is expecting a boolean.

Here's the TabContent component's beforeChange prop.

```<code>  /***
   * Function to execute before tab switch. Return value must be boolean
   * If the return result is false, tab switch is restricted
   */
  beforeChange: {
    type: Function
  },
</code>```

Here's what actually happens when the promise is resolved.

```<code>  validateBeforeChange (promiseFn, callback) {
    this.setValidationError(null)
    // we have a promise
    if (isPromise(promiseFn)) {
      this.setLoading(true)
      promiseFn.then((res) => {
   //                 ^^^
  // res is undefined because there is no return value in your case,
 //  error is catched later on.
//
        this.setLoading(false)
        let validationResult = res === true
        this.executeBeforeChange(validationResult, callback)
      }).catch((error) => {
        this.setLoading(false)
        this.setValidationError(error)
      })
      // we have a simple function
    } else {
      let validationResult = promiseFn === true
      this.executeBeforeChange(validationResult, callback)
    }
  },
</code>```

Try the following:

```<code><script>
import swal from 'sweetalert'

export default {
  methods: {
    validateFirstTab: function () {
      this.$validator.validateAll().then((result) => {
        if (result) {
          return true
        }
        swal('Input Field(s) Validation', 'Please correct the errors!', 'error')
        return false
      })
    }
  }
}
</script>
</code>```

Body:
I am using Vue2 for buidling a tab-based form. I am using in my main.js

import VueFormWizard from 'vue-form-wizard'

import 'vue-form-wizard/dist/vue-form-wizard.min.css'

Vue.use(VueFormWizard)

import VeeValidate from 'vee-validate'

Vue.use(VeeValidate)

The file AddUser.vue comprises of the following code:

<template>

   <form-wizard @on-complete="onComplete"
             shape="tab"
                      color="#3498db"
                      error-color="#a94442">

Add a New User

             <tab-content title="User Details" :before-change="validateFirstTab">

                                Name
                                <input v-model="user.name" v-validate data-vv-rules="required|alpha_spaces" data-vv-delay="500" data-vv-as="Name" class="form-control" :class="{'input': true, 'is-danger': errors.has('name') }" type="text" placeholder="Enter Name" name="name" autofocus="true" />

                          {{ errors.first('name') }}

                                </form-wizard>

                                <template>

The problem that I am facing is whenever I am trying to validate the input field it is getting validated correctly but throwing an error on console: "cannot read property then of undefined" while switching to the new tab. I searched through the communities only to get back a solution of returning a Promise with resolve(true) always but still unfortunately, even with a valid input in the first tab, I am unable to switch to the next tab(code not given in the html below).

Can someone help me out in this regard as to what or how should be the approach? As I am quite new to Vue, please let me know if you need any further details

Body:
A return value is missing in the validator promise. vue-form-wizard beforeChange function is expecting a boolean.

Here's the TabContent component's beforeChange prop.

  /***
   * Function to execute before tab switch. Return value must be boolean
   * If the return result is false, tab switch is restricted
   */
  beforeChange: {
    type: Function
  },

Here's what actually happens when the promise is resolved.

  validateBeforeChange (promiseFn, callback) {
    this.setValidationError(null)
    // we have a promise
    if (isPromise(promiseFn)) {
      this.setLoading(true)
      promiseFn.then((res) => {
   //                 ^^^
  // res is undefined because there is no return value in your case,
 //  error is catched later on.
//
        this.setLoading(false)
        let validationResult = res === true
        this.executeBeforeChange(validationResult, callback)
      }).catch((error) => {
        this.setLoading(false)
        this.setValidationError(error)
      })
      // we have a simple function
    } else {
      let validationResult = promiseFn === true
      this.executeBeforeChange(validationResult, callback)
    }
  },

Try the following:

<script>
import swal from 'sweetalert'

export default {
  methods: {
    validateFirstTab: function () {
      this.$validator.validateAll().then((result) => {
        if (result) {
          return true
        }
        swal('Input Field(s) Validation', 'Please correct the errors!', 'error')
        return false
      })
    }
  }
}
</script>


问:
difference between onViewRender and events to load events in full calendar
I am using onViewRender to load events for my full calendar in an angular2 application.  using onViewRender is making multiple api calls to fetch events. can I use anything else than onViewRender in my template to load events. below is the problem im facing .

```<code>Put a <p-schedule (onViewRender)="testMethod($event)"> on your template. Add a method such as this to your component:

testMethod(e)
{
console.log(e);
}

You'll see that the method is called infinitely.
</code>```

and below is my actual code

component.html

```<code>     <p-schedule [events]="events" [eventLimit] ="3" (onViewRender)="loadEvents($event)"
    (onEventClick)="handleEventClick($event)"
     (onDayClick)="handleDayClick($event)" ></p-schedule>

component.ts

 loadEvents(e) {

    if (this) {
      let month = e.view.start._d.getMonth() + 2;
      let year = e.view.start._d.getFullYear();

      if (month == '13') {
        month = 1;
        year = year + 1;

      }

      this.userService.getGadgetsData(this.calendarInfo.id, "Calendar", month, year).subscribe(gadgetsData => {

         this.newEvents = gadgetsData.Data.Issues.map(function (o) {
          return o.Values.reduce(function (acc, _ref) {
            var Key = _ref.Key,
              Value = _ref.Value;
            return acc[Key] = Value, acc;
          }, {});
        });

        this.newEventsInfo = JSON.parse(JSON.stringify(this.newEvents).split(this.eventField).join('eventDate'));

        this.calendarEvents = this.newEventsInfo.map(({ Key, Summary, eventDate, Created }) =>
          ({ title: Key + ': ' + Summary, start: eventDate, id: Key, tooltip: Summary }));

        this.eventsData = this.calendarEvents.map(function (o) {

          o.start = moment.utc(o.start).format('YYYY-MM-DD');
          return o;

        });

         this.events = this.eventsData; // here is the code which replaces event list

      });
    }

  }
</code>```

Replacing the events list triggers another onViewRender event, causing infinite loop.

答: I just downgraded ngprime from 2.0.3 to 2.0.0 and now it works fine. no more api calls.</p>

Body:
I am using onViewRender to load events for my full calendar in an angular2 application.  using onViewRender is making multiple api calls to fetch events. can I use anything else than onViewRender in my template to load events. below is the problem im facing .

Put a
 on your template. Add a method such as this to your component:

testMethod(e)
{
console.log(e);
}

You'll see that the method is called infinitely.

and below is my actual code

component.html

component.ts

 loadEvents(e) {

    if (this) {
      let month = e.view.start._d.getMonth() + 2;
      let year = e.view.start._d.getFullYear();

      if (month == '13') {
        month = 1;
        year = year + 1;

      }

      this.userService.getGadgetsData(this.calendarInfo.id, "Calendar", month, year).subscribe(gadgetsData => {

         this.newEvents = gadgetsData.Data.Issues.map(function (o) {
          return o.Values.reduce(function (acc, _ref) {
            var Key = _ref.Key,
              Value = _ref.Value;
            return acc[Key] = Value, acc;
          }, {});
        });

        this.newEventsInfo = JSON.parse(JSON.stringify(this.newEvents).split(this.eventField).join('eventDate'));

        this.calendarEvents = this.newEventsInfo.map(({ Key, Summary, eventDate, Created }) =>
          ({ title: Key + ': ' + Summary, start: eventDate, id: Key, tooltip: Summary }));

        this.eventsData = this.calendarEvents.map(function (o) {

          o.start = moment.utc(o.start).format('YYYY-MM-DD');
          return o;

        });

         this.events = this.eventsData; // here is the code which replaces event list

      });
    }

  }

Replacing the events list triggers another onViewRender event, causing infinite loop.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答: The halting problem only shows that there are programs that cannot be verified.  A much more interesting and more practical question is what class of programs can be formally verified.  Maybe every program anyone cares about could (in theory) be verified.  In practice, so far, only very small programs have been proven correct.

Title: Why can't programs be proven?

OwnerDisplayName: John D. Cook


问:
Migrating a project in asp.net to drupal
I am tryin to rebuild a website designed in asp.net.But,being an informative site it has a lot of content in it which i dnt want to input to the database manually.

can ne1 help me out with any drupal module to migrate the asp.net data in sql server to mysql db in form of drupal architecture??

say for example a page in asp.net is displaying data from a form.Can i migrate it in form of cck and get the page data as nodes table.

答:
The comparison table of all available solutions is useful, but I would strongly recommend the Migrate module for this. It should work with MS SQL source data (I've only used it with MySQL and Postgres source databases), and is quite flexible in regards to mapping the source data to the Drupal schema. For Drupal 6, it supports most CCK field types (including images and files), and for Drupal 7 it supports the new Field API quite nicely.

The approach that the module takes, allows you to do continuous migrations such that if your source ASP site is still adding or changing content, it will keep track of what has been migrated, and even allows updating of previously migrated content.


问:
Check if user has phone number in CNContactStore and present error popover
I am writing a program that allows the user to pick contacts using the CNContactPickerViewController. If the selected contact does NOT have an associated phone number, I want to have it popover with an error and return to the ContactPickerViewController when they hit ok. I have gone through the code with breakpoints and it is executing correctly, however it is not presenting the error pop up.

I can't for the life of me figure out why...here is my code:

```<code> func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

    if contact.phoneNumbers.first?.value.stringValue != nil{
        //@TODO: check for repeats in people array

        // do something with contact
        let newPerson = Person(firstName: contact.givenName,
                               lastName: contact.familyName,
                               profileImage: #imageLiteral(resourceName: "capitalizing_on_the_economic_potential_of_foreign_entrepreneurs_feature.png") )

        if contact.imageDataAvailable == true{
            newPerson.profileImage = UIImage(data: contact.imageData!)!
        }

        // this is for the full name
        let fullname = "\(contact.givenName) \(contact.familyName)"
        print("The selected name is: \(fullname)")
        let phoneNum = contact.phoneNumbers.first?.value.stringValue
        print("The selected phone num is: \(phoneNum!)")

        //appends data to new activity model for prep to send back to home vc
        newActivity.people.append(newPerson)
        print("the people in the new activity array are: \(newActivity.people)")

        peopleCollection.reloadData()

    } else {
        print("error has no number")
        let alertController = UIAlertController(title: "Error: Person has no number!", message: "", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "Ok", style: .default, handler: {
            alert -> Void in
        })
        //add actions to alert sheet
        alertController.addAction(confirmAction)
        self.present(alertController, animated: true, completion: nil)
        //the code executes here correctly, but it does not present the alertController
    }
    //this is for phone number without dashes
    //print("the selected phone number is: \((contact.phoneNumbers[0].value ).value(forKey: "digits") as! String)")
}
</code>```

答:
Why don't you limit the user to pick only phone numbers? you can even hide all the other fields, so they will either see phone numbers, or nothing in the case that the contact do not have one (which will cause them to go to a different contact...)
Check the answer here, it also mentions the filtering to phone numbers only:
Contact Address book crash on iOS 10 beta
In this case, the didSelect function will be called only when a phone number is selected.</p>

Body:
I am writing a program that allows the user to pick contacts using the CNContactPickerViewController. If the selected contact does NOT have an associated phone number, I want to have it popover with an error and return to the ContactPickerViewController when they hit ok. I have gone through the code with breakpoints and it is executing correctly, however it is not presenting the error pop up.

I can't for the life of me figure out why...here is my code:

 func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

    if contact.phoneNumbers.first?.value.stringValue != nil{
        //@TODO: check for repeats in people array

        // do something with contact
        let newPerson = Person(firstName: contact.givenName,
                               lastName: contact.familyName,
                               profileImage: #imageLiteral(resourceName: "capitalizing_on_the_economic_potential_of_foreign_entrepreneurs_feature.png") )

        if contact.imageDataAvailable == true{
            newPerson.profileImage = UIImage(data: contact.imageData!)!
        }

        // this is for the full name
        let fullname = "\(contact.givenName) \(contact.familyName)"
        print("The selected name is: \(fullname)")
        let phoneNum = contact.phoneNumbers.first?.value.stringValue
        print("The selected phone num is: \(phoneNum!)")

        //appends data to new activity model for prep to send back to home vc
        newActivity.people.append(newPerson)
        print("the people in the new activity array are: \(newActivity.people)")

        peopleCollection.reloadData()

    } else {
        print("error has no number")
        let alertController = UIAlertController(title: "Error: Person has no number!", message: "", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "Ok", style: .default, handler: {
            alert -> Void in
        })
        //add actions to alert sheet
        alertController.addAction(confirmAction)
        self.present(alertController, animated: true, completion: nil)
        //the code executes here correctly, but it does not present the alertController
    }
    //this is for phone number without dashes
    //print("the selected phone number is: \((contact.phoneNumbers[0].value ).value(forKey: "digits") as! String)")
}


问:
How to Check whether a element exists in a python dictionary value which is a list?
How to check whether '111' exists in dic1?

```<code>dic1 = {'images':[000,111,222,333,444],'name':['foo','bar','baz']}
</code>```

I tried using List comprehensions but unable to get the boolean answer? I got the error 'int' object is not iterable.

答:
You can iterate over dict.values and check for existence:

```<code>dic1 = {'images':[000,111,222,333,444],'name':['foo','bar','baz']}
print(any(111 in b for b in dic1.values()))
</code>```

Output:

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

Body:
How to check whether '111' exists in dic1?

dic1 = {'images':[000,111,222,333,444],'name':['foo','bar','baz']}

I tried using List comprehensions but unable to get the boolean answer? I got the error 'int' object is not iterable.

Body:
You can iterate over dict.values and check for existence:

dic1 = {'images':[000,111,222,333,444],'name':['foo','bar','baz']}
print(any(111 in b for b in dic1.values()))

Output:

True


问:
How do I print out the results of my delete script in Powershell
I'm trying to find a way to get my script to print out a log file of what files are actually being deleted. Does anyone know how I could go about doing this? Here is my screen I would like to add that onto.</p>

```<code>Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    Remove-Item -Force
</code>```

答:
Unfortunately, the Remove-Item cmdlet doesn't support the -Passthru parameter, which might make this easier.  However, you could do this:

```<code>Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
Tee-Object -FilePath .\Log.txt |
Remove-Item -Force
</code>```

But that's a bit ugly because it outputs the directory listing from Get-ChildItem.  You could do this instead to capture just the paths:

```<code>Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
Select-Object -ExpandProperty FullName |
Tee-Object -FilePath .\Log.txt |
Remove-Item -Force
</code>```

Also, note that if you're using PowerShell v3.0 or later, the Get-ChildItem cmdlet supports the -File and -Directory parameters, so you don't need to do the whole -not $_.PsIsContainer stuff.

Body:
I'm trying to find a way to get my script to print out a log file of what files are actually being deleted. Does anyone know how I could go about doing this? Here is my screen I would like to add that onto.

Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    Remove-Item -Force

Body:
Unfortunately, the Remove-Item cmdlet doesn't support the -Passthru parameter, which might make this easier.  However, you could do this:

Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
Tee-Object -FilePath .\Log.txt |
Remove-Item -Force

But that's a bit ugly because it outputs the directory listing from Get-ChildItem.  You could do this instead to capture just the paths:

Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
Select-Object -ExpandProperty FullName |
Tee-Object -FilePath .\Log.txt |
Remove-Item -Force

Also, note that if you're using PowerShell v3.0 or later, the Get-ChildItem cmdlet supports the -File and -Directory parameters, so you don't need to do the whole -not $_.PsIsContainer stuff.


问:
create_Task(): The application called an interface that was marshalled for a different thread
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

```<code>auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });
</code>```

The postOptimation routine includes the line:

```<code>backwordCheckBox->IsChecked = params->backwards;
</code>```

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks

答:
This code will ensure the operation gets executed on the UI thread that is associated with your 'backwordCheckBox' control:</p>

```<code>backwordCheckBox->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
    ref new Windows::UI::Core::DispatchedHandler ([this, params]
{
    backwordCheckBox->IsChecked = params->backwards;
}));
</code>```

Body:
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });

The postOptimation routine includes the line:

backwordCheckBox->IsChecked = params->backwards;

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks

Body:
This code will ensure the operation gets executed on the UI thread that is associated with your 'backwordCheckBox' control:

backwordCheckBox->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
    ref new Windows::UI::Core::DispatchedHandler ([this, params]
{
    backwordCheckBox->IsChecked = params->backwards;
}));


问:
shell script to use cl1p.net online clipboard in linux - Error (23) Failed writing body
I am searching for a simple solution to send stdout (or a file content) from a linux host (raspi with bash) to my PC. The RaspberryPI has network/internet connection, but for security reasons it's not an option to set up SMB / FTP server on the raspi. It is anoying to send to an external FTP server all the time, using command line.

Please discuss general approaches (shell scripts for web form uploads, alternative options), and comment in particular on the scripting approach

I meanwhile tried to write a shell script...

```<code>#!/bin/bash
a='content='
b=`cat $2`
content=$a$b
curl -i -X POST https://cl1p.net/$1 -H "Content-Type: application/x-www-form-urlencoded" --data-binary "content=$content"
</code>```

the script, as you see, should accept 2 command line args:

```<code>$1 ... clipboard "unique name"
$2 ... file to be sent to the clipboard)
</code>```

When calling the script with the command line

```<code>$ ./sh ./bclip.sh 20171207testXX ./test.log
</code>```

I expected to be able to download the content here:
https://cl1p.net/20171207testXX

but when starting the script it says
    : not found.sh: 2: /boot/bclip.sh
    [... then the CURL upload output, and]
    (23) Failed writing body

What am I doing wrong?

答:
Where'd you get the call to ./sh from? As the error says, there's no sh binary/script in your current location.You probably added that because you couldn't run your script directly?

Just remove the ./sh from the start and instead set the script as executable with chmod +x bclip.sh and call it with simply ./blicp.sh foo bar.log.

Copy the script to a location in you PATH env var (something like /usr/local/bin or ~/bin usually works) and you can call it without the path prefix ./

Body:
I am searching for a simple solution to send stdout (or a file content) from a linux host (raspi with bash) to my PC. The RaspberryPI has network/internet connection, but for security reasons it's not an option to set up SMB / FTP server on the raspi. It is anoying to send to an external FTP server all the time, using command line.

Please discuss general approaches (shell scripts for web form uploads, alternative options), and comment in particular on the scripting approach

I meanwhile tried to write a shell script...

#!/bin/bash
a='content='
b=`cat $2`
content=$a$b
curl -i -X POST https://cl1p.net/$1 -H "Content-Type: application/x-www-form-urlencoded" --data-binary "content=$content"

the script, as you see, should accept 2 command line args:

$1 ... clipboard "unique name"
$2 ... file to be sent to the clipboard)

When calling the script with the command line

$ ./sh ./bclip.sh 20171207testXX ./test.log

I expected to be able to download the content here:
https://cl1p.net/20171207testXX

but when starting the script it says
    : not found.sh: 2: /boot/bclip.sh
    [... then the CURL upload output, and]
    (23) Failed writing body

What am I doing wrong?


问:
Can I run a custom action in a Windows Installer Project before the files are installed?
I have a Windows Installer Project that installs files to C:\Program Files\MyInstalledFiles. When I run the MSI, I want it to check if there is already a folder called MyInstalledFiles in the install destination and, if so, rename it to MyInstalledFiles-OLD. This way I can back up any files that already exist.

The catch is that I want this to be done BEFORE the files are installed by the MSI. Otherwise, it will overwrite the existing files and I will lose them. Is there any way for me to rename the folder before the installation using custom actions?

答:
Your question has a Visual Studio tag, and that might mean you are using a Visual Studio setup project to create your MSI setup. If you are using a VS setup project then the answer is no, you cannot run a custom action before the files are installed. All custom actions generated by Visual Studio installer projects run after the files are installed, despite names such as "BeforeInstall".

Other tools allow custom actions to be run before files are installed, and basically you'd have a deferred custom action sequenced before the InstallFiles action.

Whether existing files will be overwritten is by no means certain. If you had a Windows Installer based setup that installed a database that was then updated by the application an upgrade like Visual Studio's RemovePreviousVersions will not overwrite the existing files.

https://msdn.microsoft.com/en-us/library/windows/desktop/aa370531(v=vs.85).aspx


问:
Using For loop in Pandas with groupby function
unGrouped is a dataframe that looks like this:

```<code>         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN
</code>```

I have the following code:

```<code>for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount
</code>```

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

答:
Use values_counts:

```<code>bronxCount = unGrouped.borough.value_counts()['BRONX']
print(BronxCount)
</code>```

Output:

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

Body:
unGrouped is a dataframe that looks like this:

         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN

I have the following code:

for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

Body:
Use values_counts:

bronxCount = unGrouped.borough.value_counts()['BRONX']
print(BronxCount)

Output:

2


问:
Use golb patterns stored in a file for searching - bash
How can I use glob patterns that are stored in a textfile as an input for a filesearch?

I want to search all subdirectories for files that are matching global patterns which are stored in a textfile.
The file with global patterns looks like:

```<code>/Dongle/src/*.c
/App/files/**/*.xml
...
</code>```

Who can I use that file as an input for the find command in bash?

What I tried so far is:

```<code>modelFile=$1

root="Project/"
regexes=$(cat $modelFile)
outFile="out.txt"

for re in $regexes; do
    find $root -type f -regex $re > $outFile
done
</code>```

But it does not match any files. It works if I use it like:

```<code>(...)
for re in $regexes; do
    find $root -type f -regex "/App/files/**/*.xml" > $outFile
done
for re in $regexes; do
    find $root -type f -regex "/Dongle/src/*.c " >> $outFile
done
</code>```

I don't necessarily have to use find. Every other bash command would work as well.

The output should be every file that matches the glob patterns.

答:
These are not regexes, these are glob patterns.

Furthermore, find would not be very effective to find the matches, since the patterns themselves should be resolvable by the shell directly,
if your shell supports the globstar and nullglob extensions.

```<code>shopt -s globstar nullglob

while read glob; do
    for path in $glob; do
        echo "$path"
    done
done < "$modelFile" > "$outFile"
</code>```

Some other important issues with your original code:

Redirection with > in a loop to the same file would overwrite the file on every iteration

Always enclose in double quotes variables used as command line arguments

Process line by line input using a while loop instead of a for loop

Body:
How can I use glob patterns that are stored in a textfile as an input for a filesearch?

I want to search all subdirectories for files that are matching global patterns which are stored in a textfile.
The file with global patterns looks like:

/Dongle/src/*.c
/App/files/**/*.xml
...

Who can I use that file as an input for the find command in bash?

What I tried so far is:

modelFile=$1

root="Project/"
regexes=$(cat $modelFile)
outFile="out.txt"

for re in $regexes; do
    find $root -type f -regex $re > $outFile
done

But it does not match any files. It works if I use it like:

(...)
for re in $regexes; do
    find $root -type f -regex "/App/files/**/*.xml" > $outFile
done
for re in $regexes; do
    find $root -type f -regex "/Dongle/src/*.c " >> $outFile
done

I don't necessarily have to use find. Every other bash command would work as well.

The output should be every file that matches the glob patterns.

Body:
These are not regexes, these are glob patterns.

Furthermore, find would not be very effective to find the matches, since the patterns themselves should be resolvable by the shell directly,
if your shell supports the globstar and nullglob extensions.

shopt -s globstar nullglob

while read glob; do
    for path in $glob; do
        echo "$path"
    done
done < "$modelFile" > "$outFile"

Some other important issues with your original code:

Redirection with > in a loop to the same file would overwrite the file on every iteration

Always enclose in double quotes variables used as command line arguments

Process line by line input using a while loop instead of a for loop


问:
How to read and share and process simultaneously data from parallel processes in Python 2?
Here is my issue.
I am working on a system that acquires data from three different devices (each time, I would like to launch a process that executes a "read_data" loop).

From the three data recorded in realtime, I would like to add a loop on top of that , that would perform an action regarding these data.

Ex (with an obviously really bad semantic, but that's for understanding the idea):

```<code>Class Sensor1:
read_s1():
 data_s1 = ...
Class Sensor2:
read_s2():
 data_s2 = ...
Class Sensor3:
read_s3():
 data_s3 = ...

main:
read_s1.start()
read_s2.start()
read_s3.start()

while True: #processing and acting regarding realtime data from the three sensors
   if read_s1.data_s1/read_s2.data_s2 + read_s3.data_s3 == 2:
               #do something
</code>```

I tried to use threading and multiprocess, but I could not manage to launch the three threads that read and save in a variable the incoming data, then accessing when I want from an external loop to these data.

答:
I'm going to try to be more specific:

I have precisely :

```<code>thread_1:
   while not e.isSet():
         data1 = read_data1()
thread_2:
   while not e.isSet():
         data2 = read_data2()
thread_3:
   while not e.isSet():
         data3 = read_data3()

if __name__ == 'main':
      thread_1.start()
      thread_2.start()
      thread_3.start()
      while not e.isSet():
            if data1 = 2 and data2 = 3 and data3=4:
                     #do something
</code>```

How am I suppose to use the Lock?
Each thread has a different execution time by iteration as the reading of the data has a different time for each sensor.
Thank you very much!

Body:
Here is my issue.
I am working on a system that acquires data from three different devices (each time, I would like to launch a process that executes a "read_data" loop).

From the three data recorded in realtime, I would like to add a loop on top of that , that would perform an action regarding these data.

Ex (with an obviously really bad semantic, but that's for understanding the idea):

Class Sensor1:
read_s1():
 data_s1 = ...
Class Sensor2:
read_s2():
 data_s2 = ...
Class Sensor3:
read_s3():
 data_s3 = ...

main:
read_s1.start()
read_s2.start()
read_s3.start()

while True: #processing and acting regarding realtime data from the three sensors
   if read_s1.data_s1/read_s2.data_s2 + read_s3.data_s3 == 2:
               #do something

I tried to use threading and multiprocess, but I could not manage to launch the three threads that read and save in a variable the incoming data, then accessing when I want from an external loop to these data.

Body:
I'm going to try to be more specific:

I have precisely :

thread_1:
   while not e.isSet():
         data1 = read_data1()
thread_2:
   while not e.isSet():
         data2 = read_data2()
thread_3:
   while not e.isSet():
         data3 = read_data3()

if __name__ == 'main':
      thread_1.start()
      thread_2.start()
      thread_3.start()
      while not e.isSet():
            if data1 = 2 and data2 = 3 and data3=4:
                     #do something

How am I suppose to use the Lock?
Each thread has a different execution time by iteration as the reading of the data has a different time for each sensor.
Thank you very much!


问:
What is the best practices of making a repository class with EF4 code first?
There seem to be many ways to apply the repository patterns that is why i need your opinion and a good clear answer on what seem the best way of applying the repository pattern. It is the generic repository ? But there is a problem where some domain object dont have the same behaviour as others. It is specify repository ? What about code repeatition between repositories? it is both combinaison ? how about using a di container for both kind of implementation ?

Thanks

Edit: the orm i am using is entity framework 4. Would be nice to have an example with EF4.

答:
The Repository pattern itself is pretty explicit in those areas that require specification. The rest is left out on purpose, because it depends on my outside factors, such as your programming language, project scope and your personal programming style.

In other words: You seem to be asking for a pattern on how to apply the pattern, but in the end you will have to take your own decisions when programming.

I will try to reply to your more specific questions though:

Yes, using Generics is a good idea for a repository. Another approach would be to have a common interface for all objects that should be stored. You might also go with both, depending on your requirements.

Try to deal with differences in object behaviour by calling polymorphic methods on the objects to be stored.

There should be no code repetition if you do it right (by using generics and / or interfaces).


问:
Emgu CV - Combining greyscale images into single Bgr image
I'm trying to convert a greyscale image to a Hsv image, but with the S and V channels set to a preset value. The following code works but takes ~400ms to execute.

```<code>public void ToHueImage(this Image<Gray, double> image, Image<Hsv, double> output)
{
        for (int i = 0; i < image.Width; i++)
        {
            for (int j = 0; j < image.Height; j++)
            {
                output.Data[j, i, 0] = image.Data[j, i, 0];
                output.Data[j, i, 1] = 255;
                output.Data[j, i, 2] = 255;
            }
        }
    }
}
</code>```

I would like to be able to assign a single greyscale image channel to each of the H, S, and V planes in a single operation to avoid copying the pixels across individually, something along the lines of

```<code>public void ToHueImage(this Image<Gray, double> image, Image<Hsv, double>     output)
{
    output.Data.H = image;
    output.Data.S = WHITE_IMAGE; // These are static
    output.Data.V = WHITE_IMAGE; // These are static
}
</code>```

without resorting to byte copying etc. I'm trying to get the execution time to ~30ms or so. Is there any straightforward way to accomplish this?

答:
Sorted thanks to Miki: just need to call opencv function merge using CVInvoke:</p>

```<code>CvInvoke.Merge(new VectorOfMat(image.Mat, whiteImage.Mat, whiteImage.Mat), heatMap.Mat);
</code>```

Body:
I'm trying to convert a greyscale image to a Hsv image, but with the S and V channels set to a preset value. The following code works but takes ~400ms to execute.

public void ToHueImage(this Image<Gray, double> image, Image<Hsv, double> output)
{
        for (int i = 0; i < image.Width; i++)
        {
            for (int j = 0; j < image.Height; j++)
            {
                output.Data[j, i, 0] = image.Data[j, i, 0];
                output.Data[j, i, 1] = 255;
                output.Data[j, i, 2] = 255;
            }
        }
    }
}

I would like to be able to assign a single greyscale image channel to each of the H, S, and V planes in a single operation to avoid copying the pixels across individually, something along the lines of

public void ToHueImage(this Image<Gray, double> image, Image<Hsv, double>     output)
{
    output.Data.H = image;
    output.Data.S = WHITE_IMAGE; // These are static
    output.Data.V = WHITE_IMAGE; // These are static
}

without resorting to byte copying etc. I'm trying to get the execution time to ~30ms or so. Is there any straightforward way to accomplish this?

Body:
Sorted thanks to Miki: just need to call opencv function merge using CVInvoke:

CvInvoke.Merge(new VectorOfMat(image.Mat, whiteImage.Mat, whiteImage.Mat), heatMap.Mat);


问:
Page breaks in html don't appear when embedded in a docx file with docx4j
I'm outputting a Word (docx) file using docx4j, and the page breaks aren't appearing in the document.
I'm using:

```<code>hr {page-break-after: always}
</code>```

for the css, but it isn't rendering as a page break in the Word document.

What html or css should I be using to get an html page break to transfer over to the docx file?

答:
Works with heading tags or paragraph tags (h1, h2, p):

I used this css style with h1 tags in my html content and  successfully got the page-breaks applying after the heading in my exported word document:

```<code>String pageBreakMarker = "<h1 style=\"page-break-after: always;\"></h1>";
</code>```

I think this is not working with html break tags has to do with how docx4j treats html break tags.

Even looking at the getting started sample on github, I only see the 'page-break-after' or 'page-break-before' being used with only html paragraph tags (p)

See link to Docx4j getting started guide on github below:

Docx4j Getting Started

Does not work with html break tags:

Using docx4, I can confirm I the "page-break-after" or "page-break-before" does not work when trying to create page breaks in word docs from  html content with break tags (hr):

```<code><br style=\"page-break-after: always; clear:both;\"></br>
</code>```

Body:
I'm outputting a Word (docx) file using docx4j, and the page breaks aren't appearing in the document.
I'm using:

hr {page-break-after: always}

for the css, but it isn't rendering as a page break in the Word document.

What html or css should I be using to get an html page break to transfer over to the docx file?

Body:
Works with heading tags or paragraph tags (h1, h2, p):

I used this css style with h1 tags in my html content and  successfully got the page-breaks applying after the heading in my exported word document:

String pageBreakMarker = "<h1 style=\"page-break-after: always;\"></h1>";

I think this is not working with html break tags has to do with how docx4j treats html break tags.

Even looking at the getting started sample on github, I only see the 'page-break-after' or 'page-break-before' being used with only html paragraph tags (p)

See link to Docx4j getting started guide on github below:

Docx4j Getting Started

Does not work with html break tags:

Using docx4, I can confirm I the "page-break-after" or "page-break-before" does not work when trying to create page breaks in word docs from  html content with break tags (hr):

<br style=\"page-break-after: always; clear:both;\"></br>


问:
How to concatenate text from multiple rows into a single text string in SQL Server
Consider a database table holding names, with three rows:

```<code>Peter
Paul
Mary
</code>```

Is there an easy way to turn this into a single string of Peter, Paul, Mary?

答:
Although it's too late, and already has many solutions. Here is simple solution for MySQL:</p>

```<code>SELECT t1.id,
        GROUP_CONCAT(t1.id) ids
 FROM table t1 JOIN table t2 ON (t1.id = t2.id)
 GROUP BY t1.id
</code>```

OwnerDisplayName: John

Body:
Consider a database table holding names, with three rows:

Peter
Paul
Mary

Is there an easy way to turn this into a single string of Peter, Paul, Mary?

LastEditorDisplayName: Dana

Body:
Although it's too late, and already has many solutions. Here is simple solution for MySQL:

SELECT t1.id,
        GROUP_CONCAT(t1.id) ids
 FROM table t1 JOIN table t2 ON (t1.id = t2.id)
 GROUP BY t1.id


问:
how to use Google Cloud Memcach to save/update unique items
In my application I run a cron job to loop over all users (2500 user) to choose an item for every user out of 4k items, considering that:
- choosing the item is based on some user info,
- I need to make sure that each user take a unique item that wasn't taken by any one else, so relation is one-to-one

To achieve this I have to run this cron job and loop over the users one by one sequentially and pick up the item for each then remove it from the list (not to be chosen by next user(s)) then move to the next user

actually in my system the number of users/items is getting bigger and bigger every single day, this cron job now takes 2 hours to set items to all users.

I need to improve this, one of the things I've thought about is using Threads but I cant do that since Im using automatic scaling, so I start thinking about push Queues, so when the cron jobs run, will make a loop like this:

```<code>for(User user : users){
    getMyItem(user.getId());
}
</code>```

where getMyItem will push the task to a servlet to handle it and choose the best item for this person based on his data.

Let's say I'll start doing that so what will be the best/robust solution to avoid setting an item to more than one user ?

Since Im using basic scaling and 8 instances, can't rely on static variables.
one of the things that came across my mind is to create a table in the DB that accept only unique items then I insert into it the taken items so if the insertion is done successfully it means no body else took this item so i can just assign it to that person, but this will make the performance a bit lower cause I need to make write DB operation with every call (I want to avoid that)

Also I thought about MemCach, its really fast but not robust enough, if I save a Set of items into it which will accept only unique items, then if more than one thread was trying to access this Set at the same time to update it, only one thread will be able to save its data and all other threads data might be overwritten and lost.

I hope you guys can help to find a solution for this problem, thanks in advance :)

答:
First - I would advice against using solely memcache for such algorithm - the key thing to remember about memcache is that it is volatile and might dissapear at any time, breaking the algorithm.

From Service levels:

Note: Whether shared or dedicated, memcache is not durable storage. Keys can be evicted when the cache fills up, according to the
  cache's LRU policy. Changes in the cache configuration or datacenter
  maintenance events can also flush some or all of the cache.

And from How cached data expires:

Under rare circumstances, values can also disappear from the cache
  prior to expiration for reasons other than memory pressure. While
  memcache is resilient to server failures, memcache values are not
  saved to disk, so a service failure can cause values to become
  unavailable.

I'd suggest adding a property, let's say called assigned, to the item entities, by default unset (or set to null/None) and, when it's assigned to a user, set to the user's key or key ID. This allows you:

to query for unassigned items when you want to make assignments

to skip items recently assigned but still showing up in the query results due to eventual consistency, so no need to struggle for consistency

to be certain that an item can uniquely be assigned to only a single user

to easily find items assigned to a certain user if/when you're doing per-user processing of items, eventually setting the assigned property to a known value signifying done when its processing completes

Note: you may need a one-time migration task to update this assigned property for any existing entities when you first deploy the solution, to have these entities included in the query index, otherwise they would not show up in the query results.

As for the growing execution time of the cron jobs: just split the work into multiple fixed-size batches (as many as needed) to be performed in separate requests, typically push tasks. The usual approach for splitting is using query cursors. The cron job would only trigger enqueueing the initial batch processing task, which would then enqueue an additional such task if there are remaining batches for processing.

To get a general idea of such a solution works take a peek at Google appengine: Task queue performance (it's python, but the general idea is the same).

Body:
In my application I run a cron job to loop over all users (2500 user) to choose an item for every user out of 4k items, considering that:
- choosing the item is based on some user info,
- I need to make sure that each user take a unique item that wasn't taken by any one else, so relation is one-to-one

To achieve this I have to run this cron job and loop over the users one by one sequentially and pick up the item for each then remove it from the list (not to be chosen by next user(s)) then move to the next user

actually in my system the number of users/items is getting bigger and bigger every single day, this cron job now takes 2 hours to set items to all users.

I need to improve this, one of the things I've thought about is using Threads but I cant do that since Im using automatic scaling, so I start thinking about push Queues, so when the cron jobs run, will make a loop like this:

for(User user : users){
    getMyItem(user.getId());
}

where getMyItem will push the task to a servlet to handle it and choose the best item for this person based on his data.

Let's say I'll start doing that so what will be the best/robust solution to avoid setting an item to more than one user ?

Since Im using basic scaling and 8 instances, can't rely on static variables.
one of the things that came across my mind is to create a table in the DB that accept only unique items then I insert into it the taken items so if the insertion is done successfully it means no body else took this item so i can just assign it to that person, but this will make the performance a bit lower cause I need to make write DB operation with every call (I want to avoid that)

Also I thought about MemCach, its really fast but not robust enough, if I save a Set of items into it which will accept only unique items, then if more than one thread was trying to access this Set at the same time to update it, only one thread will be able to save its data and all other threads data might be overwritten and lost.

I hope you guys can help to find a solution for this problem, thanks in advance :)