问:
Mysql -- Need something like UPDATE [...] ON DUPLICATE KEY [...]
I'm validating the e-mails of several databases.
Our validation provider created us a list of e-mails with a status to put (checked, non-responding, and so on...)

But for some adresses, we also got a fix (e.g.  foo@gail.com => foo@gmail.com)

I need to put the right status (20), and only sometimes fix the e-mail.  I also could have to fix the mail while the status is already right.

My current PDO request to update those is as follows :

```<code>$req_fix_mail_and_update_status = "
    UPDATE {$user_table_name}
        SET status = :mail_status1
        , {$mail_column_name} = :mail_fixed1
    WHERE (({$mail_column_name} LIKE :mail_address)  OR  ({$mail_column_name} LIKE :mail_fixed2))
        AND ((status != :mail_status2) OR ({$mail_column_name} NOT LIKE :mail_fixed3))
";
</code>```

Now, here comes the tricky part :

One of the databases stores data about several websites, and may contain mail duplicates.

I got a composed unique constraint on something like (fk_site, email)

... and an edge case, with some e-mails having both "fixed" and "non-fixed" values entries

e.g. :

```<code>Login   FK_Site  Mail            Status
Alice        01  foo@gmail.com        0
Alice        01  foo@gmal.com         0
Bob          02  foo@gmal.com         0
</code>```

Of course, trying to fix the wrong adress would makes duplicate invalid because of the (fk_site, email) unique constraint would fail on Alice => the requests fails (#$%§@&!).

But Bob stil needs his mail fixed, and the lines need their status updated, too !

I'm looking for a way to get around this, but can't find anything with SQL.
Making one (say, up to two) more requests when I fail could be ok, but it seems to be a slippy way, and I don't want to turn the task to something dirty and unreadable for such an edge cas

Typically, an UPDATE [...] with a "ON DUPLICATE KEY <just update status>" clause is what I'd need, but I wasn't surprise to see is doesn't exist.

My worker is written in PHP, and uses PDO

Any idea ?

答:
Ok, so here is the substitute "answer" to my problem.
Note that a more simple solution (if it exists...) would be welcome.

It technically solves my needs, but is pretty ugly and costs me 3 extra requests instead of one.

One to update the mail & status of lines having a wrong mail which wont create a duplicate once mail is fixed

One to update only the status of lines having an already correct e-mail

One to update only the status of lines having a mail which cant be fixed due to the constraint

This is a bit heavy, but performance isn't an issue here.  What bugs me is that it makes the code less readable, and a detailed explanation is needed to understand WHY 3 requests are necessary.

Here's my (PDO) request to update only lines which wouldn't create a duplicate :

```<code>UPDATE prospect p1
    SET email = :mail_fixed1
    ,status = :mail_status1
WHERE
    p1.email = :mail_address
    AND NOT EXISTS (
        SELECT site_id FROM (SELECT site_id, email, origin  FROM  prospect cpy) as p2
        WHERE
            email = :mail_fixed2
            AND p1.site_id = p2.site_id
            AND p1.origin = p2.origin
        )
</code>```

The unicity constraint is on the triplet (site_id, email, origin)

Placeholders like :mail_fixed1 and :mail_fixed2 have the same values bound.  The reason why I have to use different ones is because my script also connects to a SQL-Server database, and the driver crashes with an unintelligible error when a placeholder is used more than once.

My 3nd request, which only updates lines for which the mail fix WOULD create a duplicate is the same, except "NOT EXISTS" is replaced with "EXISTS" (also, the mail isn't modified, and the status is fixed, but those are details)

The 2rd request in-between has nothing particular, but I put it here for completeness sake :

```<code>UPDATE {$user_table_name}
    SET status = :mail_status1
WHERE ({$mail_column_name} LIKE :mail_address)
    AND ((status IS NULL)  OR  (status != :mail_status2))
</code>```

I forgot to mention one other little drawback : my script used to count the precise number of updated lines, but it may now count a few lines more than once, since the same line can be updated by 2 requests.  It's a small detail, but remains annoying.

Anyway, I hope this post will help someone else !

Body:
I'm validating the e-mails of several databases.
Our validation provider created us a list of e-mails with a status to put (checked, non-responding, and so on...)

But for some adresses, we also got a fix (e.g.  foo@gail.com => foo@gmail.com)

I need to put the right status (20), and only sometimes fix the e-mail.  I also could have to fix the mail while the status is already right.

My current PDO request to update those is as follows :

$req_fix_mail_and_update_status = "
    UPDATE {$user_table_name}
        SET status = :mail_status1
        , {$mail_column_name} = :mail_fixed1
    WHERE (({$mail_column_name} LIKE :mail_address)  OR  ({$mail_column_name} LIKE :mail_fixed2))
        AND ((status != :mail_status2) OR ({$mail_column_name} NOT LIKE :mail_fixed3))
";

Now, here comes the tricky part :

One of the databases stores data about several websites, and may contain mail duplicates.

I got a composed unique constraint on something like (fk_site, email)

... and an edge case, with some e-mails having both "fixed" and "non-fixed" values entries

e.g. :

Login   FK_Site  Mail            Status
Alice        01  foo@gmail.com        0
Alice        01  foo@gmal.com         0
Bob          02  foo@gmal.com         0

Of course, trying to fix the wrong adress would makes duplicate invalid because of the (fk_site, email) unique constraint would fail on Alice => the requests fails (#$%§@&!).

But Bob stil needs his mail fixed, and the lines need their status updated, too !

I'm looking for a way to get around this, but can't find anything with SQL.
Making one (say, up to two) more requests when I fail could be ok, but it seems to be a slippy way, and I don't want to turn the task to something dirty and unreadable for such an edge cas

Typically, an UPDATE [...] with a "ON DUPLICATE KEY <just update status>" clause is what I'd need, but I wasn't surprise to see is doesn't exist.

My worker is written in PHP, and uses PDO

Any idea ?

Body:
Ok, so here is the substitute "answer" to my problem.
Note that a more simple solution (if it exists...) would be welcome.

It technically solves my needs, but is pretty ugly and costs me 3 extra requests instead of one.

One to update the mail & status of lines having a wrong mail which wont create a duplicate once mail is fixed

One to update only the status of lines having an already correct e-mail

One to update only the status of lines having a mail which cant be fixed due to the constraint

This is a bit heavy, but performance isn't an issue here.  What bugs me is that it makes the code less readable, and a detailed explanation is needed to understand WHY 3 requests are necessary.

Here's my (PDO) request to update only lines which wouldn't create a duplicate :

UPDATE prospect p1
    SET email = :mail_fixed1
    ,status = :mail_status1
WHERE
    p1.email = :mail_address
    AND NOT EXISTS (
        SELECT site_id FROM (SELECT site_id, email, origin  FROM  prospect cpy) as p2
        WHERE
            email = :mail_fixed2
            AND p1.site_id = p2.site_id
            AND p1.origin = p2.origin
        )

The unicity constraint is on the triplet (site_id, email, origin)

Placeholders like :mail_fixed1 and :mail_fixed2 have the same values bound.  The reason why I have to use different ones is because my script also connects to a SQL-Server database, and the driver crashes with an unintelligible error when a placeholder is used more than once.

My 3nd request, which only updates lines for which the mail fix WOULD create a duplicate is the same, except "NOT EXISTS" is replaced with "EXISTS" (also, the mail isn't modified, and the status is fixed, but those are details)

The 2rd request in-between has nothing particular, but I put it here for completeness sake :

UPDATE {$user_table_name}
    SET status = :mail_status1
WHERE ({$mail_column_name} LIKE :mail_address)
    AND ((status IS NULL)  OR  (status != :mail_status2))

I forgot to mention one other little drawback : my script used to count the precise number of updated lines, but it may now count a few lines more than once, since the same line can be updated by 2 requests.  It's a small detail, but remains annoying.

Anyway, I hope this post will help someone else !


来源: stackexchange

问:
read.csv and skip last column in R
I have read several other posts about how to import csv files with read.csv but skipping specific columns. However, all the examples I have found had very few columns, and so it was easy to do something like:

```<code> columnHeaders <- c("column1", "column2", "column_to_skip")
 columnClasses <- c("numeric", "numeric", "NULL")
 data <- read.csv(fileCSV, header = FALSE, sep = ",", col.names =
 columnHeaders, colClasses = columnClasses)
</code>```

I have 201 columns, without column labels. I would like to skip the last column. How would it be possible to do this without naming all the other columns to keep? Many thanks.

答:
Bit hacky but, I usually read in a small number of the rows of the dataset I want, then use sapply(..., class) to find the column types and set the last one to "NULL".

```<code>data<-read.table("test.csv", sep=',', nrows = 100)
colClasses<-sapply(data, class)
colClasses[length(colClasses)]<-"NULL"
</code>```

Then you can pass this colClasses to your read.csv() function

ContentLicense: CC BY-SA 3.0

Title: read.csv and skip last column in R

Body:
I have read several other posts about how to import csv files with read.csv but skipping specific columns. However, all the examples I have found had very few columns, and so it was easy to do something like:

 columnHeaders <- c("column1", "column2", "column_to_skip")
 columnClasses <- c("numeric", "numeric", "NULL")
 data <- read.csv(fileCSV, header = FALSE, sep = ",", col.names =
 columnHeaders, colClasses = columnClasses)

I have 201 columns, without column labels. I would like to skip the last column. How would it be possible to do this without naming all the other columns to keep? Many thanks.

Body:
Bit hacky but, I usually read in a small number of the rows of the dataset I want, then use sapply(..., class) to find the column types and set the last one to "NULL".

data<-read.table("test.csv", sep=',', nrows = 100)
colClasses<-sapply(data, class)
colClasses[length(colClasses)]<-"NULL"

Then you can pass this colClasses to your read.csv() function


问:
howto implement a class that evealuates contains in a list
I have:
- MyClass with hashCode() overwritten
- I'll try to avoid adding a second instance of MyClass with the same content to an List using the contains() method of the List.

How can I achive this ? I thought this is done by just overriding the hashCode() method ?

I guess code says more then words

```<code>public class TestClass {

    public static void main(String[] args){

        MyClass myclass1 = new MyClass(2);
        MyClass myclass2 = new MyClass(2);

        List<MyClass> myclasses = new ArrayList<MyClass>();
        myclasses.add(myclass1);
        if(!myclasses.contains(myclass2)){
            myclasses.add(myclass2);
            System.out.println("I'll add ...");
        }

        System.out.println(myclasses.size());
    }
}

public class MyClass {

    int id = -1;
    String something = "";

    public MyClass(int idparam){
        this.id = idparam;
    }

    @Override
    public int hashCode() {
        return id;
    }

}
</code>```

Updated Class:

```<code>public boolean equals(MyClass secondmyclass) {
    return secondmyclass.id == this.id;
}
</code>```

答:
You have to override equals and hashcode methods. The object is not contained in the list as is not equal to any instance in the list, even if it generates same hash code.

```<code>@Override
public boolean equals(Object obj) {
    boolean eq = false;
    if (obj != null && obj instanceof YOURCLASS) {
        eq = this.getId().equals((YOUCLASS)obj.getId());
    }
}
</code>```

Equals method should look like this. YOURCLASS is the name of the bean added to the list. You have to compare the key fields after verifying the obj instance is not null and is of the same type of the original instance.

In your example YOURCLASS is MyClass and the comparison inside equals should be with == instead of equals, as you are not using int insteand of Integer for the field.

Body:
I have:
- MyClass with hashCode() overwritten
- I'll try to avoid adding a second instance of MyClass with the same content to an List using the contains() method of the List.

How can I achive this ? I thought this is done by just overriding the hashCode() method ?

I guess code says more then words

public class TestClass {

    public static void main(String[] args){

        MyClass myclass1 = new MyClass(2);
        MyClass myclass2 = new MyClass(2);

        List<MyClass> myclasses = new ArrayList<MyClass>();
        myclasses.add(myclass1);
        if(!myclasses.contains(myclass2)){
            myclasses.add(myclass2);
            System.out.println("I'll add ...");
        }

        System.out.println(myclasses.size());
    }
}

public class MyClass {

    int id = -1;
    String something = "";

    public MyClass(int idparam){
        this.id = idparam;
    }

    @Override
    public int hashCode() {
        return id;
    }

}

Updated Class:

public boolean equals(MyClass secondmyclass) {
    return secondmyclass.id == this.id;
}

Body:
You have to override equals and hashcode methods. The object is not contained in the list as is not equal to any instance in the list, even if it generates same hash code.

@Override
public boolean equals(Object obj) {
    boolean eq = false;
    if (obj != null && obj instanceof YOURCLASS) {
        eq = this.getId().equals((YOUCLASS)obj.getId());
    }
}

Equals method should look like this. YOURCLASS is the name of the bean added to the list. You have to compare the key fields after verifying the obj instance is not null and is of the same type of the original instance.

In your example YOURCLASS is MyClass and the comparison inside equals should be with == instead of equals, as you are not using int insteand of Integer for the field.


问:
selecting a ng-select with jquery
The first control on my page needs to have input focus when the page initially loads, unfortunately, in my case, that control is an ng-select.

So, somewhere in my ang2 template:

```<code><ng-select id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>
</code>```

In my ngAfterViewInit, I have:

```<code>$("#mySelect > div").focus();
$("#mySelect > div").select();
</code>```

(Also tried dropping the div)

Alas, this is not working.

Note:
This is NOT a duplicate of "What is the easiest way to put a default focus on an element in AngularJS". That question is referring to an input control, so basic jquery focus/select works. This is specifically referring to an ng-select (which render as a bunch children div's).

答:
you could do it without jQuery:

@ViewChild('yourFieldReference') fieldRefName: ElementRef;

.
.
.
.

ngOnInit() {
 this.fieldRefName.nativeElement.focus();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input #yourFieldReference id="fieldID"></code>```

I've done it with input but you could do it with any HTML element tag

Title: selecting a ng-select with jquery

Body:
The first control on my page needs to have input focus when the page initially loads, unfortunately, in my case, that control is an ng-select.

So, somewhere in my ang2 template:

<ng-select id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>

In my ngAfterViewInit, I have:

$("#mySelect > div").focus();
$("#mySelect > div").select();

(Also tried dropping the div)

Alas, this is not working.

Note:
This is NOT a duplicate of "What is the easiest way to put a default focus on an element in AngularJS". That question is referring to an input control, so basic jquery focus/select works. This is specifically referring to an ng-select (which render as a bunch children div's).

Body:
you could do it without jQuery:

@ViewChild('yourFieldReference') fieldRefName: ElementRef;

.
.
.
.

ngOnInit() {
 this.fieldRefName.nativeElement.focus();
}

<input #yourFieldReference id="fieldID">

I've done it with input but you could do it with any HTML element tag


答:
You want to plot the values, plt.scatter(x_values.values, y_values.values). It would also make sense to sort the data, to get a smooth line.

```<code>import numpy as np
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

#read data
dataframe = pd.read_fwf('data/brainbody.txt')
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]

#train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)

#visualize results
plt.scatter(x_values.values, y_values.values)

x = np.sort(x_values.values.flatten())
plt.plot(x, body_reg.predict(x[:,np.newaxis]))

plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Title: wrong order in (matplotlib.pyplot) scatter plot axis

Body:
I'm following this linear regression example but my result differs from what should be. The problem is in the plot axis, they are not in order.

expected:

my result:

zoom to see the axis:

The Code:

import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

#read data
dataframe = pd.read_fwf('brain_body.txt')
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]

#train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)

#visualize results
plt.scatter(x_values, y_values)
plt.plot(x_values, body_reg.predict(x_values))
plt.show()

brain_body.txt

Brain        Body
    3.385    44.500
    0.480    15.500
    1.350     8.100
  465.000   423.000
   36.330   119.500
   27.660   115.000
   14.830    98.200
    1.040     5.500
    4.190    58.000
    0.425     6.400
    0.101     4.000
    0.920     5.700
    1.000     6.600
    0.005     0.140
    0.060     1.000
    3.500    10.800
    2.000    12.300
    1.700     6.300
 2547.000  4603.000
    0.023     0.300
  187.100   419.000
  521.000   655.000
    0.785     3.500
   10.000   115.000
    3.300    25.600
    0.200     5.000
    1.410    17.500
  529.000   680.000
  207.000   406.000
   85.000   325.000
    0.750    12.300
   62.000  1320.000
 6654.000  5712.000
    3.500     3.900
    6.800   179.000
   35.000    56.000
    4.050    17.000
    0.120     1.000
    0.023     0.400
    0.010     0.250
    1.400    12.500
  250.000   490.000
    2.500    12.100
   55.500   175.000
  100.000   157.000
   52.160   440.000
   10.550   179.500
    0.550     2.400
   60.000    81.000
    3.600    21.000
    4.288    39.200
    0.280     1.900
    0.075     1.200
    0.122     3.000
    0.048     0.330
  192.000   180.000
    3.000    25.000
  160.000   169.000
    0.900     2.600
    1.620    11.400
    0.104     2.500
    4.235    50.400

It is my first time in python and I think there is a problem with the installation of some module but I don't have a clue.

Body:
You want to plot the values, plt.scatter(x_values.values, y_values.values). It would also make sense to sort the data, to get a smooth line.

import numpy as np
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

#read data
dataframe = pd.read_fwf('data/brainbody.txt')
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]

#train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)

#visualize results
plt.scatter(x_values.values, y_values.values)

x = np.sort(x_values.values.flatten())
plt.plot(x, body_reg.predict(x[:,np.newaxis]))

plt.show()


问:
How to get Generic class<T> name of typescript?
My Generic class

```<code> export class BaseService<T> {
 public subUrl;
 constructor(public repo:RepogitoryService) { }
}
</code>```

How can I store the class name of T on a local variable?

答:
You must understand that Typescript is just a transpiler (compiler to javascript). Some of the syntax sugar (such as generics) are working only in type-checking phase (and also it's helpful for intellisense in your IDE/text-editor).

However assignment to a variable is happening in runtime, in runtime it's just a plain Javascript. There are no types and no generics in runtime.

But here's the easiest way I would do it:

```<code>class Some<T> {
    private TName : string;
    constructor(x : T&Function) {
        this.TName = x.name;
    }
}

class Another {

}

const some = new Some<Another>(Another);
</code>```

Body:
My Generic class

 export class BaseService<T> {
 public subUrl;
 constructor(public repo:RepogitoryService) { }
}

How can I store the class name of T on a local variable?

Body:
You must understand that Typescript is just a transpiler (compiler to javascript). Some of the syntax sugar (such as generics) are working only in type-checking phase (and also it's helpful for intellisense in your IDE/text-editor).

However assignment to a variable is happening in runtime, in runtime it's just a plain Javascript. There are no types and no generics in runtime.

But here's the easiest way I would do it:

class Some<T> {
    private TName : string;
    constructor(x : T&Function) {
        this.TName = x.name;
    }
}

class Another {

}

const some = new Some<Another>(Another);


问:
Extracting file names from text file
I need to extract file names with their extension from an input text file to a string vector.
The input text file is quite messy and serves as configuration file for some application.

What I know about the file names I am trying to extract is they are preceded by a 'file =' mention, the filename is quoted between ' ' or " ". Example : file="name.abc". I also have no guarantee of how spacing is : It may be file="name.abc", file = "name.abc" , file= "name.abc"... And extension can be of different lengths.

So I tried the following code:

```<code>std::vector<std::string> attachment_names;
std::istringstream words(text_content);
std::string word;
std::string pst_extension(".abc"); // My code should support any extension
while (words >> word)
{
    auto extension_found = word.find(abc_extension);
    if (extension_found != word.npos)
    {
        auto name_start = word.find("'") + 1;
             //I am not even sure the file is quoted by ''

        std::string attachment_name = word.substr(name_start, (extension_found + 3) - name_start + 1);
             //Doing this annoys me a bit... Especially that the extension may be longer than 3 characters

        attachment_names.push_back(attachment_name);
    }
}
</code>```

Is there a nicer way of doing this? Is there a possibility to rely more on the file caption to support any extension?

答:
From C++11 or using boost, my recommendation is that you
use a regular expression with a regex iterator for this problem, since you have variations in the number of spaces and parsing is going to get a bit messy.
A sregex_iterator will traverse the text and match regexes (you can use as a source any bidirectional iterator, for example, strings taken with getline). A non-tested idea follows:

```<code>static std::regex const filename_re("[[:space:]]*file[[:space:]]*=(.*)[[:space:]]*");

std::regex_iterator rit(line.begin(), line.end(), filename_re), end;

while (rit != end) {
  cout << rit[1] << ',';
  ++rit;
}
</code>```

This, taking for each iteration your line, would get the filename found and print it, since the capture group captures the filename.

Title: Extracting file names from text file

Body:
I need to extract file names with their extension from an input text file to a string vector.
The input text file is quite messy and serves as configuration file for some application.

What I know about the file names I am trying to extract is they are preceded by a 'file =' mention, the filename is quoted between ' ' or " ". Example : file="name.abc". I also have no guarantee of how spacing is : It may be file="name.abc", file = "name.abc" , file= "name.abc"... And extension can be of different lengths.

So I tried the following code:

std::vector<std::string> attachment_names;
std::istringstream words(text_content);
std::string word;
std::string pst_extension(".abc"); // My code should support any extension
while (words >> word)
{
    auto extension_found = word.find(abc_extension);
    if (extension_found != word.npos)
    {
        auto name_start = word.find("'") + 1;
             //I am not even sure the file is quoted by ''

        std::string attachment_name = word.substr(name_start, (extension_found + 3) - name_start + 1);
             //Doing this annoys me a bit... Especially that the extension may be longer than 3 characters

        attachment_names.push_back(attachment_name);
    }
}

Is there a nicer way of doing this? Is there a possibility to rely more on the file caption to support any extension?

Body:
From C++11 or using boost, my recommendation is that you
use a regular expression with a regex iterator for this problem, since you have variations in the number of spaces and parsing is going to get a bit messy.
A sregex_iterator will traverse the text and match regexes (you can use as a source any bidirectional iterator, for example, strings taken with getline). A non-tested idea follows:

static std::regex const filename_re("[[:space:]]*file[[:space:]]*=(.*)[[:space:]]*");

std::regex_iterator rit(line.begin(), line.end(), filename_re), end;

while (rit != end) {
  cout << rit[1] << ',';
  ++rit;
}

This, taking for each iteration your line, would get the filename found and print it, since the capture group captures the filename.


问:
MySQL limit & in wont work together
I have 3 tables and I am trying to get 10 most common languages and number of countries which use this language. My tables are:

```<code>City:           Name|Population|CountryCode
Country:        Name|Code
CoutryLanguage: Language|CountryCode
</code>```

To get the top 10 languages I use the population in each city and join it with country language:

```<code>SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10
</code>```

My next logic is to join country with language where language is in my new created table:

```<code>select co.Name, cl.Language
from Country co Inner join CountryLanguage cl on co.Code = cl.CountryCode
where cl.Language in (SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10)
</code>```

This gives me a weird error, I can use it just fine without LIMIT 10 but that just lists all countries and all languages. Is there a way to fix this?? I saw few questions about this but none of them is really clear. Would you mind explaining this error to me?? I can't upgrade my version of sql. Thanks in advance

 I am limiting the number of languages to 10, not the whole table

答:
Just replace the sub-query with a temporary table like this:</p>

```<code>CREATE TEMPORARY TABLE tmp_lang (key(Language)) SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON
ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10;
select co.Name, cl.Language
from Country co Inner join CountryLanguage cl on co.Code = cl.CountryCode
join
tmp_lang tl on c1.Language = tl.Language;
</code>```

Title: MySQL limit & in wont work together

Body:
I have 3 tables and I am trying to get 10 most common languages and number of countries which use this language. My tables are:

City:           Name|Population|CountryCode
Country:        Name|Code
CoutryLanguage: Language|CountryCode

To get the top 10 languages I use the population in each city and join it with country language:

SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10

My next logic is to join country with language where language is in my new created table:

select co.Name, cl.Language
from Country co Inner join CountryLanguage cl on co.Code = cl.CountryCode
where cl.Language in (SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10)

This gives me a weird error, I can use it just fine without LIMIT 10 but that just lists all countries and all languages. Is there a way to fix this?? I saw few questions about this but none of them is really clear. Would you mind explaining this error to me?? I can't upgrade my version of sql. Thanks in advance

 I am limiting the number of languages to 10, not the whole table

Body:
Just replace the sub-query with a temporary table like this:

CREATE TEMPORARY TABLE tmp_lang (key(Language)) SELECT cl.language
FROM City ci INNER JOIN CountryLanguage cl ON
ci.CountryCode = cl.CountryCode
GROUP BY cl.Language
order by sum(ci.population) desc limit 10;
select co.Name, cl.Language
from Country co Inner join CountryLanguage cl on co.Code = cl.CountryCode
join
tmp_lang tl on c1.Language = tl.Language;


问:
MVC Form returns null model back to controller
View has a list of items, each with a checkbox.  Purpose of the form is to check the boxes then return the list to the db.  I expect to see the PickList model in the ViewModel populated with the hidden seedid and the checkbox values, but the form always submits with the PickList as null.</p>

```<code>@model Inventory.ViewModels.ExtractionViewModel

<div class="col-md-4">
    <button class="btn btn-primary" type="submit" form="pick-list-form">Update Pick List</button>
</div>

@using (Html.BeginForm("UpdatePickList", "Extraction", FormMethod.Post, new { @id = "pick-list-form" }))
{
    <table class="table">
        <tr>
            <th>
                Seed Reference
            </th>
            <th>Extracted?</th>
        </tr>

        @foreach (var item in Model.PickList)
        {
            <tr>
                <td>
                    @Html.HiddenFor(modelItem => item.ExtractionId)
                    @Html.HiddenFor(modelItem => item.SeedId)
                    @Html.DisplayFor(modelItem => item.SeedId)
                </td>
                <td>
                    @Html.CheckBoxFor(modelItem => item.IsExtracted)
                </td>
            </tr>
        }
    </table>
}

View Model

public class ExtractionViewModel
{
    public ExtractionDTO Extraction{ get; set; }
    public List<PickListDTO> PickList { get; set; }
}

Pick list model

public class PickListDTO
{
    public int ExtractionId { get; set; }
    public int SeedId { get; set; }
    public bool IsExtracted { get; set; }
}
</code>```

答:
Using @Html.DisplayFormay cause the model to be sent back as NULL. You can use @Html.TextBoxFor.

And just to remind:

Use HiddenFor when you want to provide posted data that the user does not need to be aware of.

Use DisplayFor when you want to show records but not allow them to be editted.

Use TextBoxFor when you want to allow user input or allow the user to edit a field.

I hope it helps you!

Body:
View has a list of items, each with a checkbox.  Purpose of the form is to check the boxes then return the list to the db.  I expect to see the PickList model in the ViewModel populated with the hidden seedid and the checkbox values, but the form always submits with the PickList as null.

@model Inventory.ViewModels.ExtractionViewModel

    <button class="btn btn-primary" type="submit" form="pick-list-form">Update Pick List</button>

@using (Html.BeginForm("UpdatePickList", "Extraction", FormMethod.Post, new { @id = "pick-list-form" }))
{

                Seed Reference

            Extracted?

        @foreach (var item in Model.PickList)
        {

                    @Html.HiddenFor(modelItem => item.ExtractionId)
                    @Html.HiddenFor(modelItem => item.SeedId)
                    @Html.DisplayFor(modelItem => item.SeedId)

                    @Html.CheckBoxFor(modelItem => item.IsExtracted)

        }

}

View Model

public class ExtractionViewModel
{
    public ExtractionDTO Extraction{ get; set; }
    public List<PickListDTO> PickList { get; set; }
}

Pick list model

public class PickListDTO
{
    public int ExtractionId { get; set; }
    public int SeedId { get; set; }
    public bool IsExtracted { get; set; }
}


问:
JS Bootstrap tabbed panel, loading a URL on click
I'm trying to get a Bootstrap tabbed panel to reload itself on click of the button rather than just show the tab. So clicking on the "office" tab will reload the page, and then have the #office tab showing. I have it all working... except for the page reload. It never fires.

HTML

```<code>    <div>
  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation">
        <a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a>     </li>
    <li role="presentation" class="active">
        <a id="office" href="#office" aria-controls="profile" role="tab" data-toggle="tab">Office</a>
    </li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane" id="home">Home</div>
    <div role="tabpanel" class="tab-pane active" id="office">Office</div>
  </div>

</div>
</code>```

JS

```<code>jQuery("#office").click(function(e){
            console.log("clicked")
            e.preventDefault();
            window.location.replace = "http://www.myurl.com#office";
            console.log("after")

            return false;

        });
</code>```

https://jsfiddle.net/zxLt5z2r/

Updated Codepen:

https://codepen.io/anon/pen/QOqrvY

答:
You are returning false and also calling preventDefault();

```<code>jQuery("#office").click(function(e){
            console.log("clicked")
            window.location.href = "http://www.myurl.com#office";
            console.log("after")
        });
</code>```

Also, use window.location.href = "http://example.com/new_url";

Body:
I'm trying to get a Bootstrap tabbed panel to reload itself on click of the button rather than just show the tab. So clicking on the "office" tab will reload the page, and then have the #office tab showing. I have it all working... except for the page reload. It never fires.

HTML

        Home

        Office

Home

Office

JS

jQuery("#office").click(function(e){
            console.log("clicked")
            e.preventDefault();
            window.location.replace = "http://www.myurl.com#office";
            console.log("after")

            return false;

        });

https://jsfiddle.net/zxLt5z2r/

Updated Codepen:

https://codepen.io/anon/pen/QOqrvY

Body:
You are returning false and also calling preventDefault();

jQuery("#office").click(function(e){
            console.log("clicked")
            window.location.href = "http://www.myurl.com#office";
            console.log("after")
        });

Also, use window.location.href = "http://example.com/new_url";


问:
UITextView: Automatically break line when reached a fixed width
I'm working on a view which holds a UITextView. Estimating the correct height for the content works just fine but when continuously typing the content grows horizontally over the border. Which looks like this:

Is there any handy solution which automatically breaks the line when reaching the, through auto layout, defined max width ?

答: If you want to fix a limit of caracters or number of lines, you can by implementing a method from UITextView delegate called func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String)


问:
Sequelize postgres procedure returns string instead of object
I have stored procedure which makes insert in the end:

```<code>CREATE OR REPLACE FUNCTION procedure_name(id_ VARCHAR(128), fname_ VARCHAR(128), lname_ VARCHAR(128)) RETURNS RECORD AS $$
DECLARE
      result RECORD;
BEGIN
    --some logic here
    INSERT INTO user (id, fname, lname)
       VALUES (id_, fname_, lname_)
    RETURNING * into result;
    RETURN result;
END;
$$ LANGUAGE plpgsql;
</code>```

When I run plain INSERT (plain SQL from code):

```<code>var query = "INSERT INTO user (id, fname, lname) VALUES (2, Jack, Doe) RETURNING *;"
sequelizeConnection.query(query, {raw : true, plain: true, type:sequelizeConnection.QueryTypes.INSERT})
</code>```

result has mapped to object:

```<code>{
    id: 2,
    fname: Jack,
    lname: Doe
}
</code>```

But when I invoke procedure like this:

```<code>    function insertUser(data) {
        var options = {replacements: data, raw:true, plain:true,  model:sequelize.models['user'], type: sequelize.QueryTypes.INSERT};
        return sequelize.query("SELECT procedure_name(:id, :fname, :lname)", options);
    }
</code>```

I get following result:

```<code>{ procedure_name: '(1,John,Doe)'}
</code>```

How to get object from procedure?

答:
With help of Abdel P. complete answer was found: </p>

```<code>sequelize.query("Select * from procedure_name(:id, :fname, :lname) as (id VARCHAR(128), fname VARCHAR(128), lname VARCHAR(128))", options)
</code>```

Body:
I have stored procedure which makes insert in the end:

CREATE OR REPLACE FUNCTION procedure_name(id_ VARCHAR(128), fname_ VARCHAR(128), lname_ VARCHAR(128)) RETURNS RECORD AS $$
DECLARE
      result RECORD;
BEGIN
    --some logic here
    INSERT INTO user (id, fname, lname)
       VALUES (id_, fname_, lname_)
    RETURNING * into result;
    RETURN result;
END;
$$ LANGUAGE plpgsql;

When I run plain INSERT (plain SQL from code):

var query = "INSERT INTO user (id, fname, lname) VALUES (2, Jack, Doe) RETURNING *;"
sequelizeConnection.query(query, {raw : true, plain: true, type:sequelizeConnection.QueryTypes.INSERT})

result has mapped to object:

{
    id: 2,
    fname: Jack,
    lname: Doe
}

But when I invoke procedure like this:

    function insertUser(data) {
        var options = {replacements: data, raw:true, plain:true,  model:sequelize.models['user'], type: sequelize.QueryTypes.INSERT};
        return sequelize.query("SELECT procedure_name(:id, :fname, :lname)", options);
    }

I get following result:

{ procedure_name: '(1,John,Doe)'}

How to get object from procedure?

Body:
With help of Abdel P. complete answer was found:

sequelize.query("Select * from procedure_name(:id, :fname, :lname) as (id VARCHAR(128), fname VARCHAR(128), lname VARCHAR(128))", options)


问:
Not sending userAgent in header, Node.js console application
I'm just beginning to learn javascript and https requests.  I'm working in Visual Studio 2017, I created a blank javascript console app from the template and added the following code.

```<code>const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();
</code>```

The response I get from the server is

```<code>{"message":"User-Agent header is required."}
</code>```

When I navigate to https://api.gdax.com/products/BTC-USD/stats in my browser I get the correct response.  How come I can't do the same in a javascript console?

答:
You need to set headers manually.  See http documentation for all possible request options (this is the same for http and https).

try:

```<code>const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false,
    headers: {
        'User-Agent': 'Foo/1.0',
    },
};
</code>```

Body:
I'm just beginning to learn javascript and https requests.  I'm working in Visual Studio 2017, I created a blank javascript console app from the template and added the following code.

const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();

The response I get from the server is

{"message":"User-Agent header is required."}

When I navigate to https://api.gdax.com/products/BTC-USD/stats in my browser I get the correct response.  How come I can't do the same in a javascript console?

Body:
You need to set headers manually.  See http documentation for all possible request options (this is the same for http and https).

try:

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false,
    headers: {
        'User-Agent': 'Foo/1.0',
    },
};


问:
Failing JUnit tests for embedded Fongo DB
I have a Spring Boot application which use MongoDB. I would like to use the embedded FongoDB for my JUnit tests. I follow some articles, for example:

http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html

My Fongo test configuration looks like

```<code>package com.myproject.rest;

import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Profile("test")
@ComponentScan(basePackages = "com.myproject.service.data")
@EnableMongoRepositories(basePackages = "com.myproject.service.data.repository")
@Configuration
public class MongoTestConfig extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "demo-test";
    }

    @Bean
    @Override
    public Mongo mongo() {
        return new Fongo("mongo-test").getMongo();
    }

}
</code>```

I have this dependency for that:

```<code>        <dependency>
            <groupId>com.github.fakemongo</groupId>
            <artifactId>fongo</artifactId>
            <version>2.1.0</version>
            <scope>test</scope>
        </dependency>
</code>```

I would like to test my services which autowired a repository interface which extends MongoRepository

```<code>package com.myproject.service.data.repository;

import com.myproject.service.data.entity.JournalData;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface JournalRepository extends MongoRepository<JournalData, String> {

    @Override
    public List<JournalData> findAll(Iterable<String> ids);
}
</code>```

My tests class are inherited from the class below:

```<code>package com.myproject.rest;

import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import cz.csas.services.commons.api.RequestMetadata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@PowerMockIgnore({"javax.xml.*", "org.xml.*", "org.w3c.*", "javax.management.*", "javax.net.ssl.*"})
@PrepareForTest({RequestMetadata.class})
@ActiveProfiles("test")
public class EndpointTestContext {

    @Autowired
    protected MockMvc mockMvc;

    //@Rule
    //public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("demo-test");

    @Before
    public void setup() {
        mockStatic(RequestMetadata.class);
        when(RequestMetadata.builder()).thenCallRealMethod();
        RequestMetadata m = RequestMetadata.builder()
                .workingMode("TEST")
                .build();
        when(RequestMetadata.getMetadata()).thenReturn(m);
    }

}
</code>```

But when I run the Maven tests I recieve the following:

```<code>Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.mongodb.MongoClientOptions
    at com.mongodb.MockMongoClient.create(MockMongoClient.java:42)
    at com.github.fakemongo.Fongo.createMongo(Fongo.java:175)
    at com.github.fakemongo.Fongo.<init>(Fongo.java:88)
    at com.github.fakemongo.Fongo.<init>(Fongo.java:75)
    at com.github.fakemongo.Fongo.<init>(Fongo.java:67)
    at com.myproject.rest.MongoTestConfig.mongo(MongoTestConfig.java:30)
    at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4.CGLIB$mongo$1(<generated>)
    at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4$$FastClassBySpringCGLIB$$3ab8bfd7.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4.mongo(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 115 common frames omitted
</code>```

Can anyone suggest how to fix it? Thank you in advance.

答:
Fongo can't find class from mongo-java-driver artifact. It declares

```<code><!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.2</version>
</dependency>
</code>```

as provided dependency. You should have mongo-java-driver on your test classpath. Most probably

```<code><scope>runtime</scope>
</code>```

or test will be enough for you.

Body:
I have a Spring Boot application which use MongoDB. I would like to use the embedded FongoDB for my JUnit tests. I follow some articles, for example:

http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html

My Fongo test configuration looks like

package com.myproject.rest;

import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Profile("test")
@ComponentScan(basePackages = "com.myproject.service.data")
@EnableMongoRepositories(basePackages = "com.myproject.service.data.repository")
@Configuration
public class MongoTestConfig extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "demo-test";
    }

    @Bean
    @Override
    public Mongo mongo() {
        return new Fongo("mongo-test").getMongo();
    }

}

I have this dependency for that:

        <dependency>
            <groupId>com.github.fakemongo</groupId>
            <artifactId>fongo</artifactId>
            <version>2.1.0</version>
            <scope>test</scope>
        </dependency>

I would like to test my services which autowired a repository interface which extends MongoRepository

package com.myproject.service.data.repository;

import com.myproject.service.data.entity.JournalData;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface JournalRepository extends MongoRepository<JournalData, String> {

    @Override
    public List<JournalData> findAll(Iterable<String> ids);
}

My tests class are inherited from the class below:

package com.myproject.rest;

import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import cz.csas.services.commons.api.RequestMetadata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@PowerMockIgnore({"javax.xml.*", "org.xml.*", "org.w3c.*", "javax.management.*", "javax.net.ssl.*"})
@PrepareForTest({RequestMetadata.class})
@ActiveProfiles("test")
public class EndpointTestContext {

    @Autowired
    protected MockMvc mockMvc;

    //@Rule
    //public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("demo-test");

    @Before
    public void setup() {
        mockStatic(RequestMetadata.class);
        when(RequestMetadata.builder()).thenCallRealMethod();
        RequestMetadata m = RequestMetadata.builder()
                .workingMode("TEST")
                .build();
        when(RequestMetadata.getMetadata()).thenReturn(m);
    }

}

But when I run the Maven tests I recieve the following:

Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.mongodb.MongoClientOptions
    at com.mongodb.MockMongoClient.create(MockMongoClient.java:42)
    at com.github.fakemongo.Fongo.createMongo(Fongo.java:175)
    at com.github.fakemongo.Fongo.<init>(Fongo.java:88)
    at com.github.fakemongo.Fongo.<init>(Fongo.java:75)
    at com.github.fakemongo.Fongo.<init>(Fongo.java:67)
    at com.myproject.rest.MongoTestConfig.mongo(MongoTestConfig.java:30)
    at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4.CGLIB$mongo$1(<generated>)
    at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4$$FastClassBySpringCGLIB$$3ab8bfd7.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4.mongo(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 115 common frames omitted

Can anyone suggest how to fix it? Thank you in advance.

Body:
Fongo can't find class from mongo-java-driver artifact. It declares

<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.2</version>
</dependency>

as provided dependency. You should have mongo-java-driver on your test classpath. Most probably

<scope>runtime</scope>

or test will be enough for you.


问:
##[error]System error 1326 has occurred. - VSTS Release Task: Windows Machine File Copy
I am using VSTS to deploy an MVC Website and a database to an Azure Virtual Machine . While trying to copy the needed dacpac file i get this error: ##[error]System error 1326 has occurred.

Here is the log from the release:

```<code>2017-11-03T10:29:50.7943998Z ##[section]Starting: Copy files from *******
2017-11-03T10:29:50.8436980Z ==============================================================================
2017-11-03T10:29:50.8436980Z Task         : Windows Machine File Copy
2017-11-03T10:29:50.8436980Z Description  : Copy files to remote machine(s)
2017-11-03T10:29:50.8436980Z Version      : 2.0.1
2017-11-03T10:29:50.8436980Z Author       : Microsoft Corporation
2017-11-03T10:29:50.8436980Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=627415)
2017-11-03T10:29:50.8436980Z ==============================================================================
2017-11-03T10:29:54.1838780Z Copy started for - *******
2017-11-03T10:29:54.9182580Z ##[error]System error 1326 has occurred.

2017-11-03T10:29:54.9807578Z ##[section]Finishing: Copy files from *******
</code>```

The error does not give me alot of details about the problem so i started digging deeper in the problem. I have Enabled all the needed ports, checked if the account specified was an administrator(it was), made sure the date was set correctrly(tried this because there are some examples where it works).

Azure File Copy does not help me in my situation.

Any information would be very appreciated. Thank you !!!

答:
I had the same problem also. I solved it by changing the version of the script from 2* to 1*. I think the problem has to do with the password
look these links
enter link description here

enter link description here

Body:
I am using VSTS to deploy an MVC Website and a database to an Azure Virtual Machine . While trying to copy the needed dacpac file i get this error: ##[error]System error 1326 has occurred.

Here is the log from the release:

2017-11-03T10:29:50.7943998Z ##[section]Starting: Copy files from *******
2017-11-03T10:29:50.8436980Z ==============================================================================
2017-11-03T10:29:50.8436980Z Task         : Windows Machine File Copy
2017-11-03T10:29:50.8436980Z Description  : Copy files to remote machine(s)
2017-11-03T10:29:50.8436980Z Version      : 2.0.1
2017-11-03T10:29:50.8436980Z Author       : Microsoft Corporation
2017-11-03T10:29:50.8436980Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=627415)
2017-11-03T10:29:50.8436980Z ==============================================================================
2017-11-03T10:29:54.1838780Z Copy started for - *******
2017-11-03T10:29:54.9182580Z ##[error]System error 1326 has occurred.

2017-11-03T10:29:54.9807578Z ##[section]Finishing: Copy files from *******

The error does not give me alot of details about the problem so i started digging deeper in the problem. I have Enabled all the needed ports, checked if the account specified was an administrator(it was), made sure the date was set correctrly(tried this because there are some examples where it works).

Azure File Copy does not help me in my situation.

Any information would be very appreciated. Thank you !!!


问:
creating JSON format
I want to create JSON object like below,

```<code>{"Validate":"Check","Parameters":[{"name":"Greg", "value":"1"},{"name":"Mike","value":"2"}]};
</code>```

and I have two arrays like below,

```<code>["Greg", "Mike] and ["1", "2"]
</code>```

What is the best way to combine these arrays to populate the JSON object I described above by using JS?

答:
Try using map</p>

```<code>let names = ["Greg", "Mike"];
let values = ["1", "2"];
let parameters = names.map((name, index) => ({name: name, value: values[index]}))
let json = {"Validate":"Check","Parameters":parameters};
</code>```

Title: creating JSON format

Body:
I want to create JSON object like below,

{"Validate":"Check","Parameters":[{"name":"Greg", "value":"1"},{"name":"Mike","value":"2"}]};

and I have two arrays like below,

["Greg", "Mike] and ["1", "2"]

What is the best way to combine these arrays to populate the JSON object I described above by using JS?

Body:
Try using map

let names = ["Greg", "Mike"];
let values = ["1", "2"];
let parameters = names.map((name, index) => ({name: name, value: values[index]}))
let json = {"Validate":"Check","Parameters":parameters};


问:
Power BI refresh Token Useablity
I have been working on powerBI embedding for the last 6 months. I have the faced same issue of token expiration. I have generated refresh token, but that too (not sure) may be getting expired after some period of time. </p>

<p>Can any one please suggest me a better way to get token that doesn't expire or help me in re-usability of refresh token which I have stored. </p>

答:
There are two different tokens in Power BI: embed token and access token.

With embed token, if it's a web platform, you're able to refresh it automatically like this:
https://github.com/Microsoft/PowerBI-JavaScript/wiki/Refresh-token-using-JavaScript-SDK-example

Or if you're using Power BI Embedded, you're able to create long lasting tokens:
https://community.powerbi.com/t5/Developer/Integrate-PowerBI-with-Netsuite/m-p/93864#M3319

Access token is a bit different. It comes from Azure and depending on your platform, you might be able to refresh it automatically. If you're on web platform, the easiest way is to just hit F5, otherwise you'll need to automate this: https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-walkthrough-push-data-get-token/

Title: Power BI refresh Token Useablity

Body:
I have been working on powerBI embedding for the last 6 months. I have the faced same issue of token expiration. I have generated refresh token, but that too (not sure) may be getting expired after some period of time.

Can any one please suggest me a better way to get token that doesn't expire or help me in re-usability of refresh token which I have stored.


问:
Xcode & IB - Window Controller Method
I have 2 windows in an xcode project, A and B.  A is to capture information, B is to display.  I built the windows in IB.

I would like to create a method to control the submit from window A to close window A, and display window B fullscreen.

I am completely new to OBJ C and Cocoa, so Please explain this or provide example code...

If I want to do this, I know I need to create a file from within IB with my A and B to add to my project to add the code, or do I simply add a cocoa file .h and .m to the project.  If so, what tells IB that these files correspond to the windows I already created in IB.  Once the IBAction is completed I know how to link in IB, but I am at a loss as to how to proceed.

答:
So from what it sounds, you need to declare (in .h):

```<code>- (IBAction) closeWindowA:(id)self;
</code>```

Then tell your application what closeWindowA really does (in. m):

```<code>- (IBAction) closeWindowA {

    // your code goes here. Look up method(s) for closing the window - don't know them by heart

}
</code>```

Then, just connect your Button or whatever is triggering the action in Interface builder using the draggable connections. Hope this helps - I also have to recommend 'Cocoa Programming for Mac OSX' by Aaron Hillegas. Helps tremendously in understanding these kinds of things.

ContentLicense: CC BY-SA 2.5

Title: Xcode & IB - Window Controller Method

Body:
So from what it sounds, you need to declare (in .h):

- (IBAction) closeWindowA:(id)self;

Then tell your application what closeWindowA really does (in. m):

- (IBAction) closeWindowA {

    // your code goes here. Look up method(s) for closing the window - don't know them by heart

}

Then, just connect your Button or whatever is triggering the action in Interface builder using the draggable connections. Hope this helps - I also have to recommend 'Cocoa Programming for Mac OSX' by Aaron Hillegas. Helps tremendously in understanding these kinds of things.


问:
swift firebase nested children count
```<code>groups
--group1(autoid)
---subgroup1(autoid)
----id
----ownerId
----description
--group2(autoid)
---subgroup2(autoid)
----id
----ownerId
----description
</code>```

In a structure like over here i have to count all occurrencies of ownerId that are equal to my id (currentUserId) in all groups, can somebody help me?

what i've done so far:

root.child("groups").observe(.value, with: {(snapshot) in
    if let result = snapshot.children.allObjects as? [DataSnapshot] {
        var count = 0
        for child in result {
            let orderID = child.key as String //get autoID
            self.root.child("groups/\(orderID)/").queryOrdered(byChild: "ownerId").queryEqual(toValue: self.currentUserId).observe(.value, with: { (snapshot: DataSnapshot!) in
                print(snapshot.childrenCount, "quanti sono")
                count += (Int(snapshot.childrenCount))
                print(count)
            })
        }
    }
})
```

with this i can get a count but it updates all cycles... i need i need the final value outside

答:
You can achieve this step by doing a single observe of .childAdded type. The .childAdded on an sub child, in your example groups, is like a for loop that iterate all nodes.

With this configuration you can append a .queryOrdered(byChild:) and a .queryEqual(toValue:):

```<code>ref.child("groups")
    .queryOrdered(byChild: "ownerID")
    .queryEqual(toValue: 123)
    .observe(.childAdded)
{ (snap) in
    print(snap)
}
</code>```

After that, if you want to count all this child, you need to add a property on your class

This is a test example:

To optimize performance remember to add a .indexOn rule on your firebase app:

```<code>"groups" : {
  ".indexOn" : "ownerID"
}
</code>```

Hope this help you ;)

Title: swift firebase nested children count

Body:
groups
--group1(autoid)
---subgroup1(autoid)
----id
----ownerId
----description
--group2(autoid)
---subgroup2(autoid)
----id
----ownerId
----description

In a structure like over here i have to count all occurrencies of ownerId that are equal to my id (currentUserId) in all groups, can somebody help me?

what i've done so far:

root.child("groups").observe(.value, with: {(snapshot) in
    if let result = snapshot.children.allObjects as? [DataSnapshot] {
        var count = 0
        for child in result {
            let orderID = child.key as String //get autoID
            self.root.child("groups/\(orderID)/").queryOrdered(byChild: "ownerId").queryEqual(toValue: self.currentUserId).observe(.value, with: { (snapshot: DataSnapshot!) in
                print(snapshot.childrenCount, "quanti sono")
                count += (Int(snapshot.childrenCount))
                print(count)
            })
        }
    }
})

with this i can get a count but it updates all cycles... i need i need the final value outside

Body:
You can achieve this step by doing a single observe of .childAdded type. The .childAdded on an sub child, in your example groups, is like a for loop that iterate all nodes.

With this configuration you can append a .queryOrdered(byChild:) and a .queryEqual(toValue:):

ref.child("groups")
    .queryOrdered(byChild: "ownerID")
    .queryEqual(toValue: 123)
    .observe(.childAdded)
{ (snap) in
    print(snap)
}

After that, if you want to count all this child, you need to add a property on your class

This is a test example:

To optimize performance remember to add a .indexOn rule on your firebase app:

"groups" : {
  ".indexOn" : "ownerID"
}

Hope this help you ;)


问:
Java Error: NullPointerException due to missing Constructor(s)
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

```<code>Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)
</code>```

This is where the error happens:

```<code>public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}
</code>```

The "Display" class I'm trying to access:

```<code>public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}
</code>```

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.

答:
In Java the default constructor (the one without any argument) appears only if no other constructor is specified. Since you wrote your own constructor:

```<code>public Display(JFrame frame){
    this.frame = frame;
}
</code>```

You cannot call new Display() now.
You can either:

Create a JFrame in ArrayControl class and Call new Display(jFrame);

Create a new constructor without arguments in Display class:

```<code>public Display() { //do nothing or maybe create JFrame here? }
</code>```

Body:
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)

This is where the error happens:

public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}

The "Display" class I'm trying to access:

public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.

Body:
In Java the default constructor (the one without any argument) appears only if no other constructor is specified. Since you wrote your own constructor:

public Display(JFrame frame){
    this.frame = frame;
}

You cannot call new Display() now.
You can either:

Create a JFrame in ArrayControl class and Call new Display(jFrame);

Create a new constructor without arguments in Display class:

public Display() { //do nothing or maybe create JFrame here? }


问:
Javascript: Check if Element has Changed
I want to know, if it's possible, how to check in javascript if an element has changed or an attribute of it?

I mean something like window.onhashchange for an element something like:

```<code>document.getElementById("element").onElementChange = function();
</code>```

As I know onchange is something like this, but will it work if I want to know in this way:

```<code>var element = {};
element.attribute = result;

element.attribute.onchange = function();
</code>```

答:
I did this.  It works pretty well. I would have used the setProperty method if I had known.  </p>

```<code>function searchArray(searchValue, theArray, ChangeValue){
    for (var i=0; i < theArray.length; i++) {
        if (theArray[i].id === searchValue) {
            theArray[i].changed = ChangeValue;
        }
    }
}

function getArrayIindex(elementid, theArray){
    for (var i=0; i < theArray.length; i++) {
        if (theArray[i].id === elementid) {
            return i;
        }
    }
}

function setInputEvents(hiddenObject) {

        var element;

        for (var i = 0; i < document.forms[0].length; i++) {
            element = document.forms[0].elements[i];

            //Check to see if the element is of type input
            if (element.type in { text: 1, password: 1, textarea: 1 }) {

                arrFieldList.push({
                    id: element.id,
                    changed:false,
                    index: i,
                });

                element.onfocus = function () {
                    if (!arrFieldList[getArrayIindex(this.id, arrFieldList)].changed) {
                        hiddenObject.value = this.value;
                        this.value = '';
                    }
                }

                element.onblur = function () {
                    if (this.value == '') {
                        this.value = hiddenObject.value;
                    }
                }

                element.onchange = function () {
                    searchArray(this.id, arrFieldList, true);
                }
            }

        }
</code>```

Body:
I want to know, if it's possible, how to check in javascript if an element has changed or an attribute of it?

I mean something like window.onhashchange for an element something like:

document.getElementById("element").onElementChange = function();

As I know onchange is something like this, but will it work if I want to know in this way:

var element = {};
element.attribute = result;

element.attribute.onchange = function();

Body:
I did this.  It works pretty well. I would have used the setProperty method if I had known.

function searchArray(searchValue, theArray, ChangeValue){
    for (var i=0; i < theArray.length; i++) {
        if (theArray[i].id === searchValue) {
            theArray[i].changed = ChangeValue;
        }
    }
}

function getArrayIindex(elementid, theArray){
    for (var i=0; i < theArray.length; i++) {
        if (theArray[i].id === elementid) {
            return i;
        }
    }
}

function setInputEvents(hiddenObject) {

        var element;

        for (var i = 0; i < document.forms[0].length; i++) {
            element = document.forms[0].elements[i];

            //Check to see if the element is of type input
            if (element.type in { text: 1, password: 1, textarea: 1 }) {

                arrFieldList.push({
                    id: element.id,
                    changed:false,
                    index: i,
                });

                element.onfocus = function () {
                    if (!arrFieldList[getArrayIindex(this.id, arrFieldList)].changed) {
                        hiddenObject.value = this.value;
                        this.value = '';
                    }
                }

                element.onblur = function () {
                    if (this.value == '') {
                        this.value = hiddenObject.value;
                    }
                }

                element.onchange = function () {
                    searchArray(this.id, arrFieldList, true);
                }
            }

        }


答:
Location.replace() is a function that takes an URL as the parameter.

Try:

```<code>window.location.replace("http://www.myurl.com#office");
</code>```

Title: JS Bootstrap tabbed panel, loading a URL on click

Body:
I'm trying to get a Bootstrap tabbed panel to reload itself on click of the button rather than just show the tab. So clicking on the "office" tab will reload the page, and then have the #office tab showing. I have it all working... except for the page reload. It never fires.

HTML

        Home

        Office

Home

Office

JS

jQuery("#office").click(function(e){
            console.log("clicked")
            e.preventDefault();
            window.location.replace = "http://www.myurl.com#office";
            console.log("after")

            return false;

        });

https://jsfiddle.net/zxLt5z2r/

Updated Codepen:

https://codepen.io/anon/pen/QOqrvY

Body:
Location.replace() is a function that takes an URL as the parameter.

Try:

window.location.replace("http://www.myurl.com#office");


问:
Using Java Selenium to scrape a data across multiple pages when the url doesn't change
I have been trying to write a simple code to scrape some basic stats from www.whoscored.com.
My code loops through first page links and scrape data just fine but when I switch with driver.findElement(By.xpath("")).click(); to next table, it collects data from first game BUT then keeps looping/return AGAIN on the first table/page...

Here is the code:

```<code>package Whoscored;

import java.io.File;

public class Datascrape {

public static void main(String[] args) throws InterruptedException,
IOException {

        WebDriver driver = new FirefoxDriver();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)

              // get the URL
               driver.get("https://www.whoscored.com/Regions/81/Tournaments/6/Seasons/6393/Germany-Bundesliga-II");

        Thread.sleep(1000);
        driver.manage().window().maximize();

          // first loop to identify matches-list over and over again

         for (int w=0;w<=100;w++){

        List<WebElement> lista1 =
        driver.findElements(By.cssSelector(".match-link.match-report.rc"));

          // second loop for each table

        for (int j=0;j<=lista1.size(); j++){
        lista1.get(j).click();
        driver.manage().window().maximize();

// go deeper (two clicks), grab stats and return to original position/table

   // clicks
   driver.findElement(By.xpath(".//*[@id='sub-
   navigation']/ul/li[4]/a")).click();
   driver.findElement(By.xpath(".//*[@id='live-match-
   options']/li[3]")).click();

   // grab stats/text
   String home6 = driver.findElement(By.xpath(".//*
   [@id='chalkboard']/div[2]/div[1]/div[3]/div[2]/span[1]")).getText();
   String away6 = driver.findElement(By.xpath(".//*
   [@id='chalkboard']/div[2]/div[1]/div[3]/div[2]/span[2]")).getText();

          driver.navigate().back();
          Thread.sleep(5000);
          driver.navigate().back();
          Thread.sleep(5000);
   lista1= driver.findElements(By.cssSelector(".match-link.match-
   report.rc"));

            }
   // after it finishes with first table go to second table with click

   driver.findElement(By.xpath(".//*[@id='date-
   controller']/a[1]/span")).click();
   Thread.sleep(5000);
    }
           }
}
</code>```

答:
You have to make sure that data has been loaded before reading the document.
e.g. your call

```<code>driver.findElement(By.xpath(".//*[@id='date-controller']a[1]/span")).click();
</code>```

is fine, but you also need to make sure that the next sibling

```<code>driver.findElement(By.xpath(".//*[@id='date-controller']a[2]/span"))
</code>```

has changed its value for example the initial span contains "23 - 29 Jan 2017" and onclick it should change to "19 - 25 Dec 2016"

Body:
I have been trying to write a simple code to scrape some basic stats from www.whoscored.com.
My code loops through first page links and scrape data just fine but when I switch with driver.findElement(By.xpath("")).click(); to next table, it collects data from first game BUT then keeps looping/return AGAIN on the first table/page...

Here is the code:

package Whoscored;

import java.io.File;

public class Datascrape {

public static void main(String[] args) throws InterruptedException,
IOException {

        WebDriver driver = new FirefoxDriver();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)

              // get the URL
               driver.get("https://www.whoscored.com/Regions/81/Tournaments/6/Seasons/6393/Germany-Bundesliga-II");

        Thread.sleep(1000);
        driver.manage().window().maximize();

          // first loop to identify matches-list over and over again

         for (int w=0;w<=100;w++){

        List<WebElement> lista1 =
        driver.findElements(By.cssSelector(".match-link.match-report.rc"));

          // second loop for each table

        for (int j=0;j<=lista1.size(); j++){
        lista1.get(j).click();
        driver.manage().window().maximize();

// go deeper (two clicks), grab stats and return to original position/table

   // clicks
   driver.findElement(By.xpath(".//*[@id='sub-
   navigation']/ul/li[4]/a")).click();
   driver.findElement(By.xpath(".//*[@id='live-match-
   options']/li[3]")).click();

   // grab stats/text
   String home6 = driver.findElement(By.xpath(".//*
   [@id='chalkboard']/div[2]/div[1]/div[3]/div[2]/span[1]")).getText();
   String away6 = driver.findElement(By.xpath(".//*
   [@id='chalkboard']/div[2]/div[1]/div[3]/div[2]/span[2]")).getText();

          driver.navigate().back();
          Thread.sleep(5000);
          driver.navigate().back();
          Thread.sleep(5000);
   lista1= driver.findElements(By.cssSelector(".match-link.match-
   report.rc"));

            }
   // after it finishes with first table go to second table with click

   driver.findElement(By.xpath(".//*[@id='date-
   controller']/a[1]/span")).click();
   Thread.sleep(5000);
    }
           }
}

Body:
You have to make sure that data has been loaded before reading the document.
e.g. your call

driver.findElement(By.xpath(".//*[@id='date-controller']a[1]/span")).click();

is fine, but you also need to make sure that the next sibling

driver.findElement(By.xpath(".//*[@id='date-controller']a[2]/span"))

has changed its value for example the initial span contains "23 - 29 Jan 2017" and onclick it should change to "19 - 25 Dec 2016"


问:
Powershell Code for a birthday cake
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.</p>

```<code>$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}
</code>```

答:
Here's a fix to your current code so it runs:

```<code>$Birthday = [DateTime]'11/21/2017'
$Today = Get-Date

If ($Birthday.Date -eq $Today.Date)
{
    'Happy 18th Birthday, JularJ!'
}
Else
{
    'Eat Cake Anyways'
}
</code>```

Here's a bonus, put this into a .bat or .cmd file and you don't need to worry about executionpolicy stuff:

```<code>powershell -ExecutionPolicy Bypass -NoProfile -NoExit -NoLogo -EncodedCommand "JABCAGkAcgB0AGgAZABhAHkAIAA9ACAAWwBEAGEAdABlAFQAaQBtAGUAXQAnADEAMQAvADIAMQAvADIAMAAxADcAJwAKACQAVABvAGQAYQB5ACAAPQAgAEcAZQB0AC0ARABhAHQAZQAKAAoASQBmACAAKAAkAEIAaQByAHQAaABkAGEAeQAuAEQAYQB0AGUAIAAtAGUAcQAgACQAVABvAGQAYQB5AC4ARABhAHQAZQApAAoAewAKACAAIAAgACAAJwBIAGEAcABwAHkAIAAxADgAdABoACAAQgBpAHIAdABoAGQAYQB5ACwAIABKAHUAbABhAHIASgAhACcACgB9AAoARQBsAHMAZQAKAHsACgAgACAAIAAgACcARQBhAHQAIABDAGEAawBlACAAQQBuAHkAdwBhAHkAcwAnAAoAfQA="
</code>```

This is your script encoded in base64 and will execute all the same.

You can validate by running the following in PowerShell:

```<code>[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('JABCAGkAcgB0AGgAZABhAHkAIAA9ACAAWwBEAGEAdABlAFQAaQBtAGUAXQAnADEAMQAvADIAMQAvADIAMAAxADcAJwAKACQAVABvAGQAYQB5ACAAPQAgAEcAZQB0AC0ARABhAHQAZQAKAAoASQBmACAAKAAkAEIAaQByAHQAaABkAGEAeQAuAEQAYQB0AGUAIAAtAGUAcQAgACQAVABvAGQAYQB5AC4ARABhAHQAZQApAAoAewAKACAAIAAgACAAJwBIAGEAcABwAHkAIAAxADgAdABoACAAQgBpAHIAdABoAGQAYQB5ACwAIABKAHUAbABhAHIASgAhACcACgB9AAoARQBsAHMAZQAKAHsACgAgACAAIAAgACcARQBhAHQAIABDAGEAawBlACAAQQBuAHkAdwBhAHkAcwAnAAoAfQA='))
</code>```

Title: Powershell Code for a birthday cake

Body:
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.

$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}

Body:
Here's a fix to your current code so it runs:

$Birthday = [DateTime]'11/21/2017'
$Today = Get-Date

If ($Birthday.Date -eq $Today.Date)
{
    'Happy 18th Birthday, JularJ!'
}
Else
{
    'Eat Cake Anyways'
}

Here's a bonus, put this into a .bat or .cmd file and you don't need to worry about executionpolicy stuff:

powershell -ExecutionPolicy Bypass -NoProfile -NoExit -NoLogo -EncodedCommand "JABCAGkAcgB0AGgAZABhAHkAIAA9ACAAWwBEAGEAdABlAFQAaQBtAGUAXQAnADEAMQAvADIAMQAvADIAMAAxADcAJwAKACQAVABvAGQAYQB5ACAAPQAgAEcAZQB0AC0ARABhAHQAZQAKAAoASQBmACAAKAAkAEIAaQByAHQAaABkAGEAeQAuAEQAYQB0AGUAIAAtAGUAcQAgACQAVABvAGQAYQB5AC4ARABhAHQAZQApAAoAewAKACAAIAAgACAAJwBIAGEAcABwAHkAIAAxADgAdABoACAAQgBpAHIAdABoAGQAYQB5ACwAIABKAHUAbABhAHIASgAhACcACgB9AAoARQBsAHMAZQAKAHsACgAgACAAIAAgACcARQBhAHQAIABDAGEAawBlACAAQQBuAHkAdwBhAHkAcwAnAAoAfQA="

This is your script encoded in base64 and will execute all the same.

You can validate by running the following in PowerShell:

[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('JABCAGkAcgB0AGgAZABhAHkAIAA9ACAAWwBEAGEAdABlAFQAaQBtAGUAXQAnADEAMQAvADIAMQAvADIAMAAxADcAJwAKACQAVABvAGQAYQB5ACAAPQAgAEcAZQB0AC0ARABhAHQAZQAKAAoASQBmACAAKAAkAEIAaQByAHQAaABkAGEAeQAuAEQAYQB0AGUAIAAtAGUAcQAgACQAVABvAGQAYQB5AC4ARABhAHQAZQApAAoAewAKACAAIAAgACAAJwBIAGEAcABwAHkAIAAxADgAdABoACAAQgBpAHIAdABoAGQAYQB5ACwAIABKAHUAbABhAHIASgAhACcACgB9AAoARQBsAHMAZQAKAHsACgAgACAAIAAgACcARQBhAHQAIABDAGEAawBlACAAQQBuAHkAdwBhAHkAcwAnAAoAfQA='))


问:
Why do lots of (old) programs use floor(0.5 + input) instead of round(input)?
The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

```<code>int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}
</code>```

which outputs:

```<code>1
0
</code>```

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?

答:
A simple reason could be that there are different methods of rounding numbers so unless you knew the method used, you could different results.

With floor(), you can be consistent with the results. If the float is .5 or greater, adding it will bump up to the next int. But .49999 will just drop the decimal.

Body:
The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}

which outputs:

1
0

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?


问:
how can i install the packages in r properly and correctly using Rstudio app?
I tried to install "xlsx" package using Rstudio, and i couldn't install it.

I am trying to install my packages using install.packages("xlsxjars").  I already tried doing that from Tools window in Rstudio app, and I tried using the console.

I am using Linux (Gnome 17.04).  I get this error:

input

```<code>install.packages("xlsxjars")
</code>```

output

```<code>Installing package into ‘/home/aim/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/xlsxjars_0.6.1.tar.gz'
Error in install.packages : error reading from connection
</code>```

答:
if you get some Errors while installing r packages kind of somthing.so is miising  or  some packages are missing depending on the version of R, you should try this commands because, i had this kind of errors with R 3.0.x in Ubuntu 14.04
so  i upgrade my R version to fix it with the following commands :

sudo sh -c 'echo "deb http://cran.rstudio.com/bin/linux/ubuntu trusty/" »

gpg —keyserver keyserver.ubuntu.com —recv-key E084DAB9

gpg -a —export E084DAB9 | sudo apt-key add -

sudo apt-get —purge remove r-base-core

sudo apt-get update

sudo apt-get -y install r-base

sudo apt-get update

now i can install all packages without errors

Body:
I tried to install "xlsx" package using Rstudio, and i couldn't install it.

I am trying to install my packages using install.packages("xlsxjars").  I already tried doing that from Tools window in Rstudio app, and I tried using the console.

I am using Linux (Gnome 17.04).  I get this error:

input

install.packages("xlsxjars")

output

Installing package into ‘/home/aim/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/xlsxjars_0.6.1.tar.gz'
Error in install.packages : error reading from connection


问:
Preflight request in VueJS with axios
I am a bit stuck with getting a response from the meetup API. The error I am getting:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Here's my code:

```<code>var config = {'Access-Control-Allow-Headers': 'Authorization'}

axios.get(`https://api.meetup.com/self/calendar?&sign=true&photo-host=public&page=20`, {headers: config})
.then(response => {
  console.log(response.data)
  this.posts = response.data
})
.catch(e => {
  this.errors.push(e)
})
</code>```

I've read a little bit on CORS here Cross-Origin Resource Sharing (CORS) but all my attempts in getting this to work have failed.

Can any of you shed some light on this?

Thanks,

Manu

答:
Right, I got this working now. Both @FailedUnitTest and @Manav Mandal suggestions are worth considering. However, instead of using OAuth you can use an API key - which I found easier. Also, my proxy is my expressJS server.

On the server side you would have something along the following lines:

```<code>var express = require('express');
var axios = require('axios');

// meetup API
var instance = axios.create({
  baseURL: 'https://api.meetup.com/'
});

app.get('/anything', function(req, res) {
  const apiKey = 'yourKey';
  const isSigned = 'true';
  const photoHost = 'public';
  const pageCount = '20';
  const url = '/self/calendar?' + 'key=' + apiKey + '&sign=' + isSigned
+ '&photo-host=' + photoHost + '&page=' + pageCount + '';

  instance.get(url)
  .then(response => {
    return res.send(response.data);
  })
  .catch(e => {
    return e;
  })
});
</code>```

And the client side:

```<code>data () {
  return {
    cards: [],
    errors: []
  };
},
created () {
  axios.get('/anything')
  .then(response => {
    this.cards = response.data;
  })
  .catch(e => {
    this.errors.push(e);
  });
}
</code>```

Make sure both your server and your client run over the same port.

Regards,

Manu

Title: Preflight request in VueJS with axios

Body:
I am a bit stuck with getting a response from the meetup API. The error I am getting:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Here's my code:

var config = {'Access-Control-Allow-Headers': 'Authorization'}

axios.get(`https://api.meetup.com/self/calendar?&sign=true&photo-host=public&page=20`, {headers: config})
.then(response => {
  console.log(response.data)
  this.posts = response.data
})
.catch(e => {
  this.errors.push(e)
})

I've read a little bit on CORS here Cross-Origin Resource Sharing (CORS) but all my attempts in getting this to work have failed.

Can any of you shed some light on this?

Thanks,

Manu

Body:
Right, I got this working now. Both @FailedUnitTest and @Manav Mandal suggestions are worth considering. However, instead of using OAuth you can use an API key - which I found easier. Also, my proxy is my expressJS server.

On the server side you would have something along the following lines:

var express = require('express');
var axios = require('axios');

// meetup API
var instance = axios.create({
  baseURL: 'https://api.meetup.com/'
});

app.get('/anything', function(req, res) {
  const apiKey = 'yourKey';
  const isSigned = 'true';
  const photoHost = 'public';
  const pageCount = '20';
  const url = '/self/calendar?' + 'key=' + apiKey + '&sign=' + isSigned
+ '&photo-host=' + photoHost + '&page=' + pageCount + '';

  instance.get(url)
  .then(response => {
    return res.send(response.data);
  })
  .catch(e => {
    return e;
  })
});

And the client side:

data () {
  return {
    cards: [],
    errors: []
  };
},
created () {
  axios.get('/anything')
  .then(response => {
    this.cards = response.data;
  })
  .catch(e => {
    this.errors.push(e);
  });
}

Make sure both your server and your client run over the same port.

Regards,

Manu


问:
How to override scrollbar on a child element only
I have some custom scrollbar styles coming from external css file which I don't have any control of.

::-webkit-scrollbar {
    width: 5px;
}

I would like keep this custom scrollbar styles but override it within a container element. I've tried to target it different ways with no luck.

#test::-webkit-scrollbar {
    width: 10px !important;
}

http://jsfiddle.net/Lk5ct8ta/

答:
You're seeing the scrollbar on the body.  Your div#test is 2000px tall causing the body to overflow, so the body gets the scrollbar, but your custom styles are assigned to div#test which does not have overflowed content.

For example, here div#test is reduced in height and overflow set to scroll, with more content forcing it's content to overflow and the scrollbar styles to apply:

div{
    height:200px;
    overflow: scroll;
}

::-webkit-scrollbar {
    width: 5px;
}
::-webkit-scrollbar-thumb {
    background-color:#808080;
}

#test::-webkit-scrollbar {
    width: 10px !important;
}

#test::-webkit-scrollbar-thumb {
    background-color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.</div></code>```

Body:
You're seeing the scrollbar on the body.  Your div#test is 2000px tall causing the body to overflow, so the body gets the scrollbar, but your custom styles are assigned to div#test which does not have overflowed content.

For example, here div#test is reduced in height and overflow set to scroll, with more content forcing it's content to overflow and the scrollbar styles to apply:

div{
    height:200px;
    overflow: scroll;
}

::-webkit-scrollbar {
    width: 5px;
}
::-webkit-scrollbar-thumb {
    background-color:#808080;
}

#test::-webkit-scrollbar {
    width: 10px !important;
}

#test::-webkit-scrollbar-thumb {
    background-color:red;
}

<div id="test">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum facilis odit animi exercitationem sint, laborum fugiat voluptatem alias, nesciunt accusamus amet, perferendis doloribus vel id illo, quae est ipsam libero. Quisquam fugit dignissimos fugiat repellat. Rem animi, inventore velit corporis, tempora minus excepturi reprehenderit vero deleniti eveniet fugiat. Eveniet, asperiores.</div>