问:
Swift: NSCoding Implementation For An Object Without Instance Variables
Case in point: Beginner here please bear with me. I just learnt how to persist objects by encoding/decoding & archiving/unarchiving. Problem is now I want to persist a single UIImage. What is the recommended way to do that?

My current implementation that works but looks really weird:

```<code>class Photo: NSObject, NSCoding {

    static let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
    static let archiveURL = documentsDirectory.appendingPathComponent("photo")

    static func saveToDisk(selectedPhoto: UIImage) {
        NSKeyedArchiver.archiveRootObject(selectedPhoto, toFile: archiveURL.path)
    }

    static func loadFromDisk() -> UIImage? {
        guard let unarchivedPhoto = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? UIImage
            else {return nil}
        return unarchivedPhoto
    }

    func encode(with aCoder: NSCoder) {
    }

    convenience required init?(coder aDecoder: NSCoder) {
        self.init()
    }
}
</code>```

Is there a better way to do it? Many thanks.

答:
I completely misunderstood the use of NSCoding and Archive. "Archives provide a means to convert objects and values into an architecture-independent stream of bytes that preserves the identity of and the relationships between the objects and values."

So to save/load a UIImage simply:

```<code>// Define path
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
let photoURL = documentsDirectory.appendingPathComponent("photo.jpg")

// Convert selectedPhoto to Data and write to path
if let data = UIImageJPEGRepresentation(selectedPhoto, 1) {
    try? data.write(to: photoURL)
}

// Load Data and init UIImage
UIImage(contentsOfFile: photoURL.path)
</code>```

Body:
Case in point: Beginner here please bear with me. I just learnt how to persist objects by encoding/decoding & archiving/unarchiving. Problem is now I want to persist a single UIImage. What is the recommended way to do that?

My current implementation that works but looks really weird:

class Photo: NSObject, NSCoding {

    static let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
    static let archiveURL = documentsDirectory.appendingPathComponent("photo")

    static func saveToDisk(selectedPhoto: UIImage) {
        NSKeyedArchiver.archiveRootObject(selectedPhoto, toFile: archiveURL.path)
    }

    static func loadFromDisk() -> UIImage? {
        guard let unarchivedPhoto = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? UIImage
            else {return nil}
        return unarchivedPhoto
    }

    func encode(with aCoder: NSCoder) {
    }

    convenience required init?(coder aDecoder: NSCoder) {
        self.init()
    }
}

Is there a better way to do it? Many thanks.

Body:
I completely misunderstood the use of NSCoding and Archive. "Archives provide a means to convert objects and values into an architecture-independent stream of bytes that preserves the identity of and the relationships between the objects and values."

So to save/load a UIImage simply:

// Define path
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
let photoURL = documentsDirectory.appendingPathComponent("photo.jpg")

// Convert selectedPhoto to Data and write to path
if let data = UIImageJPEGRepresentation(selectedPhoto, 1) {
    try? data.write(to: photoURL)
}

// Load Data and init UIImage
UIImage(contentsOfFile: photoURL.path)


来源: stackexchange

问:
Is it OK to pass pandas GroupBy functions as argument in python function? and how should I pass their arguments?
I would like a function that takes a GroupBy operations such as mean(), max() as argument. I'm not sure as to how to include arguments for these functions. For example, in the case of quantile, there is the argument for telling which quantile, so in such case I should be able to provide this extra argument.

```<code>def compute_moment(data, moment = pd.core.groupby.GroupBy.mean):

    # This builds columns that we will use to group.
    group_data = data.rank(pct = True).round(1).add_suffix('_grouper')
    df = data.join(group_data)

    out = []
    for col in data.columns:
        #This is the key step, what if I want moment to be, say quantile(q = .7)?
        x = df.groupby(col+'_grouper').mean()[col] #no problem here
        y = moment(df.groupby(col+'_grouper'))['y']

        out += [pd.concat([x, y], axis=1)]

    return out

>>> out = compute_moment(data, pd.core.groupby.GroupBy.mean)

#output is a list of dataframes like this one:
>>> print out[0]

              rho         y
rho_grouper
0.0          0.024998  0.035754
0.1          0.099908  0.036522
0.2          0.199903  0.032319
0.3          0.299908  0.038726
0.4          0.399907  0.034523
0.5          0.499907  0.031123
0.6          0.599909  0.031352
0.7          0.699908  0.030531
0.8          0.799902  0.031277
0.9          0.899904  0.028456
1.0          0.974912  0.029378
</code>```

I would like to know how to do this correctly, or why not, a simpler alternative to have a function that applies these groupby operations, and lets me pass arguments if necessary.

By the way, is it OK to pass a pandas.GroupBy function as argument?

答:
It is ok to pass anything you want, if it works and serves you well.
You can pass function's agrs either as an additional dict/tuple argument, or just use *args and **kwargs.

still, it is unclear what you want to achieve here.
First, It looks like you're messing with data and df in your function.
Second, if I understand correctlly, pd.core.groupby.GroupBy is a class of a data-object - it is what you'll get from df.groupby, not the other way around. thus, you shouldn't use it here.

However, you can simply pass strings or agg functions as an arguement, and then apply them in .agg method:

```<code>def foo(df, agg='mean'):
    momentum = df.groupby('grouper').agg(agg)
</code>```

this way you can pass either strings( 'mean', 'sum') or arrays, or dicts, or even functions into aggarguement). Moreover, in this case array will result in getting all functions in the array applied to all columns, so you don't have to join and you don't have to loop.

To learn more on how groupby work, take a look here, for example:
https://chrisalbon.com/python/pandas_apply_operations_to_groups.html

ContentLicense: CC BY-SA 3.0

Body:
I would like a function that takes a GroupBy operations such as mean(), max() as argument. I'm not sure as to how to include arguments for these functions. For example, in the case of quantile, there is the argument for telling which quantile, so in such case I should be able to provide this extra argument.

def compute_moment(data, moment = pd.core.groupby.GroupBy.mean):

    # This builds columns that we will use to group.
    group_data = data.rank(pct = True).round(1).add_suffix('_grouper')
    df = data.join(group_data)

    out = []
    for col in data.columns:
        #This is the key step, what if I want moment to be, say quantile(q = .7)?
        x = df.groupby(col+'_grouper').mean()[col] #no problem here
        y = moment(df.groupby(col+'_grouper'))['y']

        out += [pd.concat([x, y], axis=1)]

    return out

>>> out = compute_moment(data, pd.core.groupby.GroupBy.mean)

#output is a list of dataframes like this one:
>>> print out[0]

              rho         y
rho_grouper
0.0          0.024998  0.035754
0.1          0.099908  0.036522
0.2          0.199903  0.032319
0.3          0.299908  0.038726
0.4          0.399907  0.034523
0.5          0.499907  0.031123
0.6          0.599909  0.031352
0.7          0.699908  0.030531
0.8          0.799902  0.031277
0.9          0.899904  0.028456
1.0          0.974912  0.029378

I would like to know how to do this correctly, or why not, a simpler alternative to have a function that applies these groupby operations, and lets me pass arguments if necessary.

By the way, is it OK to pass a pandas.GroupBy function as argument?

Body:
It is ok to pass anything you want, if it works and serves you well.
You can pass function's agrs either as an additional dict/tuple argument, or just use *args and **kwargs.

still, it is unclear what you want to achieve here.
First, It looks like you're messing with data and df in your function.
Second, if I understand correctlly, pd.core.groupby.GroupBy is a class of a data-object - it is what you'll get from df.groupby, not the other way around. thus, you shouldn't use it here.

However, you can simply pass strings or agg functions as an arguement, and then apply them in .agg method:

def foo(df, agg='mean'):
    momentum = df.groupby('grouper').agg(agg)

this way you can pass either strings( 'mean', 'sum') or arrays, or dicts, or even functions into aggarguement). Moreover, in this case array will result in getting all functions in the array applied to all columns, so you don't have to join and you don't have to loop.

To learn more on how groupby work, take a look here, for example:
https://chrisalbon.com/python/pandas_apply_operations_to_groups.html


问:
INT stays the same outside FOR loop
Function "f_vowels" works; it prints the number of common vowels the two strings have. The other one, "two_c", should work as well; it gives true if the two strings share at least two common letters in the same position. My problem is the third one, cause it should print those letters but always prints the message "Strings don't have 2 common letters". I think I know why: I'm increasing "dim" with a FOR loop, but the boolean function's still working with the original "dim". How do I fix this?</p>

```<code>#include <iostream>
#include <string.h>
using namespace std;

// functions' calls

void f_vowels(string, string);
bool two_c(int);
void print_2c(string, string, int, int);

// main
int main(){
string s1, s2;
int i, j, vowels;
int l1, l2;
char vow, c1, c2;

cout << "Enter your string: ";
getline(cin, s1);
cout << "\n";

cout << "Enter your string: ";
getline(cin, s2);
cout << "\n";

f_vowels(s1, s2);

int dim=0;
char common[dim];

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    common[dim++];
    }
}

two_c(dim);

if (two_c(dim)==true){
print_2c(s1, s2, l1, l2);
}

else cout << "Strings don't have 2 common letters.";

}

//functions

//common vowels

void f_vowels(string s1, string s2){

int l1=s1.length();
char c1[l1];
s1.copy(c1, l1);

int l2=s2.length();
char c2[l2];
s2.copy(c2, l2);

int vowels=0;
char vow[]={'a','e','i','o','u','A','E','I','O','U'};

for (int i=0; i<10; i++){
    for (int j=0; j<l1 && j<l2; j++){
    if (c1[j]=vow[i] && c2[j]==vow[i]){
        vowels++;
        }
      }
    }
    cout << vowels << "\n\n";
    }

 // true if strings have at least 2 common letters in the same position

bool two_c(int dim){

if (dim<2){
return false;
}
else return true;

}

// print boolean function

void print_2c(string s1, string s2, int l1, int l2){

int dim=0;
char common[dim];

    for (int i=0; i<l1 && i<l2; i++){
        for (int j=0; j<l1 && j<l2; j++){
            if (s1[i]==s2[i])
            common[j]=s1[i];
            cout << common[j] << "is a common letter. \n";
            }
      }
}
</code>```

答:
Couple issues here.

This logic:

```<code>int dim=0;
char common[dim];

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    common[dim++];
    }
}
</code>```

...Does nothing. common[dim++] performs a lookup and throws out the value because it’s not getting assigned to anything. What it seems like you’re trying is to determine the the array size dim or at least increment it’s size based on the number of expected matches. To do that, you must first calculate dim before you declare you’re array. So:

```<code>int dim=0;

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    dim++;
    }
}

char common[dim]; //won’t compile
</code>```

This approach will not compile though because the compiler can’t know the size of dim until the program runs. You’ll need to dynamically allocate the array using ‘new’ you if you still think an array is the way to do this (consider std::vector).

```<code>int dim=0;

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    dim++;
    }
}

char* common = new char[dim];
</code>```

ALSO:

Regarding

```<code>void print_2c(string s1, string s2, int l1, int l2){

 int dim=0;
char common[dim]; //a local array, not what you e setup

for (int i=0; i<l1 && i<l2; i++){
    for (int j=0; j<l1 && j<l2; j++){
        if (s1[i]==s2[i])
        common[j]=s1[i];
        cout << common[j] << "is a common letter. \n";
        }
  }
}
</code>```

Whatever logic is running here is being performed on a local and empty array called common, different from the common you’ve created prior to this call. It seems you want access to you array. You’ll need to pass in common in some form (probably as an argument) and then you’ll be able to use what you’ve setup. So:

```<code>void print_2c(string s1, string s2, int l1, int l2, char* common, const int dim){

for (int i=0; i<l1 && i<l2; i++){
    for (int j=0; j<l1 && j<l2; j++){
        if (s1[i]==s2[i])
        common[j]=s1[i];
        cout << common[j] << "is a common letter. \n";
        }
  }
}
</code>```

And called as:

```<code>print_2c(s1,s2,l1,l2,common,dim);
</code>```

LASTLY:
this logic:

```<code>for (int i=0; i<l1 && i<l2; i++){
    for (int j=0; j<l1 && j<l2; j++){
        if (s1[i]==s2[i])
        common[j]=s1[i];
        cout << common[j] << "is a common letter. \n";
        }
  }
</code>```

Probably isn’t doing what you want.  In the inner loop, when the char in s1 matches s2, all values in common up to min(l1,l2) are set to that char, and it’ll just print out “is a common letter” for that char repeatedly. Common will stay filled with all entries being the same char until the next match when all values get overwritten and set to the new char value. Not what you want.

If common instead was an array of bools and each index represented an eligible matching character (ie vowel), you could do something like:

```<code>for (int i=0; i<l1 && i<l2; i++){
    //no inner loop needed
        if (s1[i]==s2[i])
        common[s1[i]]=true;
        cout << s1[i] << "is a common letter. \n";
        }
  }
</code>```

Title: INT stays the same outside FOR loop

Body:
Function "f_vowels" works; it prints the number of common vowels the two strings have. The other one, "two_c", should work as well; it gives true if the two strings share at least two common letters in the same position. My problem is the third one, cause it should print those letters but always prints the message "Strings don't have 2 common letters". I think I know why: I'm increasing "dim" with a FOR loop, but the boolean function's still working with the original "dim". How do I fix this?

#include <iostream>
#include <string.h>
using namespace std;

// functions' calls

void f_vowels(string, string);
bool two_c(int);
void print_2c(string, string, int, int);

// main
int main(){
string s1, s2;
int i, j, vowels;
int l1, l2;
char vow, c1, c2;

cout << "Enter your string: ";
getline(cin, s1);
cout << "\n";

cout << "Enter your string: ";
getline(cin, s2);
cout << "\n";

f_vowels(s1, s2);

int dim=0;
char common[dim];

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    common[dim++];
    }
}

two_c(dim);

if (two_c(dim)==true){
print_2c(s1, s2, l1, l2);
}

else cout << "Strings don't have 2 common letters.";

}

//functions

//common vowels

void f_vowels(string s1, string s2){

int l1=s1.length();
char c1[l1];
s1.copy(c1, l1);

int l2=s2.length();
char c2[l2];
s2.copy(c2, l2);

int vowels=0;
char vow[]={'a','e','i','o','u','A','E','I','O','U'};

for (int i=0; i<10; i++){
    for (int j=0; j<l1 && j<l2; j++){
    if (c1[j]=vow[i] && c2[j]==vow[i]){
        vowels++;
        }
      }
    }
    cout << vowels << "\n\n";
    }

 // true if strings have at least 2 common letters in the same position

bool two_c(int dim){

if (dim<2){
return false;
}
else return true;

}

// print boolean function

void print_2c(string s1, string s2, int l1, int l2){

int dim=0;
char common[dim];

    for (int i=0; i<l1 && i<l2; i++){
        for (int j=0; j<l1 && j<l2; j++){
            if (s1[i]==s2[i])
            common[j]=s1[i];
            cout << common[j] << "is a common letter. \n";
            }
      }
}

Body:
Couple issues here.

This logic:

int dim=0;
char common[dim];

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    common[dim++];
    }
}

...Does nothing. common[dim++] performs a lookup and throws out the value because it’s not getting assigned to anything. What it seems like you’re trying is to determine the the array size dim or at least increment it’s size based on the number of expected matches. To do that, you must first calculate dim before you declare you’re array. So:

int dim=0;

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    dim++;
    }
}

char common[dim]; //won’t compile

This approach will not compile though because the compiler can’t know the size of dim until the program runs. You’ll need to dynamically allocate the array using ‘new’ you if you still think an array is the way to do this (consider std::vector).

int dim=0;

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    dim++;
    }
}

char* common = new char[dim];

ALSO:

Regarding

void print_2c(string s1, string s2, int l1, int l2){

 int dim=0;
char common[dim]; //a local array, not what you e setup

for (int i=0; i<l1 && i<l2; i++){
    for (int j=0; j<l1 && j<l2; j++){
        if (s1[i]==s2[i])
        common[j]=s1[i];
        cout << common[j] << "is a common letter. \n";
        }
  }
}

Whatever logic is running here is being performed on a local and empty array called common, different from the common you’ve created prior to this call. It seems you want access to you array. You’ll need to pass in common in some form (probably as an argument) and then you’ll be able to use what you’ve setup. So:

void print_2c(string s1, string s2, int l1, int l2, char* common, const int dim){

for (int i=0; i<l1 && i<l2; i++){
    for (int j=0; j<l1 && j<l2; j++){
        if (s1[i]==s2[i])
        common[j]=s1[i];
        cout << common[j] << "is a common letter. \n";
        }
  }
}

And called as:

print_2c(s1,s2,l1,l2,common,dim);

LASTLY:
this logic:

for (int i=0; i<l1 && i<l2; i++){
    for (int j=0; j<l1 && j<l2; j++){
        if (s1[i]==s2[i])
        common[j]=s1[i];
        cout << common[j] << "is a common letter. \n";
        }
  }

Probably isn’t doing what you want.  In the inner loop, when the char in s1 matches s2, all values in common up to min(l1,l2) are set to that char, and it’ll just print out “is a common letter” for that char repeatedly. Common will stay filled with all entries being the same char until the next match when all values get overwritten and set to the new char value. Not what you want.

If common instead was an array of bools and each index represented an eligible matching character (ie vowel), you could do something like:

for (int i=0; i<l1 && i<l2; i++){
    //no inner loop needed
        if (s1[i]==s2[i])
        common[s1[i]]=true;
        cout << s1[i] << "is a common letter. \n";
        }
  }


问:
Query condition missed key schema element : Validation Error
I am trying to query dynamodb using the following code:

```<code>const AWS = require('aws-sdk');

let dynamo = new AWS.DynamoDB.DocumentClient({
  service: new AWS.DynamoDB(
    {
      apiVersion: "2012-08-10",
      region: "us-east-1"
    }),
  convertEmptyValues: true
});

dynamo.query({
  TableName: "Jobs",
  KeyConditionExpression: 'sstatus = :st',
  ExpressionAttributeValues: {
    ':st': 'processing'
  }
}, (err, resp) => {
  console.log(err, resp);
});
</code>```

When I run this, I get an error saying:

```<code>ValidationException: Query condition missed key schema element: id
</code>```

I do not understand this. I have defined id as the partition key for the jobs table and need to find all the jobs that are in processing status.

答:
You're trying to run a query using a condition that does not include the primary key. This is how queries work in DynamoDB. You would need to do a scan for the info in your case, however, I don't think that is the best option.

I think you want to set up a global secondary index and use that to query for the processing status.

Body:
I am trying to query dynamodb using the following code:

const AWS = require('aws-sdk');

let dynamo = new AWS.DynamoDB.DocumentClient({
  service: new AWS.DynamoDB(
    {
      apiVersion: "2012-08-10",
      region: "us-east-1"
    }),
  convertEmptyValues: true
});

dynamo.query({
  TableName: "Jobs",
  KeyConditionExpression: 'sstatus = :st',
  ExpressionAttributeValues: {
    ':st': 'processing'
  }
}, (err, resp) => {
  console.log(err, resp);
});

When I run this, I get an error saying:

ValidationException: Query condition missed key schema element: id

I do not understand this. I have defined id as the partition key for the jobs table and need to find all the jobs that are in processing status.


问:
Don't want icons on my TabWidget
I'm still learning about Android, and while playing around with TabHost and TabWidget, I can't help but notice that there's no option to turn off the icons.

It's eating up valuable space even when I don't actually set an icon into the TabSpec. Is there any way to reduce the height of the tab bar? It's really hard to find small icons (at 3 different sizes) that perfectly fits what I intended those tabs to contain. I have zero skills with graphics.

答: getTabHost().getTabWidget().getChildAt(0).setHeight(10) method we can set the height for the tabs

ContentLicense: CC BY-SA 2.5

Title: Don't want icons on my TabWidget


问:
MySQL SSH "support"
In some official Oracle material I am reading

"MySQL supports SSH (secure shell) connection to a remote MySQL server.

This requires:

An SSH client on the client machine

Port forwarding through an SSH tunnel from the client to the server
A client application on the machine with the SSH client
When you complete the setup, you have a local port that hosts an SSH connection to MySQL, encrypted using SSH."

Question

What an application (MySQL) could "support" on SSH?
If I using an SSH client, and correctly configure port forwarding, is not the SSH transparent for MySQL?  (With other words, MySQL have nothing to ti with this)

I am not a Linux guru, missing I something?

答:
Perhaps you are talking about SSH Tunneling?  You can use SSH to create your own encrypted connection from a program (client) on one computer to a program (server) on another computer.  And as you mentioned, it works for any client/server programs, not just MySQL/mysqld.

Here is an exiting SO answer that shows you how it's done with MySQL and SSH:

MySQL connection over SSH tunnel - how to specify other MySQL server?

Title: MySQL SSH "support"


问:
Copy Cell's Formula result as Value into same Cell
I have this code I have written to find values over 0 in a particular column:

```<code>Private Sub CommandButton1_Click()

    a = Worksheets("Sheet1").Cells(Rows.Count, 3).End(xlUp).Row

    For i = 4 To a
        If Worksheets("sheet1").Cells(i, 3).Value > 0 Then
            Worksheets("sheet1").Cells(i, 3).Copy
            Worksheets("sheet1").Cells(1, 3).PasteSpecial xlPasteValues
        End If
    Next

    Application.CutCopyMode = False

End Sub
</code>```

My problem is in the copy and paste value.  I need to just copy the cell and paste value in that same cell.  for example, if the macro reads in cell c5 that the total is greater then 0, then it copies cell c5 and paste value in c5.

How do I fix the paste value line to paste the value in the same cell it copied?

答:
Instead of using copy/paste, just do it like this:</p>

```<code>Worksheets("sheet1").Cells(i, 3).Value = Worksheets("sheet1").Cells(i, 3).Value
</code>```

Body:
I have this code I have written to find values over 0 in a particular column:

Private Sub CommandButton1_Click()

    a = Worksheets("Sheet1").Cells(Rows.Count, 3).End(xlUp).Row

    For i = 4 To a
        If Worksheets("sheet1").Cells(i, 3).Value > 0 Then
            Worksheets("sheet1").Cells(i, 3).Copy
            Worksheets("sheet1").Cells(1, 3).PasteSpecial xlPasteValues
        End If
    Next

    Application.CutCopyMode = False

End Sub

My problem is in the copy and paste value.  I need to just copy the cell and paste value in that same cell.  for example, if the macro reads in cell c5 that the total is greater then 0, then it copies cell c5 and paste value in c5.

How do I fix the paste value line to paste the value in the same cell it copied?

Body:
Instead of using copy/paste, just do it like this:

Worksheets("sheet1").Cells(i, 3).Value = Worksheets("sheet1").Cells(i, 3).Value


问:
Usage of Kotlin Coroutines
I have house simulation where are various types of devices. These devices are generating events after some time period.

So I've decided to use new thread everytime when device (wash machine) is doing something (washing clothes) that is blocking for some time (eg. 2 minutes), so main thread is not blocked. This thread only sleeps for that period (2 minutes) and afterwards makes callback that washing is done.

Is it possible to use for this corountines in Kotlin? Would it be better?

答: If the rest of your application uses coroutines, it would make sense to do this with coroutines as well. If it doesn't, I don't see any benefit. However, you can use a ScheduledExecutorService instead of doing it manually.

Title: Usage of Kotlin Coroutines


问:
OpenCart 3.0 (3.x) + Authorize.net - how to disable ONLY the Authorize.net E-mail?
We currently accept credit cards by phone (entering the order info into the Virtual Terminal) as well as on the website (OpenCart, using the built-in Authorize.net AIM module).

Problem: when order is placed on website, the customer receives 2 E-mails - 1 from our site, 1 from Authorize. The Authorize E-mail, being plaintext, looks ugly AF, and my boss wants to have it disabled.

Attempt # 1: looked in the Authorize.net AIM plugin/module settings. No such option.

Attempt # 2: in the Authorize.net account, under "Settings -> E-mail Receipt", there is a checkbox "Email transaction receipt to customer (if email address is provided)".

Result #2:  unfortunately, this disables ALL transaction E-mails - from website transactions (OK) and from Virtual Terminal phone-order transactions (NOT cool). We have to provide an E-mail receipt to phone customers.

Attempt #3: in the OpenCart system, editing file:

```<code>catalog/controller/extension/payment/authorizenet_aim.php
</code>```

to comment out the line

```<code>$data['x_email'] = $order_info['email'];
</code>```

Result #3: during checkout, even if a valid E-mail is entered, upon trying to submit the order, the "Email address is required" error message appears.

So...
Can't disable it in Authorize plugin/module in OpenCart.
Can't disable it in Authorize Account Settings.
Can't just delete the E-mail from the array of data that OpenCart collects during checkout.

How can I disable the Authorize.net E-mail (and ONLY the Authorize.net E-mail, I still want the website receipt to go out) on a site built on OpenCart 3.0?

答:
Found the solution (via Authorize.net Developers Forum). Simpler than I expected:

Open file: public_html/catalog/controller/extension/payment/authorizenet_aim.php

Find line: $data['x_relay_response'] = 'false';

Add after: $data['x_email_customer'] = 'false';

This allows the checkout process to complete without errors, and sends the transaction to Authorize.net along with the instruction to not E-mail the customer.

Body:
We currently accept credit cards by phone (entering the order info into the Virtual Terminal) as well as on the website (OpenCart, using the built-in Authorize.net AIM module).

Problem: when order is placed on website, the customer receives 2 E-mails - 1 from our site, 1 from Authorize. The Authorize E-mail, being plaintext, looks ugly AF, and my boss wants to have it disabled.

Attempt # 1: looked in the Authorize.net AIM plugin/module settings. No such option.

Attempt # 2: in the Authorize.net account, under "Settings -> E-mail Receipt", there is a checkbox "Email transaction receipt to customer (if email address is provided)".

Result #2:  unfortunately, this disables ALL transaction E-mails - from website transactions (OK) and from Virtual Terminal phone-order transactions (NOT cool). We have to provide an E-mail receipt to phone customers.

Attempt #3: in the OpenCart system, editing file:

catalog/controller/extension/payment/authorizenet_aim.php

to comment out the line

$data['x_email'] = $order_info['email'];

Result #3: during checkout, even if a valid E-mail is entered, upon trying to submit the order, the "Email address is required" error message appears.

So...
Can't disable it in Authorize plugin/module in OpenCart.
Can't disable it in Authorize Account Settings.
Can't just delete the E-mail from the array of data that OpenCart collects during checkout.

How can I disable the Authorize.net E-mail (and ONLY the Authorize.net E-mail, I still want the website receipt to go out) on a site built on OpenCart 3.0?


问:
Callback becomes null after being passed as function parameter
I have 2 functions funcA and funcB. funcA calls funcB and
passes a callback. In funcA the callback (cb) is well-defined, but
funcB gets undefined.

Here is the code:

```<code>MyClass.prototype.funcA= function (a) {
    return new Promise((resolve, reject) => {
        let cb = (reading) => {
            console.log("Will resolve:" + reading);
            resolve(funcC(reading));
        };

        if (cb)
            console.log("cb ok");
        else
            console.log("cb ko");

        this.funcB(a, cb);
    });
}

MyClass.prototype.funcB= function (a, callback, c) {
    console.log("funcB");
    console.log("callback: " + callback);
    this.device.send(a, response => {
        console.log("CB ?");
        if (callback) {
            console.log("CB !");
            callback(response);
        }
        else {
            console.log("no callback");
            console.log(callback);
        }
    });

    if (c) {
        funcB([0x00, 0x00]);
    }
};
</code>```

And here is the console output:

```<code>cb ok
funcB
callback: (reading) => {
            console.log("Will resolve:" + reading);
            resolve(funcC(reading));
        }
CB ?
no callback
undefined
</code>```

Note that in the code base I have other functions that calls funcB and funcB successfully calls the callback.

答:
I've found the issue.

this.device.send() does not call the callback it is given, but the callback given in a previous call. As it was not documented I had to go 3 layers down to find the implementation...

So the solution is to call funcB() until the callback you want is called.

Body:
I have 2 functions funcA and funcB. funcA calls funcB and
passes a callback. In funcA the callback (cb) is well-defined, but
funcB gets undefined.

Here is the code:

MyClass.prototype.funcA= function (a) {
    return new Promise((resolve, reject) => {
        let cb = (reading) => {
            console.log("Will resolve:" + reading);
            resolve(funcC(reading));
        };

        if (cb)
            console.log("cb ok");
        else
            console.log("cb ko");

        this.funcB(a, cb);
    });
}

MyClass.prototype.funcB= function (a, callback, c) {
    console.log("funcB");
    console.log("callback: " + callback);
    this.device.send(a, response => {
        console.log("CB ?");
        if (callback) {
            console.log("CB !");
            callback(response);
        }
        else {
            console.log("no callback");
            console.log(callback);
        }
    });

    if (c) {
        funcB([0x00, 0x00]);
    }
};

And here is the console output:

cb ok
funcB
callback: (reading) => {
            console.log("Will resolve:" + reading);
            resolve(funcC(reading));
        }
CB ?
no callback
undefined

Note that in the code base I have other functions that calls funcB and funcB successfully calls the callback.


问:
Remove the strong name from 3rd party assemblies?
How can I remove a strong name from a 3rd party assembly that I do not have the source code for, maybe using ilasm/ildasm (since it is possible to add a strong name using ilasm/ildasm)?

Generally, it seems to be possible, since this tool seems to be able to do this.

答:
This is to remove strong name validation, not remove the strong name signature, however searches for strongname validation errors seem to route to this question so this is not irrelevant.

sn.exe can be used to disable strongname validation (sn.exe can be accessed via visual studio developer command prompt)

To disable strongname validation for all assemblies with a given public key token:

```<code>sn.exe -Vr *,<public key hex token>
</code>```

or to disable validation for all assemblies with any public key:

```<code>sn.exe -Vr *,*
</code>```

Body:
This is to remove strong name validation, not remove the strong name signature, however searches for strongname validation errors seem to route to this question so this is not irrelevant.

sn.exe can be used to disable strongname validation (sn.exe can be accessed via visual studio developer command prompt)

To disable strongname validation for all assemblies with a given public key token:

sn.exe -Vr *,<public key hex token>

or to disable validation for all assemblies with any public key:

sn.exe -Vr *,*


问:
Match exact phrase within a string in Python
I'm trying to determine whether a substring is in a string.
The issue I'm running into is that I don't want my function to return True if the substring is found within another word in the string.

For example: if the substring is; "Purple cow"
and the string is; "Purple cows make the best pets."
This should return False. Since cow isn't plural in the substring.

And if the substring was; "Purple cow"
and the string was; "Your purple cow trampled my hedge!"
would return True

My code looks something like this:

```<code>def is_phrase_in(phrase, text):
    phrase = phrase.lower()
    text = text.lower()

    return phrase in text

text = "Purple cows make the best pets!"
phrase = "Purple cow"
print(is_phrase_in(phrase, text)
</code>```

In my actual code I clean up unnecessary punctuation and spaces in 'text' before comparing it to phrase, but otherwise this is the same.
I've tried using re.search, but I don't understand regular expressions very well yet and have only gotten the same functionality from them as in my example.

Thanks for any help you can provide!

答:
Regular Expressions should do the trick    </p>

```<code>import re

def is_phrase_in(phrase, text):
    phrase = phrase.lower()
    text = text.lower()
    if re.findall('\\b'+phrase+'\\b', text):
        found = True
    else:
        found = False
    return found
</code>```

Body:
I'm trying to determine whether a substring is in a string.
The issue I'm running into is that I don't want my function to return True if the substring is found within another word in the string.

For example: if the substring is; "Purple cow"
and the string is; "Purple cows make the best pets."
This should return False. Since cow isn't plural in the substring.

And if the substring was; "Purple cow"
and the string was; "Your purple cow trampled my hedge!"
would return True

My code looks something like this:

def is_phrase_in(phrase, text):
    phrase = phrase.lower()
    text = text.lower()

    return phrase in text

text = "Purple cows make the best pets!"
phrase = "Purple cow"
print(is_phrase_in(phrase, text)

In my actual code I clean up unnecessary punctuation and spaces in 'text' before comparing it to phrase, but otherwise this is the same.
I've tried using re.search, but I don't understand regular expressions very well yet and have only gotten the same functionality from them as in my example.

Thanks for any help you can provide!

Body:
Regular Expressions should do the trick

import re

def is_phrase_in(phrase, text):
    phrase = phrase.lower()
    text = text.lower()
    if re.findall('\\b'+phrase+'\\b', text):
        found = True
    else:
        found = False
    return found


问:
Singleton class that show a toast in different activities using resources efficiently
I have a singleton class (let's call it: SingleWorker) that it's used in multiple activities. Depending on the case it shows a toast or a progress dialog if a task is being done. I have 2 ways in my mind on how to do this:

1) creating a separate method in the singleton - SingleWorker, that will get the context of the activity before the toast/progress is shown

2) in the extended Application singleton, I will store, every time I enter a new activity (and on its onResume) its instance, that i will then use that in the SingleWorker singleton.

Which one is the better choice (I guess the first one), can I do it better? I tried to find an efficient answer by myself, but I need a direction or a tip. Any idea, suggestion, advice or link is gratefully received. Thanks for reading !

答:
Toasts are not bound to a specific Activity in terms of their visibility.
That's one of the reasons why they where somewhat 'deprecated' (not officially, that's just my interpretation of Google's design guidelines and their own apps) in favor of the Snackbar which is bound to a specific View.

I see no advantage in using an activity context instead of the application context to create a Toast.

Vice versa, when letting your Singleton hold a reference to activity contexts, you might very easily create a memory leak by holding on to an already destroyed Activity.
You could just pass in the Activity as a method parameter, but that might not be so convenient (e.g. calling that method from a class other than Activity).

Long story short: I would suggest to let your SingleWorker have a reference to the application context to create the Toast.


问:
Parse polish date with time to ISO format in Javascript
I have date 14.05.2017 15:32 its polish format of date and time dd.MM.yyyy HH:mm when im using moment library with locales it always set time to default value of 00:00:00.

Here is example code that i've tried to use
Fiddle

console.log(moment('14.05.2017 15:32').format('dd.MM.yyyy HH:mm'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script></code>```

Any other suggestions how to parse it?
Expected result:

```<code>2017-05-14T15:32:00.004Z
</code>```

答:
You should replace the 'pl' argument with the explicit format to parse and add the argument to the format method to display it in the same format:

```<code>moment('14.05.2017 15:32','DD.MM.YYYY HH:mm').format('DD.MM.YYYY HH:mm')
</code>```

Fiddle here

Body:
I have date 14.05.2017 15:32 its polish format of date and time dd.MM.yyyy HH:mm when im using moment library with locales it always set time to default value of 00:00:00.

Here is example code that i've tried to use
Fiddle

console.log(moment('14.05.2017 15:32').format('dd.MM.yyyy HH:mm'))

Any other suggestions how to parse it?
Expected result:

2017-05-14T15:32:00.004Z

Body:
You should replace the 'pl' argument with the explicit format to parse and add the argument to the format method to display it in the same format:

moment('14.05.2017 15:32','DD.MM.YYYY HH:mm').format('DD.MM.YYYY HH:mm')

Fiddle here


问:
How to Encrypt a n byte string with a n byte encryption result using Rijndael encryption C#
I'm having a issue. This Encrypts my name perfectly. My name comes in as 4 long so the name might come in as "John" but then it Encrypts it as abcasdlkj123908=! (something like that) is there a way I can have it encrypt something instead like w124 that is the same length of the initial variable string it encrpyted? Also what if the name comes in as Darryl and is 6 long ? I need to deal with that too</p>

```<code>public string EncryptAName(string someName)
    {
        Rijndael rinj = new RijndaelManaged();
        string encryptionKey = "HERPDERP";
        rinj.Mode = CipherMode.CBC;
        rinj.Padding = PaddingMode.PKCS7;
        rinj.KeySize = 0x80;    // Decimal: 128
        rinj.BlockSize = 0x80;
        byte[] passwordBytes = Encoding.UTF8.GetBytes(encryptionKey);
        byte[] encryptionKeyBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        int passwordBytesLength = passwordBytes.Length;

        if (passwordBytesLength > encryptionKeyBytes.Length)
        {
            passwordBytesLength = encryptionKeyBytes.Length;
        }

        Array.Copy(passwordBytes, encryptionKeyBytes, passwordBytesLength);

        rinj.Key = encryptionKeyBytes;
        rinj.IV = encryptionKeyBytes;

        ICryptoTransform ict = rinj.CreateEncryptor();
        byte[] someNameByte = Encoding.UTF8.GetBytes(someName);
        someName = Convert.ToBase64String(ict.TransformFinalBlock(someNameByte, 0, someNameByte.Length));

        return someName;
    }
</code>```

答:
If you don't mind encoding, you can do it just by XOR ing your string bytes with some very big key (which is greater by length). Small will do too, but it will be less secure:</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        var input = "Daniel";
        var key = new byte[] {5, 6};
        //encode
        var res = CycleXor(input, key);

        Debug.Assert(input.Length == res.Length);
        Console.WriteLine(res);
        //decode
        res = CycleXor(res, key);
    }

    private static string CycleXor(string input, byte[] key)
    {
        return Encoding.ASCII.GetString(CycleXor(Encoding.ASCII.GetBytes(input), key));
    }

    private static byte[] CycleXor(byte[] input, byte[] key)
    {
        if(input == null) throw new ArgumentNullException(nameof(input));
        if(key == null) throw new ArgumentNullException(nameof(input));
        if (input.Length == 0 || key.Length == 0)
            return input;

        int idx = 0;
        byte[] result = new byte[input.Length];
        while (idx<input.Length)
        {
            result[idx] = (byte)(input[idx] ^ key[idx % key.Length]);
            idx++;
        }
        return result;
    }
}
</code>```

Body:
I'm having a issue. This Encrypts my name perfectly. My name comes in as 4 long so the name might come in as "John" but then it Encrypts it as abcasdlkj123908=! (something like that) is there a way I can have it encrypt something instead like w124 that is the same length of the initial variable string it encrpyted? Also what if the name comes in as Darryl and is 6 long ? I need to deal with that too

public string EncryptAName(string someName)
    {
        Rijndael rinj = new RijndaelManaged();
        string encryptionKey = "HERPDERP";
        rinj.Mode = CipherMode.CBC;
        rinj.Padding = PaddingMode.PKCS7;
        rinj.KeySize = 0x80;    // Decimal: 128
        rinj.BlockSize = 0x80;
        byte[] passwordBytes = Encoding.UTF8.GetBytes(encryptionKey);
        byte[] encryptionKeyBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        int passwordBytesLength = passwordBytes.Length;

        if (passwordBytesLength > encryptionKeyBytes.Length)
        {
            passwordBytesLength = encryptionKeyBytes.Length;
        }

        Array.Copy(passwordBytes, encryptionKeyBytes, passwordBytesLength);

        rinj.Key = encryptionKeyBytes;
        rinj.IV = encryptionKeyBytes;

        ICryptoTransform ict = rinj.CreateEncryptor();
        byte[] someNameByte = Encoding.UTF8.GetBytes(someName);
        someName = Convert.ToBase64String(ict.TransformFinalBlock(someNameByte, 0, someNameByte.Length));

        return someName;
    }

Body:
If you don't mind encoding, you can do it just by XOR ing your string bytes with some very big key (which is greater by length). Small will do too, but it will be less secure:

class Program
{
    static void Main(string[] args)
    {
        var input = "Daniel";
        var key = new byte[] {5, 6};
        //encode
        var res = CycleXor(input, key);

        Debug.Assert(input.Length == res.Length);
        Console.WriteLine(res);
        //decode
        res = CycleXor(res, key);
    }

    private static string CycleXor(string input, byte[] key)
    {
        return Encoding.ASCII.GetString(CycleXor(Encoding.ASCII.GetBytes(input), key));
    }

    private static byte[] CycleXor(byte[] input, byte[] key)
    {
        if(input == null) throw new ArgumentNullException(nameof(input));
        if(key == null) throw new ArgumentNullException(nameof(input));
        if (input.Length == 0 || key.Length == 0)
            return input;

        int idx = 0;
        byte[] result = new byte[input.Length];
        while (idx<input.Length)
        {
            result[idx] = (byte)(input[idx] ^ key[idx % key.Length]);
            idx++;
        }
        return result;
    }
}


答:
Since your phrase can have multiple words, doing a simple split and intersect won't work. I'd go with regex for this one:</p>

```<code>import re

def is_phrase_in(phrase, text):
    return re.search(r"\b{}\b".format(phrase), text, re.IGNORECASE) is not None

phrase = "Purple cow"

print(is_phrase_in(phrase, "Purple cows make the best pets!"))   # False
print(is_phrase_in(phrase, "Your purple cow trampled my hedge!"))  # True
</code>```

Title: Match exact phrase within a string in Python

Body:
Since your phrase can have multiple words, doing a simple split and intersect won't work. I'd go with regex for this one:

import re

def is_phrase_in(phrase, text):
    return re.search(r"\b{}\b".format(phrase), text, re.IGNORECASE) is not None

phrase = "Purple cow"

print(is_phrase_in(phrase, "Purple cows make the best pets!"))   # False
print(is_phrase_in(phrase, "Your purple cow trampled my hedge!"))  # True


问:
Merging two dataframes with different keys of different data types in R
I have two dataframes

master

```<code>P_ID      C_ID   D_ID ...
520686814 1222   1281
336892632 1232   8181 ...
</code>```

and

```<code>str(master$P_ID) : integer64 [1:12000] 520686814 336892632 140101133 85433815 339389222
</code>```

Also

Dimension

```<code>p_id      year  gender state
520686814 2017  1      A
336892632 2016  2      B
</code>```

and

```<code>str(Dimension$p_id) : num [1:9915433] 520686814 336892632 636774575 248552775...
</code>```

So essentially I can see that there are records matching in both dataframes for a p_id. So I do a join using

```<code>joined <- merge(master, Dimension, by.x = "P_ID", by.y = "p_id")
</code>```

And to my surprise, I get no records in joined. Does the join don't work on different data types even though they work while subsetting?

答:
Assuming you're not performing any mathematical operations on them you could (some would argue should) store IDs as character strings instead. It's my understanding that this is a safer approach. Additionally, merging on strings is faster than merging on numerics.

```<code>master$P_ID <- as.character(master$P_ID)
Dimension$p_id <- as.character(Dimension$p_id)
joined <- merge(master, Dimension, by.x = "P_ID", by.y = "p_id")
</code>```

The code above should get it done. It doesn't answer the question of why your merge fails but does provide you with a workaround.

Body:
I have two dataframes

master

P_ID      C_ID   D_ID ...
520686814 1222   1281
336892632 1232   8181 ...

and

str(master$P_ID) : integer64 [1:12000] 520686814 336892632 140101133 85433815 339389222

Also

Dimension

p_id      year  gender state
520686814 2017  1      A
336892632 2016  2      B

and

str(Dimension$p_id) : num [1:9915433] 520686814 336892632 636774575 248552775...

So essentially I can see that there are records matching in both dataframes for a p_id. So I do a join using

joined <- merge(master, Dimension, by.x = "P_ID", by.y = "p_id")

And to my surprise, I get no records in joined. Does the join don't work on different data types even though they work while subsetting?

Body:
Assuming you're not performing any mathematical operations on them you could (some would argue should) store IDs as character strings instead. It's my understanding that this is a safer approach. Additionally, merging on strings is faster than merging on numerics.

master$P_ID <- as.character(master$P_ID)
Dimension$p_id <- as.character(Dimension$p_id)
joined <- merge(master, Dimension, by.x = "P_ID", by.y = "p_id")

The code above should get it done. It doesn't answer the question of why your merge fails but does provide you with a workaround.


问:
Skewed background just CSS
need divide background on two parts:

I have:

body {
  background: #b6da8c;
  overflow: hidden;
}

body:before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 50%;
  height: 100%;
  background: #005370;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skewX(-10deg);
  -ms-transform: skewX(-10deg);
  transform: skewX(-10deg);
  z-index: -1;
}```

As you can see there is divided into 3 actually, how to change it to have 2 as on image?

答:
Really simple fix without too much modification to your code. Just push the element off the screen and increase its width.</p>

```<code>body {
background: #b6da8c;
overflow: hidden;
}

body:before {
  content: '';
  position: absolute;
  top: 0; right: -200px;
  width: 60%; height: 100%;
  background: #005370;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skewX(-10deg);
  -ms-transform: skewX(-10deg);
  transform: skewX(-10deg);
  z-index: -1;
}
</code>```

Title: Skewed background just CSS

Body:
need divide background on two parts:

I have:

body {
  background: #b6da8c;
  overflow: hidden;
}

body:before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 50%;
  height: 100%;
  background: #005370;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skewX(-10deg);
  -ms-transform: skewX(-10deg);
  transform: skewX(-10deg);
  z-index: -1;
}

As you can see there is divided into 3 actually, how to change it to have 2 as on image?

Body:
Really simple fix without too much modification to your code. Just push the element off the screen and increase its width.

body {
background: #b6da8c;
overflow: hidden;
}

body:before {
  content: '';
  position: absolute;
  top: 0; right: -200px;
  width: 60%; height: 100%;
  background: #005370;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skewX(-10deg);
  -ms-transform: skewX(-10deg);
  transform: skewX(-10deg);
  z-index: -1;
}


答:
You could change the transform-origin to be at the bottom.

body {
  background: #b6da8c;
  overflow: hidden;
}

body:before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 50%;
  height: 100%;
  background: #005370;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skewX(-10deg);
  -ms-transform: skewX(-10deg);
  transform: skewX(-10deg);
  z-index: -1;
  transform-origin: bottom;
}```

Title: Skewed background just CSS


问:
How to correctly load multiple model on an ember.js view
(Ember 2.14) I have a subview of a product edit route where I want to show the relation to another model (licence). Of course product hasMany licences and licence belongsTo produit. I also have a component to add relations. From what I understand I should load all the data from outside the component in the model function of the route.

WHen I go to the route from somewhere else in the emberApp, it display the correct relations, however when I go directly to the page, only the first licence is displayed as a relation.

Here is the produits.edit.document route's model :

```<code>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    const produit = this.modelFor('produits.edit')
    return Ember.RSVP.hash({
      allLicences: this.get('store').findAll('licence'),
      produit: produit
    });
  }
});
</code>```

The produits.edit route's model :

```<code>export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('produit', params.produit_id);
  }
</code>```

licence.js :

```<code>import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr(),
  produits: DS.hasMany('produit'),
  licenceVersions: DS.hasMany('licence/licence-version')
});
</code>```

produit model :

```<code>import Ember from 'ember';
import DS from 'ember-data';
import { modelAction } from 'ember-custom-actions';

export default DS.Model.extend({
  nom: DS.attr(),
  resume: DS.attr(),
  description: DS.attr(),
  description_sec_title: DS.attr(),
  illustration: DS.attr(),
  isPublished: DS.attr('boolean'),
  famille: DS.belongsTo('famille'),
  licences: DS.hasMany('licence'),
  addLicence: modelAction('licences', {method: 'POST'}),
  anyLicence: Ember.computed('licences.[]', function() {
    return this.get('licenses').length > 0;
  })
});
</code>```

The produits.edit.documents part of the template rendering the licences from the produit.

```<code>{{#each model.produit.licences as |licence|}}
        <tr>
          <td>{{licence.name}} </td>
          <td>{{interface/remove-button deleteElement=(action "removeLicence" licence model.produit model.produit.licences)}}</td>
          <td></td>
        </tr>
{{/each}}
</code>```

In both case, access from the app or whith a reload of the app, ember retrieve the product, and the index of licences. In one case he will show only the first licence of the product, in the other all the correct licence with a relation with the product.

What am I doing wrong in this route model?

EDIT :
Right now it can work if

Licences are included in the product(produit) JSON response from the server

OR

the JSON calls to the API are code 200 instead of 304. In both case, the browser tools  are identical. It only works with Firefox. Sometimes, the first test fails (200) but it works at the second (304) and fails to the subsequent reload (304)

答:
One think you can do is to load relationships synchronously. To do that you can change your relationship like this licences: DS.hasMany('licence', { async: false }). Now you have to include associations when you do a query, like this this.store.findRecord('produit', params.produit_id, { include: 'licences' }). You can load more associations like this, { include: 'licences.licence_versions,famille' }. Check this for more information.

You probably also use {inverse: 'licences'} in your association as you can see here.

Body:
(Ember 2.14) I have a subview of a product edit route where I want to show the relation to another model (licence). Of course product hasMany licences and licence belongsTo produit. I also have a component to add relations. From what I understand I should load all the data from outside the component in the model function of the route.

WHen I go to the route from somewhere else in the emberApp, it display the correct relations, however when I go directly to the page, only the first licence is displayed as a relation.

Here is the produits.edit.document route's model :

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    const produit = this.modelFor('produits.edit')
    return Ember.RSVP.hash({
      allLicences: this.get('store').findAll('licence'),
      produit: produit
    });
  }
});

The produits.edit route's model :

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('produit', params.produit_id);
  }

licence.js :

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr(),
  produits: DS.hasMany('produit'),
  licenceVersions: DS.hasMany('licence/licence-version')
});

produit model :

import Ember from 'ember';
import DS from 'ember-data';
import { modelAction } from 'ember-custom-actions';

export default DS.Model.extend({
  nom: DS.attr(),
  resume: DS.attr(),
  description: DS.attr(),
  description_sec_title: DS.attr(),
  illustration: DS.attr(),
  isPublished: DS.attr('boolean'),
  famille: DS.belongsTo('famille'),
  licences: DS.hasMany('licence'),
  addLicence: modelAction('licences', {method: 'POST'}),
  anyLicence: Ember.computed('licences.[]', function() {
    return this.get('licenses').length > 0;
  })
});

The produits.edit.documents part of the template rendering the licences from the produit.

{{#each model.produit.licences as |licence|}}

          {{licence.name}}
          {{interface/remove-button deleteElement=(action "removeLicence" licence model.produit model.produit.licences)}}

{{/each}}

In both case, access from the app or whith a reload of the app, ember retrieve the product, and the index of licences. In one case he will show only the first licence of the product, in the other all the correct licence with a relation with the product.

What am I doing wrong in this route model?

EDIT :
Right now it can work if

Licences are included in the product(produit) JSON response from the server

OR

the JSON calls to the API are code 200 instead of 304. In both case, the browser tools  are identical. It only works with Firefox. Sometimes, the first test fails (200) but it works at the second (304) and fails to the subsequent reload (304)


问:
Subscribe to MQTT messages from an AMQP client on RabbitMQ?
I run a RabbitMQ node with the MQTT/WebMQTT plugins enabled.
All MQTT plugin settings use the default configuration.
Various MQTT clients are sending messages to MQTT channels.
The MQTT channel names follow the format of devices/{device_id_here}/{special_name_here}

I wish to subscribe to all MQTT messages that would match devices/#/logs in MQTT. How can I accomplish this using an AMQP client on the same broker as the MQTT users?

I am using Bunny as my (Ruby) AMQP client.

答:
You can not use the # wildcard in the middle of a MQTT topic subscription as it is capable of matching multiple levels.

The correct wildcard is + as this only matches a single level in the topic hierarchy. E.g.

```<code>device/+/logs
</code>```

Body:
You can not use the # wildcard in the middle of a MQTT topic subscription as it is capable of matching multiple levels.

The correct wildcard is + as this only matches a single level in the topic hierarchy. E.g.

device/+/logs


问:
Rand Implementation
I would like to go through how rand() and srand() functions are implemented and would like to tweak the code to modify it to my requirements. Where can i find the source code of rand() and srand(). </p>

答:
It takes a seed as in input argument, usually like follows:-

```<code>double result = srand(time(NULL));
</code>```

and returns a random number that adheres to the probability and hence expected number of occurrences.

from CodeGuru forums:-

```<code>void __cdecl srand (unsigned int seed)
{
    #ifdef _MT
        _getptd()->_holdrand = (unsigned long)seed;
    #else /* _MT */
        holdrand = (long)seed;
    #endif /* _MT */
}

int __cdecl rand (void)
{
   #ifdef _MT
    _ptiddata ptd = _getptd();
    return( ((ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L) >> 16) &
    0x7fff );
   #else /* _MT */
    return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
   #endif /* _MT */
}
</code>```

Hope this helps.

Title: Rand Implementation

Body:
It takes a seed as in input argument, usually like follows:-

double result = srand(time(NULL));

and returns a random number that adheres to the probability and hence expected number of occurrences.

from CodeGuru forums:-

void __cdecl srand (unsigned int seed)
{
    #ifdef _MT
        _getptd()->_holdrand = (unsigned long)seed;
    #else /* _MT */
        holdrand = (long)seed;
    #endif /* _MT */
}

int __cdecl rand (void)
{
   #ifdef _MT
    _ptiddata ptd = _getptd();
    return( ((ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L) >> 16) &
    0x7fff );
   #else /* _MT */
    return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
   #endif /* _MT */
}

Hope this helps.


问:
JLong to Double type casting with Delphi
I searched online how to cast a JLong (JavaType) to a Double to use it in C++ code but didn't find examples.
I tried various ways to cast this JLong but none work.

```<code>function TimeSinceBoot(const aContext: JContext): Double;
  begin
    result := (((TJSystemClock.JavaClass.ELAPSED_REALTIME div 1000(JLong)) div 60(JLong))(JDouble))(Double);
  end;
</code>```

It says still Operator or ; missing.
Any suggestions ?

答:
Apart from the fact that you use the wrong syntax to cast (and the cast syntax is well documented), in Delphi, you can't cast an integral type to a floating point type anyway. And you certainly can't cast a JLong to a double.

But apparently, in the Delphi translation, JLong is an interface with a method called doubleValue. Use that:

```<code>Result := TJSystemClock.JavaClass.ELAPSED_REALTIME.doubleValue / 60000.0;
</code>```

Body:
I searched online how to cast a JLong (JavaType) to a Double to use it in C++ code but didn't find examples.
I tried various ways to cast this JLong but none work.

function TimeSinceBoot(const aContext: JContext): Double;
  begin
    result := (((TJSystemClock.JavaClass.ELAPSED_REALTIME div 1000(JLong)) div 60(JLong))(JDouble))(Double);
  end;

It says still Operator or ; missing.
Any suggestions ?

Body:
Apart from the fact that you use the wrong syntax to cast (and the cast syntax is well documented), in Delphi, you can't cast an integral type to a floating point type anyway. And you certainly can't cast a JLong to a double.

But apparently, in the Delphi translation, JLong is an interface with a method called doubleValue. Use that:

Result := TJSystemClock.JavaClass.ELAPSED_REALTIME.doubleValue / 60000.0;


问:
How to center align text in a HTML table cell, without considering other elements in the cell

How do I center text in a div in a column without counting other element in same div, please?

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
}

button {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>text1</td>
  </tr>
    <td>text2<button>ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table></code>```

答:
it is about clearing the floatting elements or in other words about block formatting context

This should help you understand what is happening, then you can use it or avoid it

exemple below using overflow to trigger the block formatting context on the div (table element do it naturally).

Your code initially did not trigger any block formatting context in your div, that's why it did not minfd the floatting element.

td, div {
  border: 1px solid black;
  width: 150px;
  text-align: center;
  overflow:hidden
}

button {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>In a 'table'</p>
<table>
  <tr>
    <td>text1</td>
  </tr>
    <td>text2<button>ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table>

<p>In a 'div' with block formatting context to mind the floatting button. </p>
<div>text1</div>
<div>text2<button>ok</button></div>
<div>text3</div></code>```

Body:
How do I center text in a div in a column without counting other element in same div, please?

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
}

button {
  float: right;
}

    text1

    text2<button>ok</button>

    text3

Body:
it is about clearing the floatting elements or in other words about block formatting context

This should help you understand what is happening, then you can use it or avoid it

exemple below using overflow to trigger the block formatting context on the div (table element do it naturally).

Your code initially did not trigger any block formatting context in your div, that's why it did not minfd the floatting element.

td, div {
  border: 1px solid black;
  width: 150px;
  text-align: center;
  overflow:hidden
}

button {
  float: right;
}

<p>In a 'table'</p>
<table>
  <tr>
    <td>text1</td>
  </tr>
    <td>text2<button>ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table>

<p>In a 'div' with block formatting context to mind the floatting button. </p>
<div>text1</div>
<div>text2<button>ok</button></div>
<div>text3</div>


答:
body {
  background: #b6da8c;
  overflow: hidden;
}

body:before {
  content: '';
  position: absolute;
  top: 0;
  left: 50%;
  width: 70%;
  height: 100%;
  background: #005370;
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skewX(-10deg);
  -ms-transform: skewX(-10deg);
  transform: skewX(-10deg);
  z-index: -1;
}```

Title: Skewed background just CSS


问:
Prove or give a counter example for this greedy algorithm
I'm having trouble with this homework question. I think the main confusion comes from not identifying a basis for a counter example.

Let P1, . . . , Pn be programs stored on a disk. Program Pi requires
  Si megabytes of storage, and the capacity of the disk is D
  megabytes. Where D is less than the sum of megabytes of storage

(a) maximize the number of programs held on the disk. Prove or give a counter-example: greedy algorithm that selects programs in order of
  increasing Si

(b) use as much of the capacity of the disk as possible. Prove or give a counter-example: greedy algorithm that selects programs in
  order of decreasing Si

Edit:
Sorry for not clarifying.

For part (a) my initial try was assuming that it does not select programs in order of increasing  Si. Choosing Pa, Pb and Pc where Sa<=Sb<=Sc, after this I didn't really understand how to go further and part (b) asks the same question but decreasing Si.

答:
a) Theorem: taking programs in increasing order of disk space required ensures that as many programs run as is possible. Proof: the proof is by contradiction. Suppose there is some other method of choosing programs that allows more to run. Then this method must select a different set of programs in at least one case; that is, it must select at least one program that requires more space than one not selected. However, the method might as well have selected the program requiring less space rather than this other one that differentiates it from the selection made by the greedy algorithm. This contradicts the assumption that this method is better than the greedy method. Therefore, no method is better than the greedy method: it is optimal.

b) Theorem: taking programs in decreasing order of disk space required does not ensure that as much disk space is used as is possible. Proof: the proof is by example. Consider the case of a disk of size 10 and programs requiring disk space 6, 5 and 5. Taking the programs in decreasing order of disk space required allows us to use only 6 of the 10 available storage units, whereas we might have taken two programs requiring 5 units each for 10 total units. Therefore, the greedy approach does not give an optimal result in all cases.


问:
Ajax Post to Overloading c# web service method
I have a webService in C# and it works perfectly when I don't overload it.
When i overload and post with ajax, it gives an error.

```<code>$.ajax({
    type: "POST",
    url: "http://localhost:6783/asd.asmx/add",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        console.log(msg);
    },
    error: function () {
        alert("this error");
    }
});
</code>```

in C#

```<code>[WebMethod(MessageName = "add2")]
public int add(int a,int b)
{
    return a+b;
}

[WebMethod(MessageName = "add3")]
public int add(int a, int b, int c)
{
    return a + b + c;
}
</code>```

I added this:

```<code>[WebServiceBinding(ConformsTo = WsiProfiles.None)]
</code>```

And when I test web service, it works. However, it doesn't work when I called with ajax.

答:
If you add a MessageName property, you must use the MessageName as your endpoint.
eg myservice.asmx/mymessagename

This page http://www.c-sharpcorner.com/UploadFile/00a8b7/web-service/ says:

the “SumOfNums MessageName="SumOfFloats"” method will be known as
  “SumOfFloats” for client applications.

Body:
I have a webService in C# and it works perfectly when I don't overload it.
When i overload and post with ajax, it gives an error.

$.ajax({
    type: "POST",
    url: "http://localhost:6783/asd.asmx/add",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        console.log(msg);
    },
    error: function () {
        alert("this error");
    }
});

in C#

[WebMethod(MessageName = "add2")]
public int add(int a,int b)
{
    return a+b;
}

[WebMethod(MessageName = "add3")]
public int add(int a, int b, int c)
{
    return a + b + c;
}

I added this:

[WebServiceBinding(ConformsTo = WsiProfiles.None)]

And when I test web service, it works. However, it doesn't work when I called with ajax.


问:
How to update marker positions with data from Firebase Google Maps API Android
I'm creating an app that makes a real time tracking of users using Firebase Database. Every user is displayed in the map using markers.

When there is a new location update, the marker has to be updated. The problem is that with Firebase method onDataChange() or similars every time a new location update is retrieved, I can't access to the old marker to remove it and create a new one or just update the old marker, because the marker doesn't exist.

I tried it saving markers in SharedPreferences using Gson, but when I pass the marker to json, the app crashes.

Does anyone know how can I update the markers?

This is written inside the onDataChange():

```<code>           for (User user: usersList) {
                Gson gson = new Gson();

                /*
                String previousJson = preferences.getString(user.getId()+"-marker", "");
                Marker previousMarker = gson.fromJson(previousJson, Marker.class);
                if (previousMarker!=null) markerAnterior.remove();
                */

                final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latlng)
                        .title(user.getId());

                Marker marker= mMap.addMarker(markerOptions);

             //   String newJson = gson.toJson(marker); //CRASH
            //    editor.putString(user.getId()+"-marker", newJson);
            //    editor.commit();

            }
</code>```

Thank you.

答:
Create a HashMap instance variable that will map user IDs to Markers:

```<code>private Map<String, Marker> mMarkerMap = new HashMap<>();
</code>```

Then, populate new Markers in the HashMap so you can retrieve them later.

If the Marker already exists, just update the location:

```<code>for (User user : usersList) {

    final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());

    Marker previousMarker = mMarkerMap.get(user.getId());
    if (previousMarker != null) {
        //previous marker exists, update position:
        previousMarker.setPosition(latlng);
    } else {
        //No previous marker, create a new one:
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latlng)
                .title(user.getId());

        Marker marker = mMap.addMarker(markerOptions);

        //put this new marker in the HashMap:
        mMarkerMap.put(user.getId(), marker);
    }
}
</code>```

Body:
I'm creating an app that makes a real time tracking of users using Firebase Database. Every user is displayed in the map using markers.

When there is a new location update, the marker has to be updated. The problem is that with Firebase method onDataChange() or similars every time a new location update is retrieved, I can't access to the old marker to remove it and create a new one or just update the old marker, because the marker doesn't exist.

I tried it saving markers in SharedPreferences using Gson, but when I pass the marker to json, the app crashes.

Does anyone know how can I update the markers?

This is written inside the onDataChange():

           for (User user: usersList) {
                Gson gson = new Gson();

                /*
                String previousJson = preferences.getString(user.getId()+"-marker", "");
                Marker previousMarker = gson.fromJson(previousJson, Marker.class);
                if (previousMarker!=null) markerAnterior.remove();
                */

                final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latlng)
                        .title(user.getId());

                Marker marker= mMap.addMarker(markerOptions);

             //   String newJson = gson.toJson(marker); //CRASH
            //    editor.putString(user.getId()+"-marker", newJson);
            //    editor.commit();

            }

Thank you.

Body:
Create a HashMap instance variable that will map user IDs to Markers:

private Map<String, Marker> mMarkerMap = new HashMap<>();

Then, populate new Markers in the HashMap so you can retrieve them later.

If the Marker already exists, just update the location:

for (User user : usersList) {

    final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());

    Marker previousMarker = mMarkerMap.get(user.getId());
    if (previousMarker != null) {
        //previous marker exists, update position:
        previousMarker.setPosition(latlng);
    } else {
        //No previous marker, create a new one:
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latlng)
                .title(user.getId());

        Marker marker = mMap.addMarker(markerOptions);

        //put this new marker in the HashMap:
        mMarkerMap.put(user.getId(), marker);
    }
}


问:
VLOOKUP to condense data into one cell
I'm trying to create a macro that takes a user's input and shortens it into an abbreviated code. Say a user has inputted the data into the table:

The macro would run and output the abbreviated code based on this table (in this case, outputting "BLK190_G16_WFUR12"):

```<code>Sub Abbreviated_Code()

'Counts number of partitions
Dim PartitionCount As Integer
PartitionCount = Application.CountIf("B16:B25", "*")

' VLOOKUP loop for as many times there are partition layers
    Let x = 0
    Let materialnum = 16 'First material listed at B16
    Do While x < PartitionCount
    abbrev = Application.VLookup(Range("B" & materialnum), info.Range("C2:D20"), 1, False)
    newCode = abbrev & Range("C" & materialnum)

    x = x + 1
    materialnum = materialnum + 1

    Range("E16") = Range("E16") & newCode & "_" 'Output string of text into cell E16
    Loop

End Sub
</code>```

If anyone could please help me out, I'd really appreciate it.

答:
After modifying your code a bit it now works, its a bit messy but error handling is also present in this code. Your data needs to be in C2 & B16.

```<code>Sub Abbreviated_Code()

'Counts number of partitions
Dim PartitionCount As Integer
PartitionCount = Application.WorksheetFunction.CountIf(Range("B16:B25"), "*")

Range("E16") = ""
' VLOOKUP loop for as many times there are partition layers
    Let x = 0
    Let materialnum = 16 'First material listed at B16
    Do While x < PartitionCount

    If Not IsError(Application.Match(Range("B" & materialnum).Value, Range("D2:D10"), 0)) Then
        abbrev = Application.WorksheetFunction.Index(Range("C2:C10"), Application.WorksheetFunction.Match(Range("B" & materialnum).Value, Range("D2:D10"), 0))
    Else:
        GoTo skip:
    End If

    newCode = abbrev & Range("C" & materialnum)

    If Range("E16") = "" Then
        Range("E16") = newCode
    Else:
        Range("E16") = Range("E16") & "_" & newCode 'Output string of text into cell E16
    End If
skip:
    x = x + 1
    materialnum = materialnum + 1
    Loop

End Sub
</code>```

Title: VLOOKUP to condense data into one cell

Body:
I'm trying to create a macro that takes a user's input and shortens it into an abbreviated code. Say a user has inputted the data into the table:

The macro would run and output the abbreviated code based on this table (in this case, outputting "BLK190_G16_WFUR12"):

Sub Abbreviated_Code()

'Counts number of partitions
Dim PartitionCount As Integer
PartitionCount = Application.CountIf("B16:B25", "*")

' VLOOKUP loop for as many times there are partition layers
    Let x = 0
    Let materialnum = 16 'First material listed at B16
    Do While x < PartitionCount
    abbrev = Application.VLookup(Range("B" & materialnum), info.Range("C2:D20"), 1, False)
    newCode = abbrev & Range("C" & materialnum)

    x = x + 1
    materialnum = materialnum + 1

    Range("E16") = Range("E16") & newCode & "_" 'Output string of text into cell E16
    Loop

End Sub

If anyone could please help me out, I'd really appreciate it.

Body:
After modifying your code a bit it now works, its a bit messy but error handling is also present in this code. Your data needs to be in C2 & B16.

Sub Abbreviated_Code()

'Counts number of partitions
Dim PartitionCount As Integer
PartitionCount = Application.WorksheetFunction.CountIf(Range("B16:B25"), "*")

Range("E16") = ""
' VLOOKUP loop for as many times there are partition layers
    Let x = 0
    Let materialnum = 16 'First material listed at B16
    Do While x < PartitionCount

    If Not IsError(Application.Match(Range("B" & materialnum).Value, Range("D2:D10"), 0)) Then
        abbrev = Application.WorksheetFunction.Index(Range("C2:C10"), Application.WorksheetFunction.Match(Range("B" & materialnum).Value, Range("D2:D10"), 0))
    Else:
        GoTo skip:
    End If

    newCode = abbrev & Range("C" & materialnum)

    If Range("E16") = "" Then
        Range("E16") = newCode
    Else:
        Range("E16") = Range("E16") & "_" & newCode 'Output string of text into cell E16
    End If
skip:
    x = x + 1
    materialnum = materialnum + 1
    Loop

End Sub


问:
Create Windows Installer for Java Programs
I'm a Java beginner.

I already created a simple GUI application that display will "hello world" label.

But, how can I create an installer from .java or .jar for windows.
Let's say that I have created a useful application and want to share it with my friends
to install it in their PC without they need to know what is JRE, or how to download JRE.

答:
Install exe4j

This you will use to create a .exe file from a jar file

Install inno setup compiler

This is used to create installer

An outdated but relevant video to guide you through
https://www.youtube.com/watch?v=kSmhIunxVW4

OwnerDisplayName: Hafizul Amri


问:
BigQuery Multiple Joins
I have an Apache combined log file that loads into Bigquery. Which has a schema that consists of resource, place_id, ip, start_time, end_time, device, status. I am trying to run a query that counts the number of resources and number of devices and groups them by resource and device.

Table:

```<code>resource   |  place_id  |  device  |  ip      |  status  |
-----------------------------------------------------------------
/resource1 | 6750320008 |  android | x.x.x.x  |  200     |
/resource1 | 6750320100 |  ipad    | x.x.x.y  |  200     |
/resource2 | 6750320008 |  android | x.x.x.z  |  200     |
</code>```

Query:

```<code>SELECT resource, device
FROM (
  Select
    EXACT_COUNT_DISTINCT(resource) AS URL,
    1 AS scalar,
  FROM ([daily_logs.app_logs_data])
  WHERE place_id = '6750320008' GROUP BY URL) AS datal
JOIN (
  SELECT
    COUNT(device) as DeviceCount,
    1 AS scalar
  FROM ([daily_logs.app_logs_data]) GROUP BY DeviceCount) AS y
ON datal.scalar=y.scalar
</code>```

I receive this error: Error: Cannot group by an aggregate.

I am basically tyring to create two tables from the same table that count different items and then I want to join them together but have them be grouped in order like this:

```<code>     URL   |  totalresourcecount  |  device  |  totaldevicecount
-----------------------------------------------------------------
/resource1 |          1           |  android |         1
/resource1 |          1           |  ipad    |         1
/resource2 |          1           |  android |         1
</code>```

I have read through the google bigquery syntax help and looked at some examples but nothing has generated the desired result. Thanks in advance!

答:
Below is for BigQuery Standard SQL and reflects your logic presented in follow-up comments

```<code>#standardSQL
SELECT resource, device, COUNT(1) cnt
FROM `project.dataset.yourtable`
WHERE place_id = '6750320008'
GROUP BY resource, device
</code>```

You can test / play with above using dummy data as below

```<code>#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT '/resource1' resource, '6750320008' place_id, 'android' device, 'x.x.x.x' ip, 200 status UNION ALL
  SELECT '/resource1', '6750320100', 'ipad', 'x.x.x.y', 200 UNION ALL
  SELECT '/resource2', '6750320008', 'android', 'x.x.x.z', 200
)
SELECT resource, device, COUNT(1) cnt
FROM `project.dataset.yourtable`
WHERE place_id = '6750320008'
GROUP BY resource, device
</code>```

Please note - above is based on how I understood your query logic expressed in your follow-up comments

Title: BigQuery Multiple Joins

Body:
I have an Apache combined log file that loads into Bigquery. Which has a schema that consists of resource, place_id, ip, start_time, end_time, device, status. I am trying to run a query that counts the number of resources and number of devices and groups them by resource and device.

Table:

resource   |  place_id  |  device  |  ip      |  status  |
-----------------------------------------------------------------
/resource1 | 6750320008 |  android | x.x.x.x  |  200     |
/resource1 | 6750320100 |  ipad    | x.x.x.y  |  200     |
/resource2 | 6750320008 |  android | x.x.x.z  |  200     |

Query:

SELECT resource, device
FROM (
  Select
    EXACT_COUNT_DISTINCT(resource) AS URL,
    1 AS scalar,
  FROM ([daily_logs.app_logs_data])
  WHERE place_id = '6750320008' GROUP BY URL) AS datal
JOIN (
  SELECT
    COUNT(device) as DeviceCount,
    1 AS scalar
  FROM ([daily_logs.app_logs_data]) GROUP BY DeviceCount) AS y
ON datal.scalar=y.scalar

I receive this error: Error: Cannot group by an aggregate.

I am basically tyring to create two tables from the same table that count different items and then I want to join them together but have them be grouped in order like this:

     URL   |  totalresourcecount  |  device  |  totaldevicecount
-----------------------------------------------------------------
/resource1 |          1           |  android |         1
/resource1 |          1           |  ipad    |         1
/resource2 |          1           |  android |         1

I have read through the google bigquery syntax help and looked at some examples but nothing has generated the desired result. Thanks in advance!

Body:
Below is for BigQuery Standard SQL and reflects your logic presented in follow-up comments

#standardSQL
SELECT resource, device, COUNT(1) cnt
FROM `project.dataset.yourtable`
WHERE place_id = '6750320008'
GROUP BY resource, device

You can test / play with above using dummy data as below

#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT '/resource1' resource, '6750320008' place_id, 'android' device, 'x.x.x.x' ip, 200 status UNION ALL
  SELECT '/resource1', '6750320100', 'ipad', 'x.x.x.y', 200 UNION ALL
  SELECT '/resource2', '6750320008', 'android', 'x.x.x.z', 200
)
SELECT resource, device, COUNT(1) cnt
FROM `project.dataset.yourtable`
WHERE place_id = '6750320008'
GROUP BY resource, device

Please note - above is based on how I understood your query logic expressed in your follow-up comments


问:
How to find the last child in lodash map object?
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution. </p>

```<code> const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return <Main>
            <Row>
                <Text />
                <Image />
            </Row>
        </Main>
})
</code>```

<p>I don't want the image on last loop </p>

答:
_.dropRight(array, [n=1]) from lodash creates a slice of array with n elements dropped from the end. So in your case it would be just _.dropRight(menus). You can do it inside map function as well:

```<code>const menuList = map(_.dropRight(menus), (el, i) => {
    return <Main>
        <Row>
            <Text />
            <Image />
        </Row>
    </Main>
})
</code>```

Body:
I looping the array of lists by lodash map function and I've try to remove the Image on last child. But I couldn't find solution.

 const menus =[
    {
        name: 'Home',
        key:'dashboard'
    },
    {
        name:'change your pin',
        key:'resetpin'
    },
    {
        name:'Contact',
        key:'contact'
    },
    {
        name:'Sign Out',
        key:'signout'
    }
]
const menuList = map(menus, (el, i) => {
        return
            <Row>
                <Text />
                <Image />
            </Row>

})

I don't want the image on last loop

Body:
_.dropRight(array, [n=1]) from lodash creates a slice of array with n elements dropped from the end. So in your case it would be just _.dropRight(menus). You can do it inside map function as well:

const menuList = map(_.dropRight(menus), (el, i) => {
    return <Main>
        <Row>
            <Text />
            <Image />
        </Row>
    </Main>
})


问:
angular2 , and my service announcement execute multiple times
I dont get it!

This is what I want ot do.  I run a model on the api server and takes about 5-10 mins to run.  So I poll the api server for when its done then I wil add code to trigger a snackbar that model is complete.

1) In my app component, I subscribe to a service that will listen for announcements from other components
    app.component.ts

```<code>ngOnInit(){
   this.polllingCallService()
}

  polllingCallService(){
    this.polling_sub = this.pollingService.pollingAnnounced$.subscribe(
      polling => {
        this.polling = polling;
        console.log('WOWWWWWWWWW')
        if (this.polling){
          this.pollingRemoteService(polling)
        } else{
          console.log('polling as nothing to do...')
        }
      });
  } //end
</code>```

From another component, I send an announcement

```<code>this.pollingService.announcePolling({'model_id':gg,'is_output':false});
</code>```

Well it works but its called twice per the logs:

```<code>WOWWWWWWWWW {model_id: "aaaaa", is_output: false}
WOWWWWWWWWW {model_id: "aaaaa", is_output: false}
</code>```

Also the below is executed twice:

```<code>this.pollingRemoteService(polling)
</code>```

Another time it was this many times:

```<code>app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
</code>```

And this is thus executed many times:

```<code>  this.pollingRemoteService(polling)
</code>```

So what happens is I get the api server twice or more in my polling service when it should be once.

Why does this happen?

Here is my polling service:

```<code>import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class PollingService {

  constructor() { }

  private pollingAnnouncedSource = new Subject<object>();
  // Observable string streams
  pollingAnnounced$ = this.pollingAnnouncedSource.asObservable();
  // Service message commands
  announcePolling(polling: object) {
    this.pollingAnnouncedSource.next(polling);
  }

}
</code>```

Here is the main code that is executed FYI on the app.component.ts:

```<code>isEmpty(obj) {
    console.log('yo dude',obj)
    //https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
  }

  pollingRemoteService(polling){

    let url = this.getEndpointPollingUrl(this.polling_endpoint)
    var result = Observable.interval(5000)
                           .switchMap(() => this._authHttp.get(url + '/' + polling['model_id']))
                           .map(res => res.json())
                           .takeWhile(models => this.isEmpty(models) == false);

    this.af_poll = result.subscribe(
      polldata  => {
        //this.polldata = polldata;
        //console.log('really?',polldata)
        //this.pollingComplete()
      },
      error => {
        let error_json = JSON.parse(error.text())
        console.log('error',error_json)
      }
    );
    //console.log('this.af_poll',this.af_poll)

  }
</code>```

答:
It sounds like you may have a memory leak. Manually generated subscriptions often need to be manually cleaned up. Your polling_sub subscription is never cleaned up and unsubscribed from in your given code.

You don't mention any unsubscribe call for the subscription generated in the polllingCallService() method. If you haven't already, add this method to that component:

```<code>ngOnDestroy() {
    this.polling_sub.unsubscribe();
}
</code>```

Body:
I dont get it!

This is what I want ot do.  I run a model on the api server and takes about 5-10 mins to run.  So I poll the api server for when its done then I wil add code to trigger a snackbar that model is complete.

1) In my app component, I subscribe to a service that will listen for announcements from other components
    app.component.ts

ngOnInit(){
   this.polllingCallService()
}

  polllingCallService(){
    this.polling_sub = this.pollingService.pollingAnnounced$.subscribe(
      polling => {
        this.polling = polling;
        console.log('WOWWWWWWWWW')
        if (this.polling){
          this.pollingRemoteService(polling)
        } else{
          console.log('polling as nothing to do...')
        }
      });
  } //end

From another component, I send an announcement

this.pollingService.announcePolling({'model_id':gg,'is_output':false});

Well it works but its called twice per the logs:

WOWWWWWWWWW {model_id: "aaaaa", is_output: false}
WOWWWWWWWWW {model_id: "aaaaa", is_output: false}

Also the below is executed twice:

this.pollingRemoteService(polling)

Another time it was this many times:

app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}
app.component.ts:132 WOWWWWWWWWW {model_id: "bbbbbb", is_output: false}

And this is thus executed many times:

  this.pollingRemoteService(polling)

So what happens is I get the api server twice or more in my polling service when it should be once.

Why does this happen?

Here is my polling service:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class PollingService {

  constructor() { }

  private pollingAnnouncedSource = new Subject<object>();
  // Observable string streams
  pollingAnnounced$ = this.pollingAnnouncedSource.asObservable();
  // Service message commands
  announcePolling(polling: object) {
    this.pollingAnnouncedSource.next(polling);
  }

}

Here is the main code that is executed FYI on the app.component.ts:

isEmpty(obj) {
    console.log('yo dude',obj)
    //https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
  }

  pollingRemoteService(polling){

    let url = this.getEndpointPollingUrl(this.polling_endpoint)
    var result = Observable.interval(5000)
                           .switchMap(() => this._authHttp.get(url + '/' + polling['model_id']))
                           .map(res => res.json())
                           .takeWhile(models => this.isEmpty(models) == false);

    this.af_poll = result.subscribe(
      polldata  => {
        //this.polldata = polldata;
        //console.log('really?',polldata)
        //this.pollingComplete()
      },
      error => {
        let error_json = JSON.parse(error.text())
        console.log('error',error_json)
      }
    );
    //console.log('this.af_poll',this.af_poll)

  }

Body:
It sounds like you may have a memory leak. Manually generated subscriptions often need to be manually cleaned up. Your polling_sub subscription is never cleaned up and unsubscribed from in your given code.

You don't mention any unsubscribe call for the subscription generated in the polllingCallService() method. If you haven't already, add this method to that component:

ngOnDestroy() {
    this.polling_sub.unsubscribe();
}


问:
Cast everything for 2 decimal points?
I want to divide two integers: 8/15 and return "53.33".

I've tried every single combination, and I've found that this is the only way I can return the desired value:

select cast(100*cast(8/cast(15 as decimal(10,4)) as decimal(18,4)) as decimal(18,2))

Is there a shorter way?

Thanks.

答:
try this:</p>

```<code>select (cast (8 as money)/cast(15 as money) * 100)
</code>```

Title: Cast everything for 2 decimal points?

Body:
try this:

select (cast (8 as money)/cast(15 as money) * 100)


问:
css being applied to all elements in array
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?</p>

```<code>$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});
</code>```

答:
No need of writing long code just use this

```<code> $(':button[disabled="disabled"]').css('background','#ccc');
</code>```

or

```<code>$('.product_tile .addtocartbutton :button[disabled="disabled"]')).css('background','#ccc');
</code>```

depending on your scenario.
Using :button applies to both button and input type="button"

Body:
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?

$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});

Body:
No need of writing long code just use this

 $(':button[disabled="disabled"]').css('background','#ccc');

or

$('.product_tile .addtocartbutton :button[disabled="disabled"]')).css('background','#ccc');

depending on your scenario.
Using :button applies to both button and input type="button"


问:
ER diagram: entity → attribute → attribute
I have to create a ER diagram for this situation:

There are some houses (with own ID) and each house has some attributes like the position of the house and the price. The position has a valuation like the price and I have a list of evaluation.

I have create an entity for the houses with the position attribute and the price attribute but I'm not able to link the position and the price attribute with own valuation.

The schema is this:

Have you some idea to solve it, without to delete the list possibile valuation entity? Thank you very much!

I wish to maintain the information house in an unique entity and the evaluation in another entity. Because my goal is to have one table for all the evaluation

答:
Why don't you create a one-to-many relationship? This way, you would have the valuation ID in house's table, and both entities will remain in separated tables.

There's a good example in this link.

ContentLicense: CC BY-SA 4.0


答:
You are doing interger division. Use float, and multiply by 100.

```<code>select 8/15.00 * 100
</code>```

Or, for your precision, just do the cast once

```<code>select cast(8/15.00 * 100 as decimal (10,2))
</code>```

If these are integers in a table then multiple by 1.0 and cast once

DEMO

```<code>declare @table table (int_one int, int_two int)
insert into @table
values
(8,15)

select
    cast(((int_one * 1.0) / int_two) * 100 as decimal(10,2))
from @table
</code>```

Title: Cast everything for 2 decimal points?

Body:
I want to divide two integers: 8/15 and return "53.33".

I've tried every single combination, and I've found that this is the only way I can return the desired value:

select cast(100*cast(8/cast(15 as decimal(10,4)) as decimal(18,4)) as decimal(18,2))

Is there a shorter way?

Thanks.

Body:
You are doing interger division. Use float, and multiply by 100.

select 8/15.00 * 100

Or, for your precision, just do the cast once

select cast(8/15.00 * 100 as decimal (10,2))

If these are integers in a table then multiple by 1.0 and cast once

DEMO

declare @table table (int_one int, int_two int)
insert into @table
values
(8,15)

select
    cast(((int_one * 1.0) / int_two) * 100 as decimal(10,2))
from @table