问:
Tensorflow hyperparameter tuning - metrics for each trial not outputted
I want to tune a hyperparameter in slightly modified DNNClassifier. I was able to run the tuning job and it succeeded too but the output does not show the final metrics for each trial. This is what the final output looks like:

```<code>{
  "completedTrialCount": "2",
  "trials": [
    {
      "trialId": "1",
      "hyperparameters": {
        "myparam": "0.003"
      }
    },
    {
      "trialId": "2",
      "hyperparameters": {
        "myparam": "0.07"
      }
    }
  ],
  "consumedMLUnits": 1.48,
  "isHyperparameterTuningJob": true
}
</code>```

how do I get the final metric for each trial so as to decide which value is the best?

My code looks like this.

My DNNClassifier:

```<code>    classifier = DNNClassifier(
        feature_columns=feature_columns,
        hidden_units=hu,
        optimizer=tf.train.AdamOptimizer(learning_rate=lr),
        activation_fn=tf.nn.leaky_relu,
        dropout=dr,
        n_classes=2,
        config=self.get_run_config(),
        model_dir=self.model_dir,
        weight_column=weight_column
    )

    tf.contrib.estimator.add_metrics(classifier, compute_metrics)

def compute_metrics(labels, predictions):
    return {'my-roc-auc': tf.metrics.auc(labels, predictions)}
</code>```

The hyperparameters spec is as follows.

```<code>trainingInput:
  hyperparameters:
    hyperparameterMetricTag: my-roc-auc
    maxTrials: 2
    enableTrialEarlyStopping: True
    params:
      - parameterName: myparam
        type: DISCRETE
        discreteValues:
          - 0.0001
          - 0.0005
          - 0.001
          - 0.003
          - 0.005
          - 0.007
          - 0.01
          - 0.03
          - 0.05
          - 0.07
          - 0.1
</code>```

I mostly followed the instructions here.

答:
Fixed it. The issue was </p>

```<code>tf.contrib.estimator.add_metrics(classifier, compute_metrics)
</code>```

<p>It should have been </p>

```<code>classifier = tf.contrib.estimator.add_metrics(classifier, compute_metrics)
</code>```

Body:
I want to tune a hyperparameter in slightly modified DNNClassifier. I was able to run the tuning job and it succeeded too but the output does not show the final metrics for each trial. This is what the final output looks like:

{
  "completedTrialCount": "2",
  "trials": [
    {
      "trialId": "1",
      "hyperparameters": {
        "myparam": "0.003"
      }
    },
    {
      "trialId": "2",
      "hyperparameters": {
        "myparam": "0.07"
      }
    }
  ],
  "consumedMLUnits": 1.48,
  "isHyperparameterTuningJob": true
}

how do I get the final metric for each trial so as to decide which value is the best?

My code looks like this.

My DNNClassifier:

    classifier = DNNClassifier(
        feature_columns=feature_columns,
        hidden_units=hu,
        optimizer=tf.train.AdamOptimizer(learning_rate=lr),
        activation_fn=tf.nn.leaky_relu,
        dropout=dr,
        n_classes=2,
        config=self.get_run_config(),
        model_dir=self.model_dir,
        weight_column=weight_column
    )

    tf.contrib.estimator.add_metrics(classifier, compute_metrics)

def compute_metrics(labels, predictions):
    return {'my-roc-auc': tf.metrics.auc(labels, predictions)}

The hyperparameters spec is as follows.

trainingInput:
  hyperparameters:
    hyperparameterMetricTag: my-roc-auc
    maxTrials: 2
    enableTrialEarlyStopping: True
    params:
      - parameterName: myparam
        type: DISCRETE
        discreteValues:
          - 0.0001
          - 0.0005
          - 0.001
          - 0.003
          - 0.005
          - 0.007
          - 0.01
          - 0.03
          - 0.05
          - 0.07
          - 0.1

I mostly followed the instructions here.

Body:
Fixed it. The issue was

tf.contrib.estimator.add_metrics(classifier, compute_metrics)

It should have been

classifier = tf.contrib.estimator.add_metrics(classifier, compute_metrics)


来源: stackexchange

问:
How to multiply the two nearby elements in a list?
I have a list like below:

```<code>a = [ 1, 2 , 3, 4, s, s+1]
</code>```

I want to keep the first two elements and then multiply the rest two nearby elements.
The result would be like below:

```<code>b = [1, 2, 12, s**2 + s]
</code>```

I know if I want the summation, I can use the code below:

```<code>b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)
</code>```

and I will get the result which is : [1, 2, 7, 2*s + 1]
However, I don't know how to get the multpilication result.
Thanks

答:
Here's a similar approach, but instead using itertools.starmap with operator.mul:

```<code>from operator import mul
from itertools import starmap

s= 5
a = [ 1, 2 , 3, 4, s, s+1]

[*a[:2], *starmap(mul, (a[i: i + 2] for i in range(2, len(a), 2)))]
# [1, 2, 12, 30]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list like below:

a = [ 1, 2 , 3, 4, s, s+1]

I want to keep the first two elements and then multiply the rest two nearby elements.
The result would be like below:

b = [1, 2, 12, s**2 + s]

I know if I want the summation, I can use the code below:

b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)

and I will get the result which is : [1, 2, 7, 2*s + 1]
However, I don't know how to get the multpilication result.
Thanks

Body:
Here's a similar approach, but instead using itertools.starmap with operator.mul:

from operator import mul
from itertools import starmap

s= 5
a = [ 1, 2 , 3, 4, s, s+1]

[*a[:2], *starmap(mul, (a[i: i + 2] for i in range(2, len(a), 2)))]
# [1, 2, 12, 30]


问:
Why is my code getting a segmentation error
For the life of me I cannot understand at all why this program is getting a segmentation error. The issue is that it retrieves an object within the vector container uses a function within the menu class using the get_command() and for some reason after testing the main function line by line this one results in a segmentation fault:

menu->get_command()->execute();

I have tried changing the syntax to create a new command object that stores the returned object from get_command() and changed the index between 0 and -1 and still nothing fixes the error. I have spent at least a couple of hours trying to figure out why but I cannot seem to find a solution.

```<code>class Base {
public:
    /* Constructors */
    Base() { };

    /* Pure Virtual Functions */
    virtual double evaluate() = 0;
    virtual std::string stringify() = 0;
};

class op : public Base
{
public:
    op() { };
    op(double op1) { operand = op1; }

    double evaluate() { return operand; }

    string stringify() {
        string value = to_string(operand);
        return value;
    }
private:
    double operand;
};

class Command {
protected:
    Base* root;

public:
    Command() { this->root = nullptr; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

class Menu {
private:
    int history_index; // Indexes which command was last executed, accounting for undo and redo functions
    std::vector<Command*> history; // Holds all the commands that have been executed until now

public:
    Menu() {
        // Constructor which initializes the internal members
        history_index = -1;
    }

    std::string execute() {
        // Returns the string converted evaluation of the current command
        return to_string(history[history_index - 1]->execute());
    }

    std::string stringify() {
        // Returns the stringified version of the current command
        return history[history_index]->stringify();
    }

    bool initialized() {
        // Returns if the history has an InitialCommand, which is necessary to start the calculation
        if (history[history_index] != nullptr)
            return true;
        else
            return false;
    }

    void add_command(Command* cmd) {
        // Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
        history.push_back(cmd);
        history_index++;
    }

    Command* get_command() {
        // Returns the command that the history_index is currently referring to
        return history[history_index];
    }

    void undo() {
        // Move back one command (does not execute it) if there is a command to undo
        history_index--;
    }

    void redo() {
        // Moves forward one command (does not execute it) if there is a command to redo
        history_index++;
    }
};

class InitialCommand : public Command {
protected:
    Base* root;

public:
    InitialCommand(Base* b) { this->root = b; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

void main()
{
    Menu* menu = new Menu();
    InitialCommand* temp = new InitialCommand(new op(7));
    menu->add_command(temp);
    EXPECT_EQ(menu->get_command()->execute(), 7);

    system("PAUSE");

}
</code>```

答:
The problem is that your Command and InitialCommand both have root variable.
InitialCommand* temp = new InitialCommand(new op(7)); will according to your constructor set InitialCommand::root. So Command::root remains uninitialized. Then Menu holds std::vector<Command*>, so InitialCommand* is implicitly converted to Command*.
At alst calling Command::execute will indeed call Command:execute because the method is not virtual. So, the uninitialized Command::root is used -> seg. fault.

Please don't use new. Use smart pointers - std::unique_ptr should be the default way to manage dynamic memory.

That said, your code seems too Java/C# like. This is C++, use value semantics if you can. There's no reason for Menu* menu = new Menu();. Menu menu; is simpler and works the same in your case. Here's a code I would've written

```<code>#include <memory>
#include <vector>
#include <string>

using namespace std;//Not a good practice and definitely a big no in header files.
class Base {
public:
    /* Constructors */
    Base() { };

    /* Pure Virtual Functions */
    virtual double evaluate() = 0;
    virtual std::string stringify() = 0;
};

class op : public Base
{
public:
    op() { };
    op(double op1) { operand = op1; }

    double evaluate() { return operand; }

    string stringify() {
        string value = to_string(operand);
        return value;
    }
private:
    double operand;
};

class Command {
protected:
    std::unique_ptr<Base> root;

public:
    Command(std::unique_ptr<Base>&& root):root(std::move(root)) { }
    //Be const-correct
    double execute() const { return root->evaluate(); }
    std::string stringify() const { return root->stringify(); }
    Base* get_root() const { return root.get(); }
};

class Menu {
private:
    int history_index; // Indexes which command was last executed, accounting for undo and redo functions
    std::vector<std::unique_ptr<Command>> history; // Holds all the commands that have been executed until now

public:
    Menu() {
        // Constructor which initializes the internal members
        history_index = -1;
    }

    std::string execute() const{
        // Returns the string converted evaluation of the current command
        return to_string(history[history_index - 1]->execute());
    }

    std::string stringify() const{
        // Returns the stringified version of the current command
        return history[history_index]->stringify();
    }

    bool initialized() const{
        // Returns if the history has an InitialCommand, which is necessary to start the calculation
        if (history[history_index] != nullptr)
            return true;
        else
            return false;
    }

    void add_command(std::unique_ptr<Command>&& cmd) {
        // Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
        history.emplace_back(std::move(cmd));
        history_index++;
    }

    Command* get_command() const {
        // Returns the command that the history_index is currently referring to
        return history[history_index].get();
    }

    void undo() {
        // Move back one command (does not execute it) if there is a command to undo
        history_index--;
    }

    void redo() {
        // Moves forward one command (does not execute it) if there is a command to redo
        history_index++;
    }
};

class InitialCommand : public Command {
protected:

public:
    InitialCommand(std::unique_ptr<Base>&& b): Command(std::move(b)){}
};

// There's no such thing as void main
int main()
{
    Menu menu;
    auto temp = std::make_unique<InitialCommand>(std::make_unique<op>(7));
    menu.add_command(std::move(temp));
    //EXPECT_EQ(menu.get_command()->execute(), 7);

    system("PAUSE");

}
</code>```

It uses move semantics which used to not be a beginners concept, but it's such integral part of modern C++ that every C++ programmer must learn it sooner rather than later.

Body:
For the life of me I cannot understand at all why this program is getting a segmentation error. The issue is that it retrieves an object within the vector container uses a function within the menu class using the get_command() and for some reason after testing the main function line by line this one results in a segmentation fault:

menu->get_command()->execute();

I have tried changing the syntax to create a new command object that stores the returned object from get_command() and changed the index between 0 and -1 and still nothing fixes the error. I have spent at least a couple of hours trying to figure out why but I cannot seem to find a solution.

class Base {
public:
    /* Constructors */
    Base() { };

    /* Pure Virtual Functions */
    virtual double evaluate() = 0;
    virtual std::string stringify() = 0;
};

class op : public Base
{
public:
    op() { };
    op(double op1) { operand = op1; }

    double evaluate() { return operand; }

    string stringify() {
        string value = to_string(operand);
        return value;
    }
private:
    double operand;
};

class Command {
protected:
    Base* root;

public:
    Command() { this->root = nullptr; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

class Menu {
private:
    int history_index; // Indexes which command was last executed, accounting for undo and redo functions
    std::vector<Command*> history; // Holds all the commands that have been executed until now

public:
    Menu() {
        // Constructor which initializes the internal members
        history_index = -1;
    }

    std::string execute() {
        // Returns the string converted evaluation of the current command
        return to_string(history[history_index - 1]->execute());
    }

    std::string stringify() {
        // Returns the stringified version of the current command
        return history[history_index]->stringify();
    }

    bool initialized() {
        // Returns if the history has an InitialCommand, which is necessary to start the calculation
        if (history[history_index] != nullptr)
            return true;
        else
            return false;
    }

    void add_command(Command* cmd) {
        // Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
        history.push_back(cmd);
        history_index++;
    }

    Command* get_command() {
        // Returns the command that the history_index is currently referring to
        return history[history_index];
    }

    void undo() {
        // Move back one command (does not execute it) if there is a command to undo
        history_index--;
    }

    void redo() {
        // Moves forward one command (does not execute it) if there is a command to redo
        history_index++;
    }
};

class InitialCommand : public Command {
protected:
    Base* root;

public:
    InitialCommand(Base* b) { this->root = b; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

void main()
{
    Menu* menu = new Menu();
    InitialCommand* temp = new InitialCommand(new op(7));
    menu->add_command(temp);
    EXPECT_EQ(menu->get_command()->execute(), 7);

    system("PAUSE");

}

Body:
The problem is that your Command and InitialCommand both have root variable.
InitialCommand* temp = new InitialCommand(new op(7)); will according to your constructor set InitialCommand::root. So Command::root remains uninitialized. Then Menu holds std::vector<Command*>, so InitialCommand* is implicitly converted to Command*.
At alst calling Command::execute will indeed call Command:execute because the method is not virtual. So, the uninitialized Command::root is used -> seg. fault.

Please don't use new. Use smart pointers - std::unique_ptr should be the default way to manage dynamic memory.

That said, your code seems too Java/C# like. This is C++, use value semantics if you can. There's no reason for Menu* menu = new Menu();. Menu menu; is simpler and works the same in your case. Here's a code I would've written

#include <memory>
#include <vector>
#include <string>

using namespace std;//Not a good practice and definitely a big no in header files.
class Base {
public:
    /* Constructors */
    Base() { };

    /* Pure Virtual Functions */
    virtual double evaluate() = 0;
    virtual std::string stringify() = 0;
};

class op : public Base
{
public:
    op() { };
    op(double op1) { operand = op1; }

    double evaluate() { return operand; }

    string stringify() {
        string value = to_string(operand);
        return value;
    }
private:
    double operand;
};

class Command {
protected:
    std::unique_ptr<Base> root;

public:
    Command(std::unique_ptr<Base>&& root):root(std::move(root)) { }
    //Be const-correct
    double execute() const { return root->evaluate(); }
    std::string stringify() const { return root->stringify(); }
    Base* get_root() const { return root.get(); }
};

class Menu {
private:
    int history_index; // Indexes which command was last executed, accounting for undo and redo functions
    std::vector<std::unique_ptr<Command>> history; // Holds all the commands that have been executed until now

public:
    Menu() {
        // Constructor which initializes the internal members
        history_index = -1;
    }

    std::string execute() const{
        // Returns the string converted evaluation of the current command
        return to_string(history[history_index - 1]->execute());
    }

    std::string stringify() const{
        // Returns the stringified version of the current command
        return history[history_index]->stringify();
    }

    bool initialized() const{
        // Returns if the history has an InitialCommand, which is necessary to start the calculation
        if (history[history_index] != nullptr)
            return true;
        else
            return false;
    }

    void add_command(std::unique_ptr<Command>&& cmd) {
        // Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
        history.emplace_back(std::move(cmd));
        history_index++;
    }

    Command* get_command() const {
        // Returns the command that the history_index is currently referring to
        return history[history_index].get();
    }

    void undo() {
        // Move back one command (does not execute it) if there is a command to undo
        history_index--;
    }

    void redo() {
        // Moves forward one command (does not execute it) if there is a command to redo
        history_index++;
    }
};

class InitialCommand : public Command {
protected:

public:
    InitialCommand(std::unique_ptr<Base>&& b): Command(std::move(b)){}
};

// There's no such thing as void main
int main()
{
    Menu menu;
    auto temp = std::make_unique<InitialCommand>(std::make_unique<op>(7));
    menu.add_command(std::move(temp));
    //EXPECT_EQ(menu.get_command()->execute(), 7);

    system("PAUSE");

}

It uses move semantics which used to not be a beginners concept, but it's such integral part of modern C++ that every C++ programmer must learn it sooner rather than later.


问:
undefined reference to `WinMain@16' collect2.exe: error: ld returned 1 exit status
I am using eclipse CDT to test the Intel instructions and below is my program:

```<code>#define cpuid(func,ax,bx,cx,dx)\
__asm__ __volatile__ ("cpuid":\
 "=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
int Check_CPU_support_AES()
 {
 unsigned int a,b,c,d;
 cpuid(1, a,b,c,d);
 return (c & 0x2000000);
 }
</code>```

When I compile the above code, I get linkage error as:

```<code>Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\Intel.o" "..\\src\\Intel.c"
gcc -o Intel.exe "src\\Intel.o"
c:/mingw/bin/../lib/gcc/mingw32/4.7.2/../../../libmingw32.a(main.o):main.c:(.text.startup+0xa7): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status
</code>```

Please help me regarding the issue.

答:
Yes, Main () function is missing and the compiler is not able to find an entry point for executing the program.

One more reason is even if you have written the main function but if you didnot save the .cpp file and try to compile it will give the same error.So make sure you have successfully saved the .cpp file and then compile and run your code.

Hope this will help since I have faced similar issue and I spent around hours to figure it out ,
Thanks

ContentLicense: CC BY-SA 3.0

Body:
I am using eclipse CDT to test the Intel instructions and below is my program:

#define cpuid(func,ax,bx,cx,dx)\
__asm__ __volatile__ ("cpuid":\
 "=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
int Check_CPU_support_AES()
 {
 unsigned int a,b,c,d;
 cpuid(1, a,b,c,d);
 return (c & 0x2000000);
 }

When I compile the above code, I get linkage error as:

Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\Intel.o" "..\\src\\Intel.c"
gcc -o Intel.exe "src\\Intel.o"
c:/mingw/bin/../lib/gcc/mingw32/4.7.2/../../../libmingw32.a(main.o):main.c:(.text.startup+0xa7): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status

Please help me regarding the issue.


问:
How to identify changes to a list of customers over time
I have a cohort of customers that changes fairly regularly. Each time the cohort changes, a complete dump of the new customers is appended to the table and given a new List_Name. Alpha, Beta, Gamma, etc. Each list generally add some customers, removes some customers, and keeps some customers. I'm trying to create a simple waterfall chart to show the changes from list to list. Typically I would just FULL OUTER JOIN Alpha<->Beta, then FULL OUTER JOIN Beta<->Gamma, etc etc to get the customers that are staying, leaving, and being added. But the List_Versions are growing quite a bit and I am wondering if there is an easier way to do this calc instead of having to edit it every time a new list is appended. I am not able to change this process since it supports legacy systems and is controlled by another department. Thoughts?

EDIT: Sql Server 2016 SP2.

```<code>CREATE TABLE #customers(cust_id int, list_name varchar(10), create_dt date)
INSERT INTO #customers values (1,'Alpha','2019-01-01')
    ,(2,'Alpha','2019-01-01')
    ,(3,'Alpha','2019-01-01')
    ,(4,'Alpha','2019-01-01')
    ,(5,'Alpha','2019-01-01')
    ,(2,'Beta','2019-03-01')
    ,(3,'Beta','2019-03-01')
    ,(4,'Beta','2019-03-01')
    ,(5,'Beta','2019-03-01')
    ,(6,'Beta','2019-03-01')
    ,(7,'Beta','2019-03-01')
    ,(1,'Gamma','2019-05-05')
    ,(6,'Gamma','2019-05-05')
    ,(7,'Gamma','2019-05-05')
    ,(9,'Gamma','2019-05-05')

--Desired Output (long way that needs to be edited every time there is a new list)
SELECT List_Name, 'Starting' Descrip, count(*) Custs FROM #customers WHERE list_name = 'alpha' group by list_name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Alpha' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Beta', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Alpha' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Gamma' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Gamma', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Gamma' AND a.cust_id = x.cust_id) GROUP BY List_Name
</code>```

答:
Okay, so you can store your “Lists” in a Common Table Expression and do the following. It’s not sexy, but it will give you the output below. You can obviously *-1 as you see fit.

```<code>WITH lists (ListName, ListDate, PreceedingDate)
AS
(
    select distinct list_name, create_dt, PreceedingDate
    from #customers C1
        outer apply (select top 1 PreceedingDate = C3.create_dt
                     from #customers C3
                     where C3.create_dt < C1.create_dt
                     order by C3.create_dt desc) C3
)
select ListID = coalesce(lists.ListDate, CTE2.ListDate)
    , ListName = max(lists.ListName)
    , Added = SUM(IIF(C2.cust_id is null, 1, 0))
    , Removed = SUM(IIF(C1.cust_id is null and C2.cust_id is not null, 1, 0))
    , Remained = SUM(IIF(C2.cust_id = C1.cust_id, 1, 0))
from lists
    inner join #customers C1 on C1.create_dt = lists.ListDate
    full outer join #customers C2 on C1.cust_id = C2.cust_id
                                    and C2.create_dt = lists.PreceedingDate
    --since for removed customers the current List will be NULL
    --we join it back on, which leads to all those COALESCEs
    left join lists CTE2 on CTE2.PreceedingDate = C2.create_dt
where coalesce(lists.ListDate, CTE2.ListDate) is not null
group by coalesce(lists.ListDate, CTE2.ListDate)
</code>```

Result:

```<code>ListID     | ListName | Added | Removed | Remained
-----------|----------|-------|---------|---------
2019-01-01 | Alpha    | 5     | 0       | 0
2019-03-01 | Beta     | 2     | 1       | 4
2019-05-05 | Gamma    | 2     | 4       | 2
</code>```

Body:
I have a cohort of customers that changes fairly regularly. Each time the cohort changes, a complete dump of the new customers is appended to the table and given a new List_Name. Alpha, Beta, Gamma, etc. Each list generally add some customers, removes some customers, and keeps some customers. I'm trying to create a simple waterfall chart to show the changes from list to list. Typically I would just FULL OUTER JOIN Alpha<->Beta, then FULL OUTER JOIN Beta<->Gamma, etc etc to get the customers that are staying, leaving, and being added. But the List_Versions are growing quite a bit and I am wondering if there is an easier way to do this calc instead of having to edit it every time a new list is appended. I am not able to change this process since it supports legacy systems and is controlled by another department. Thoughts?

EDIT: Sql Server 2016 SP2.

CREATE TABLE #customers(cust_id int, list_name varchar(10), create_dt date)
INSERT INTO #customers values (1,'Alpha','2019-01-01')
    ,(2,'Alpha','2019-01-01')
    ,(3,'Alpha','2019-01-01')
    ,(4,'Alpha','2019-01-01')
    ,(5,'Alpha','2019-01-01')
    ,(2,'Beta','2019-03-01')
    ,(3,'Beta','2019-03-01')
    ,(4,'Beta','2019-03-01')
    ,(5,'Beta','2019-03-01')
    ,(6,'Beta','2019-03-01')
    ,(7,'Beta','2019-03-01')
    ,(1,'Gamma','2019-05-05')
    ,(6,'Gamma','2019-05-05')
    ,(7,'Gamma','2019-05-05')
    ,(9,'Gamma','2019-05-05')

--Desired Output (long way that needs to be edited every time there is a new list)
SELECT List_Name, 'Starting' Descrip, count(*) Custs FROM #customers WHERE list_name = 'alpha' group by list_name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Alpha' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Beta', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Alpha' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Gamma' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Gamma', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Gamma' AND a.cust_id = x.cust_id) GROUP BY List_Name

Body:
Okay, so you can store your “Lists” in a Common Table Expression and do the following. It’s not sexy, but it will give you the output below. You can obviously *-1 as you see fit.

WITH lists (ListName, ListDate, PreceedingDate)
AS
(
    select distinct list_name, create_dt, PreceedingDate
    from #customers C1
        outer apply (select top 1 PreceedingDate = C3.create_dt
                     from #customers C3
                     where C3.create_dt < C1.create_dt
                     order by C3.create_dt desc) C3
)
select ListID = coalesce(lists.ListDate, CTE2.ListDate)
    , ListName = max(lists.ListName)
    , Added = SUM(IIF(C2.cust_id is null, 1, 0))
    , Removed = SUM(IIF(C1.cust_id is null and C2.cust_id is not null, 1, 0))
    , Remained = SUM(IIF(C2.cust_id = C1.cust_id, 1, 0))
from lists
    inner join #customers C1 on C1.create_dt = lists.ListDate
    full outer join #customers C2 on C1.cust_id = C2.cust_id
                                    and C2.create_dt = lists.PreceedingDate
    --since for removed customers the current List will be NULL
    --we join it back on, which leads to all those COALESCEs
    left join lists CTE2 on CTE2.PreceedingDate = C2.create_dt
where coalesce(lists.ListDate, CTE2.ListDate) is not null
group by coalesce(lists.ListDate, CTE2.ListDate)

Result:

ListID     | ListName | Added | Removed | Remained
-----------|----------|-------|---------|---------
2019-01-01 | Alpha    | 5     | 0       | 0
2019-03-01 | Beta     | 2     | 1       | 4
2019-05-05 | Gamma    | 2     | 4       | 2


问:
Is there a way to write this “if” list in a more elegant way?
Suppose I have an object POJO style and for some of its attributes I have to check if are equals to a particular value; if so I have to add this attribute to a list and throw an exception (just once if one of the attributes is equal to the particular value). Is there a better way to do it than this way?</p>

```<code>// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
     list.add(object.getAttributeA());
     haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
    list.add(object.getAttributeB());
    haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
    list.add(object.getAttributeC());
    haveToThrowException = true;
}//and so on

if (haveToThrownException) {
    throw new Exception(list.toString());
}
</code>```

答:
You can do it like this:</p>

```<code>List<String> list =
    Stream.of(object.getAttributeA(), object.getAttributeB(), object.getAttributeC())
        .filter("0"::equals)
        .collect(toList());
if (!list.isEmpty()) {
  throw new Exception(list.toString());
}
</code>```

Body:
Suppose I have an object POJO style and for some of its attributes I have to check if are equals to a particular value; if so I have to add this attribute to a list and throw an exception (just once if one of the attributes is equal to the particular value). Is there a better way to do it than this way?

// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
     list.add(object.getAttributeA());
     haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
    list.add(object.getAttributeB());
    haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
    list.add(object.getAttributeC());
    haveToThrowException = true;
}//and so on

if (haveToThrownException) {
    throw new Exception(list.toString());
}

Body:
You can do it like this:

List<String> list =
    Stream.of(object.getAttributeA(), object.getAttributeB(), object.getAttributeC())
        .filter("0"::equals)
        .collect(toList());
if (!list.isEmpty()) {
  throw new Exception(list.toString());
}


问:
How to increase the UITableView separator height?
I want more space(10px) between each cell. How can I do this?

And I have added this code

```<code>tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
</code>```

答:
I came across a way that has allowed me to effectively change the gap between cells.

In Interface builder I set the row height to be 46.

In the cellForRowAtIndexPath method of my TableView delegate I set the frame of the cell to be a smaller value.

```<code>cell.frame=CGRectMake(44,0,tableView.bounds.size.width,44)
</code>```

This gives me a cell with a height of 44 that fits the width of the tableView but the space provided for the row will be 46 as defined in IB.

I was filling the cell programmatically anyway so this suited me fine.

Body:
I want more space(10px) between each cell. How can I do this?

And I have added this code

tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

Body:
I came across a way that has allowed me to effectively change the gap between cells.

In Interface builder I set the row height to be 46.

In the cellForRowAtIndexPath method of my TableView delegate I set the frame of the cell to be a smaller value.

cell.frame=CGRectMake(44,0,tableView.bounds.size.width,44)

This gives me a cell with a height of 44 that fits the width of the tableView but the space provided for the row will be 46 as defined in IB.

I was filling the cell programmatically anyway so this suited me fine.


问:
Angular 6 - Could not find module "@angular-devkit/build-angular"
After updating to Angular 6.0.1, I get the following error on ng serve:

```<code>Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
Error: Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
    at Object.resolve (/home/Projects/myProjectName/node_modules/@angular-devkit/core/node/resolve.js:141:11)
    at Observable.rxjs_1.Observable [as _subscribe] (/home/Projects/myProjectName/node_modules/@angular-devkit/architect/src/architect.js:132:40)
</code>```

ng update says everything is in order. Deleting node_modules folder and a fresh npm install install did not help either.

My project is based on ng2-admin(Angular4 version). Here is my package.json dependecies:

```<code> "dependencies": {
    "@angular/animations": "^6.0.1",
    "@angular/common": "^6.0.1",
    "@angular/compiler": "^6.0.1",
    "@angular/core": "^6.0.1",
    "@angular/forms": "^6.0.1",
    "@angular/http": "^6.0.1",
    "@angular/platform-browser": "^6.0.1",
    "@angular/platform-browser-dynamic": "^6.0.1",
    "@angular/platform-server": "^6.0.1",
    "@angular/router": "^6.0.1",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-alpha.26",
    "@ngx-translate/core": "^10.0.1",
    "@ngx-translate/http-loader": "^3.0.1",
    "amcharts3": "github:amcharts/amcharts3",
    "ammap3": "github:amcharts/ammap3",
    "angular-table": "^1.0.4",
    "angular2-csv": "^0.2.5",
    "angular2-datatable": "0.6.0",
    "animate.css": "3.5.2",
    "bootstrap": "4.0.0-alpha.6",
    "bower": "^1.8.4",
    "chart.js": "1.1.1",
    "chartist": "0.10.1",
    "chroma-js": "1.3.3",
    "ckeditor": "4.6.2",
    "core-js": "2.4.1",
    "easy-pie-chart": "2.1.7",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.3.1",
    "google-maps": "3.2.1",
    "ionicons": "2.0.1",
    "jquery": "3.2.1",
    "jquery-slimscroll": "1.3.8",
    "leaflet": "0.7.7",
    "leaflet-map": "0.2.1",
    "lodash": "4.17.4",
    "ng2-ckeditor": "1.1.6",
    "ng2-completer": "^1.6.3",
    "ng2-handsontable": "^2.1.0-rc.3",
    "ng2-slim-loading-bar": "^4.0.0",
    "ng2-smart-table": "^1.0.3",
    "ng2-tree": "2.0.0-alpha.5",
    "ngx-uploader": "4.2.4",
    "normalize.css": "6.0.0",
    "roboto-fontface": "0.7.0",
    "rxjs": "^6.1.0",
    "rxjs-compat": "^6.1.0",
    "zone.js": "0.8.26"
  },
  "devDependencies": {
    "@angular/cli": "^6.0.1",
    "@angular/compiler-cli": "^6.0.1",
    "@types/fullcalendar": "2.7.40",
    "@types/jasmine": "2.5.38",
    "@types/jquery": "2.0.41",
    "@types/jquery.slimscroll": "1.3.30",
    "@types/lodash": "4.14.61",
    "@types/node": "6.0.69",
    "codelyzer": "3.0.1",
    "gh-pages": "0.12.0",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "1.4.1",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "0.2.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "npm-run-all": "4.0.2",
    "protractor": "5.1.0",
    "rimraf": "2.6.1",
    "standard-changelog": "1.0.1",
    "stylelint": "7.10.1",
    "ts-node": "2.1.2",
    "tslint": "5.2.0",
    "tslint-eslint-rules": "4.0.0",
    "tslint-language-service": "0.9.6",
    "typescript": "^2.7.2",
    "typogr": "0.6.6",
    "underscore": "1.8.3",
    "wintersmith": "2.2.5",
    "wintersmith-sassy": "1.1.0"
  }
</code>```

and my angular.json:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ng2-admin": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
              "node_modules/normalize.css/normalize.css",
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/ionicons/scss/ionicons.scss",
              "node_modules/bootstrap/scss/bootstrap.scss",
              "node_modules/leaflet/dist/leaflet.css",
              "node_modules/chartist/dist/chartist.css",
              "node_modules/fullcalendar/dist/fullcalendar.css",
              "node_modules/handsontable/dist/handsontable.full.css",
              "node_modules/ng2-slim-loading-bar/style.css",
              "src/app/theme/theme.scss",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
              "node_modules/jquery-slimscroll/jquery.slimscroll.js",
              "node_modules/tether/dist/js/tether.js",
              "node_modules/bootstrap/dist/js/bootstrap.js",
              "node_modules/handsontable/dist/handsontable.full.js",
              "node_modules/chroma-js/chroma.js"
            ]
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ng2-admin:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ng2-admin:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ng2-admin:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
              "node_modules/jquery-slimscroll/jquery.slimscroll.js",
              "node_modules/tether/dist/js/tether.js",
              "node_modules/bootstrap/dist/js/bootstrap.js",
              "node_modules/handsontable/dist/handsontable.full.js",
              "node_modules/chroma-js/chroma.js"
            ],
            "styles": [
              "node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
              "node_modules/normalize.css/normalize.css",
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/ionicons/scss/ionicons.scss",
              "node_modules/bootstrap/scss/bootstrap.scss",
              "node_modules/leaflet/dist/leaflet.css",
              "node_modules/chartist/dist/chartist.css",
              "node_modules/fullcalendar/dist/fullcalendar.css",
              "node_modules/handsontable/dist/handsontable.full.css",
              "node_modules/ng2-slim-loading-bar/style.css",
              "src/app/theme/theme.scss",
              "src/styles.scss"
            ],
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": []
          }
        }
      }
    },
    "ng2-admin-e2e": {
      "root": "",
      "sourceRoot": "",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "ng2-admin:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "e2e/tsconfig.e2e.json"
            ],
            "exclude": []
          }
        }
      }
    }
  },
  "defaultProject": "ng2-admin",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "scss"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}
</code>```

答:
That's works for me, commit and then:</p>

```<code>ng update @angular/cli @angular/core
npm install --save-dev @angular/cli@latest
</code>```

Body:
After updating to Angular 6.0.1, I get the following error on ng serve:

Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
Error: Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
    at Object.resolve (/home/Projects/myProjectName/node_modules/@angular-devkit/core/node/resolve.js:141:11)
    at Observable.rxjs_1.Observable [as _subscribe] (/home/Projects/myProjectName/node_modules/@angular-devkit/architect/src/architect.js:132:40)

ng update says everything is in order. Deleting node_modules folder and a fresh npm install install did not help either.

My project is based on ng2-admin(Angular4 version). Here is my package.json dependecies:

 "dependencies": {
    "@angular/animations": "^6.0.1",
    "@angular/common": "^6.0.1",
    "@angular/compiler": "^6.0.1",
    "@angular/core": "^6.0.1",
    "@angular/forms": "^6.0.1",
    "@angular/http": "^6.0.1",
    "@angular/platform-browser": "^6.0.1",
    "@angular/platform-browser-dynamic": "^6.0.1",
    "@angular/platform-server": "^6.0.1",
    "@angular/router": "^6.0.1",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-alpha.26",
    "@ngx-translate/core": "^10.0.1",
    "@ngx-translate/http-loader": "^3.0.1",
    "amcharts3": "github:amcharts/amcharts3",
    "ammap3": "github:amcharts/ammap3",
    "angular-table": "^1.0.4",
    "angular2-csv": "^0.2.5",
    "angular2-datatable": "0.6.0",
    "animate.css": "3.5.2",
    "bootstrap": "4.0.0-alpha.6",
    "bower": "^1.8.4",
    "chart.js": "1.1.1",
    "chartist": "0.10.1",
    "chroma-js": "1.3.3",
    "ckeditor": "4.6.2",
    "core-js": "2.4.1",
    "easy-pie-chart": "2.1.7",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.3.1",
    "google-maps": "3.2.1",
    "ionicons": "2.0.1",
    "jquery": "3.2.1",
    "jquery-slimscroll": "1.3.8",
    "leaflet": "0.7.7",
    "leaflet-map": "0.2.1",
    "lodash": "4.17.4",
    "ng2-ckeditor": "1.1.6",
    "ng2-completer": "^1.6.3",
    "ng2-handsontable": "^2.1.0-rc.3",
    "ng2-slim-loading-bar": "^4.0.0",
    "ng2-smart-table": "^1.0.3",
    "ng2-tree": "2.0.0-alpha.5",
    "ngx-uploader": "4.2.4",
    "normalize.css": "6.0.0",
    "roboto-fontface": "0.7.0",
    "rxjs": "^6.1.0",
    "rxjs-compat": "^6.1.0",
    "zone.js": "0.8.26"
  },
  "devDependencies": {
    "@angular/cli": "^6.0.1",
    "@angular/compiler-cli": "^6.0.1",
    "@types/fullcalendar": "2.7.40",
    "@types/jasmine": "2.5.38",
    "@types/jquery": "2.0.41",
    "@types/jquery.slimscroll": "1.3.30",
    "@types/lodash": "4.14.61",
    "@types/node": "6.0.69",
    "codelyzer": "3.0.1",
    "gh-pages": "0.12.0",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "1.4.1",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "0.2.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "npm-run-all": "4.0.2",
    "protractor": "5.1.0",
    "rimraf": "2.6.1",
    "standard-changelog": "1.0.1",
    "stylelint": "7.10.1",
    "ts-node": "2.1.2",
    "tslint": "5.2.0",
    "tslint-eslint-rules": "4.0.0",
    "tslint-language-service": "0.9.6",
    "typescript": "^2.7.2",
    "typogr": "0.6.6",
    "underscore": "1.8.3",
    "wintersmith": "2.2.5",
    "wintersmith-sassy": "1.1.0"
  }

and my angular.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ng2-admin": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
              "node_modules/normalize.css/normalize.css",
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/ionicons/scss/ionicons.scss",
              "node_modules/bootstrap/scss/bootstrap.scss",
              "node_modules/leaflet/dist/leaflet.css",
              "node_modules/chartist/dist/chartist.css",
              "node_modules/fullcalendar/dist/fullcalendar.css",
              "node_modules/handsontable/dist/handsontable.full.css",
              "node_modules/ng2-slim-loading-bar/style.css",
              "src/app/theme/theme.scss",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
              "node_modules/jquery-slimscroll/jquery.slimscroll.js",
              "node_modules/tether/dist/js/tether.js",
              "node_modules/bootstrap/dist/js/bootstrap.js",
              "node_modules/handsontable/dist/handsontable.full.js",
              "node_modules/chroma-js/chroma.js"
            ]
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ng2-admin:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ng2-admin:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ng2-admin:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
              "node_modules/jquery-slimscroll/jquery.slimscroll.js",
              "node_modules/tether/dist/js/tether.js",
              "node_modules/bootstrap/dist/js/bootstrap.js",
              "node_modules/handsontable/dist/handsontable.full.js",
              "node_modules/chroma-js/chroma.js"
            ],
            "styles": [
              "node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
              "node_modules/normalize.css/normalize.css",
              "node_modules/font-awesome/scss/font-awesome.scss",
              "node_modules/ionicons/scss/ionicons.scss",
              "node_modules/bootstrap/scss/bootstrap.scss",
              "node_modules/leaflet/dist/leaflet.css",
              "node_modules/chartist/dist/chartist.css",
              "node_modules/fullcalendar/dist/fullcalendar.css",
              "node_modules/handsontable/dist/handsontable.full.css",
              "node_modules/ng2-slim-loading-bar/style.css",
              "src/app/theme/theme.scss",
              "src/styles.scss"
            ],
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": []
          }
        }
      }
    },
    "ng2-admin-e2e": {
      "root": "",
      "sourceRoot": "",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "ng2-admin:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "e2e/tsconfig.e2e.json"
            ],
            "exclude": []
          }
        }
      }
    }
  },
  "defaultProject": "ng2-admin",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "scss"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}

Body:
That's works for me, commit and then:

ng update @angular/cli @angular/core
npm install --save-dev @angular/cli@latest


问:
AutoIt is not working with chrome
I want to search an image in google using Selenium WebDriver.
I have written a AutoIt script to select the image from the drive.
The AutoIt script is not working with chrome, its working fine with Firefox.

Here is my script -

```<code>WinWait("[CLASS:#32770]","",5)
ControlFocus("File Upload","","Edit1")
Sleep(2000)
ControlSetText("File Upload", "", "Edit1", "image.jpg")
Sleep(2000)
ControlClick("File Upload", "","Button1");
</code>```

I am not getting any exception in my Java code either.
I have also downloaded AutoIt extension for chrome but it didn't work.
Anyone knows the reason ?

答:
```<code>ControlFocus("Open","","Edit1")
ControlSetText("Open","","Edit1","C:\Import\assesse-import.csv")
ControlClick("Open","","Button1")
</code>```

Update "File upload" with "Open" and compile the AutoIT Script again, it should work fine.

Title: AutoIt is not working with chrome

Body:
I want to search an image in google using Selenium WebDriver.
I have written a AutoIt script to select the image from the drive.
The AutoIt script is not working with chrome, its working fine with Firefox.

Here is my script -

WinWait("[CLASS:#32770]","",5)
ControlFocus("File Upload","","Edit1")
Sleep(2000)
ControlSetText("File Upload", "", "Edit1", "image.jpg")
Sleep(2000)
ControlClick("File Upload", "","Button1");

I am not getting any exception in my Java code either.
I have also downloaded AutoIt extension for chrome but it didn't work.
Anyone knows the reason ?

Body:
ControlFocus("Open","","Edit1")
ControlSetText("Open","","Edit1","C:\Import\assesse-import.csv")
ControlClick("Open","","Button1")

Update "File upload" with "Open" and compile the AutoIT Script again, it should work fine.


问:
how do i append an object to an array from a pickerView
I have an array of class objects im using in a pickerView. I need to append that object to another array that is backing my tableView via UIButton. Im unable to figure out how to get the pickerViews Index, the closest i get is an error "Cannot convert value of type 'Int' to expected argument type 'Formula'" , not sure what im doing wrong and searched for days before asking here. Thank you in advance.</p>

```<code>class Formula {
   var formulaNumber: String = ""
   var formulaTitle: String = ""
   var base: String = ""
   var baseValue: Double = 0.0
}

class AllFormula {

   var arr: [Formula] = []
   static var newArr : [Formula] = []

init() {

    let test1 = Formula()
    test1.formulaNumber = "test1"
    test1.formulaTitle = "test1"
    test1.base = "test1"
    test1.baseValue = 10

    let test2 = Formula()
    test2.formulaNumber = "test2"
    test2.formulaTitle = "test2"
    test2.base = "test2"
    test2.baseValue = 20

    arr = [test1, test2]
    AllFormula.newArr = []
    }

}

class AddViewControllerTest : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    let allFormula = AllFormula()
    let numberOfBatches = (1...100).map { String($0) }
    @IBOutlet weak var picker: UIPickerView!

    override func viewDidLoad() {
    super.viewDidLoad()
        picker.dataSource = self
        picker.delegate = self

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 2
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 {
        return allFormula.arr.count
    }else{
        return numberOfBatches.count
    }

}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return allFormula.arr[row].formulaNumber

    }
    return numberOfBatches[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    let chosenRun = allFormula.arr[row]
    let Batches = self.numberOfBatches[row]

    //these print the correct formulas and number of batches
    print(chosenRun)
    print(Batches)

}

@IBAction func AddRunTapped(_ sender: Any) {
    //trying to get the object to pass into new array.
    AllFormula.newArr.append(picker.selectedRow(inComponent: 0))

    //also tried this, which works if it were inside the didSelectRow for the picker view. but i need it on a IBAction.
    AllFormula.newArr.append(allFormulas.arr[row])

    // where as if i choose the exact index it works.
    AllFormula.newArr.append(allFormulas.arr[1])
    }
}
</code>```

答:
nvm ... got it.

declare the var at the top level.

```<code>var test = Formula()
</code>```

didSelectRow

```<code>test = allFormula.arr[row]
</code>```

IBAction

```<code>AllFormula.newArr.append(test)
</code>```

Body:
I have an array of class objects im using in a pickerView. I need to append that object to another array that is backing my tableView via UIButton. Im unable to figure out how to get the pickerViews Index, the closest i get is an error "Cannot convert value of type 'Int' to expected argument type 'Formula'" , not sure what im doing wrong and searched for days before asking here. Thank you in advance.

class Formula {
   var formulaNumber: String = ""
   var formulaTitle: String = ""
   var base: String = ""
   var baseValue: Double = 0.0
}

class AllFormula {

   var arr: [Formula] = []
   static var newArr : [Formula] = []

init() {

    let test1 = Formula()
    test1.formulaNumber = "test1"
    test1.formulaTitle = "test1"
    test1.base = "test1"
    test1.baseValue = 10

    let test2 = Formula()
    test2.formulaNumber = "test2"
    test2.formulaTitle = "test2"
    test2.base = "test2"
    test2.baseValue = 20

    arr = [test1, test2]
    AllFormula.newArr = []
    }

}

class AddViewControllerTest : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    let allFormula = AllFormula()
    let numberOfBatches = (1...100).map { String($0) }
    @IBOutlet weak var picker: UIPickerView!

    override func viewDidLoad() {
    super.viewDidLoad()
        picker.dataSource = self
        picker.delegate = self

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 2
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 {
        return allFormula.arr.count
    }else{
        return numberOfBatches.count
    }

}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return allFormula.arr[row].formulaNumber

    }
    return numberOfBatches[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    let chosenRun = allFormula.arr[row]
    let Batches = self.numberOfBatches[row]

    //these print the correct formulas and number of batches
    print(chosenRun)
    print(Batches)

}

@IBAction func AddRunTapped(_ sender: Any) {
    //trying to get the object to pass into new array.
    AllFormula.newArr.append(picker.selectedRow(inComponent: 0))

    //also tried this, which works if it were inside the didSelectRow for the picker view. but i need it on a IBAction.
    AllFormula.newArr.append(allFormulas.arr[row])

    // where as if i choose the exact index it works.
    AllFormula.newArr.append(allFormulas.arr[1])
    }
}

Body:
nvm ... got it.

declare the var at the top level.

var test = Formula()

didSelectRow

test = allFormula.arr[row]

IBAction

AllFormula.newArr.append(test)


问:
Conditional groupby sum
I would like to create a column that contains the sum of all amounts that occurred in a given hour. For example, if the row I am looking at has 0 under the column 0, I would like the volume column for that row to be the total volume for all amounts that occurred within that hour.

So:

```<code>dat.groupby('Hours')['Amount'].sum()
</code>```

by performing groupby hours and summing the amount, I get the total amount of transactions that where made in each hour.

```<code>Hours
0     257101.87
1     146105.69
2     108819.17
....
45    532181.83
46    448887.69
47    336343.60
Name: Amount, dtype: float64
</code>```

Problem is my database contains 1000s of rows and I can't simply create a new column with the values from the groupby, I would need a condition stipulating that if the value on the hour column is 0 then return the sum of all the amounts where the hour is 0.

So the desired result would be something like this

```<code>Hours      Amount      Total
 0           20         100
 0           20         100
 0           60         100
 1           10          20
 1           10          20
 2           50          50
</code>```

In this scenario I would want to create the total column and return the sum of all amounts that occurred in a given hour

答:
Groupby + transform should do it

```<code>df["Total"] = df.groupby("Hours")["Amount"].transform(sum)
</code>```

Why this works...

A transform in pandas is like a split-apply-combine-merge in one go. You keep the same axis length after the groupby reduction.

Title: Conditional groupby sum

Body:
I would like to create a column that contains the sum of all amounts that occurred in a given hour. For example, if the row I am looking at has 0 under the column 0, I would like the volume column for that row to be the total volume for all amounts that occurred within that hour.

So:

dat.groupby('Hours')['Amount'].sum()

by performing groupby hours and summing the amount, I get the total amount of transactions that where made in each hour.

Hours
0     257101.87
1     146105.69
2     108819.17
....
45    532181.83
46    448887.69
47    336343.60
Name: Amount, dtype: float64

Problem is my database contains 1000s of rows and I can't simply create a new column with the values from the groupby, I would need a condition stipulating that if the value on the hour column is 0 then return the sum of all the amounts where the hour is 0.

So the desired result would be something like this

Hours      Amount      Total
 0           20         100
 0           20         100
 0           60         100
 1           10          20
 1           10          20
 2           50          50

In this scenario I would want to create the total column and return the sum of all amounts that occurred in a given hour

Body:
Groupby + transform should do it

df["Total"] = df.groupby("Hours")["Amount"].transform(sum)

Why this works...

A transform in pandas is like a split-apply-combine-merge in one go. You keep the same axis length after the groupby reduction.


问:
Can i use a newer version of sqlite in my project through Jetpack?
We have come to a condition where we want to use the "lead" and "lag" functions in android but they don't function unless your sqlite version is at least 3.2.  Is it possible for our project to use the newer sqllite versions through Jetpack, and if so, how?</p>

答:
Is it possible for our project to use the newer sqllite versions through Jetpack

Jetpack does not directly give you a new SQLite version.

However, if you are using Room, you can use a custom implementation of the SupportSQLiteDatabase family of interfaces. By default, Room uses its own Framework... versions, which use the built-in SQLite. But, on your Room.DatabaseBuilder, you can call openHelperFactory() and supply a SupportSQLiteOpenHelper.Factory that uses another implementation.

There are at least two of these that you could use, that are on fairly current versions of SQLite:

https://github.com/requery/sqlite-android

SQLCipher for Android, right now by way of my CWAC-SafeRoom library

Both require you to package binaries of SQLite with your app (and cryptography libraries in the case of SQLCipher for Android). This will significantly increase the size of your APK.


问:
Common mistakes when importing timeseries-timestamps (from csv.data) into R, which are labeled as characters, but need to be DateTime
I want to Import a timeseries (from .csv) into R, but the timestamps are Always characters and not DateTimes so I want to convert them. Despite of telling R the "Right Version" of %m/%d/%Y, R is Always producing NAs.
Are there common mistakes I could make

%d.%m.%Y %H:%M

答:
use the tidyverse library

Try using read_csv

use lubridate library for date handling, the syntax is pretty simple, dmy, ymd, etc

Give it a go


问:
How to efficiently structure a batch queue processing logic flow
I have a class that acts as a controller for websites. These exchanges take orders (think shopping cart). Some of the sites only allow you to have one active order/shoppingcart at a time, while others have no limitation.

My program will have a constant stream of items that need to be ordered/addedtocarts. For sites that can have an unlimited number of concurrent orders, this is not an issue, as I can just start up a new order as an item request comes in, but for sites that are limited, items will build up in a queue waiting to be processed when the current order is finished. The following is the code I have so far, and although admittingly there might be some holes or gotchas that I am not aware of (please point them out if this is the case), I think it is functional and will get the job done.

However, since the processing of an item, or queued items, can only be triggered by the addition of an item the while(Enabled) seems inefficent and wrong to me. I would like to restructure what I have to incorporate this logic, but I am not sure how to with the concurrency limitation in a thread-safe way.

```<code>class OrderItemTask
{
    public OrderStatus Status { get; private set; }
    public OrderItemParams Params { get; }
}

class SiteController
{
    public bool Enabled { get; private set; }

    //set in constructor, or options somewhere
    SemaphoreSlim maxConcurrency = new SemaphoreSlim( 1, 1 );

    Queue<OrderItemTask> itemQueue = new Queue<OrderItemTask>();

    public void Start()
    {
        lock (this)
        {
            Enabled = true;
            Task.Run( () => ProcessOrderWorker() );
        }
    }

    public void Stop()
    {
        lock (this)
        {
            Enabled = false;
        }
    }

    public OrderItemTask OrderItem(OrderItemParams @params)
    {
        var task = new OrderItemTask() { Params = @params};
        QueueItem( task );
        return task;
    }

    void QueueItem(OrderItemTask task)
     {
        lock (itemQueue)
        {
            itemQueue.Enqueue( task );
        }
    }

    async Task ProcessOrderWorker()
    {
        //while true or while SiteController is enabled
        while (Enabled)
        {
            try
            {
                await maxConcurrency.WaitAsync();
                lock (itemQueue)
                {
                    if (itemQueue.Count > 0)
                    {
                        var itemBatch = new List<OrderItemTask>();
                        while (itemQueue.Count > 0)
                            itemBatch.Add( itemQueue.Dequeue() );

                        placeOrderStrategy.PlaceOrder( itemBatch );
                    }
                }
            }
            catch(Exception e)
            { }
            finally
            {
                maxConcurrency.Release();
            }
    }
}
</code>```

答:
please look at the comments. I have the changes so it addresses your concerns</p>

```<code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trader.Classes
{
    public class OrderItemParams
    {

    }

    public class OrderStatus
    {

    }

    public class SemaphoreSlim
    {
        public SemaphoreSlim(int a, int b)
        {

        }

        internal Task WaitAsync()
        {
            //do stuff, not sure what?
            throw new NotImplementedException();
        }

        internal void Release()
        {
            throw new NotImplementedException();
        }
    }

    class OrderItemTask
    {
        public OrderStatus Status
        {
            get;
            private set;
        }

        public OrderItemParams Params
        {
            get;
            /*Sa6a: Added the set, as you were trying to assign it in public "OrderItemTask OrderItem(OrderItemParams @params)"
                    and it was telling you it is readonly */
            set;
        }
    }

    class SiteController
    {
        public bool Enabled { get; private set; }

        //set in constructor, or options somewhere
        SemaphoreSlim maxConcurrency = new SemaphoreSlim(1, 1);

        //Queue<OrderItemTask> orderQueue = new Queue<OrderItemTask>();
        ConcurrentQueue<OrderItemTask> orderQueue = new ConcurrentQueue<OrderItemTask>(); //Sa6a: NET 4.0 and above
        List<Task> tList = new List<Task>(); //Sa6a: It is good to have reference to the tasks you are starting, so you can manage them better

        /*Sa6a: I think you do not need that look at the QueueOrder method, I am leaving only start to true for now,
                so we know that the whole thing is started and we can have a way to stop it if we want */
        public void Start()
        {
            Enabled = true;

            //lock (this)   //Sa6a: you do not need this lock, as this is not a method that can be accessed by more than one thread at a time
            //{
            //if (Enabled == false) //Sa6a: this might already be true, and if this is the case, you will end up starting another process
            //{
            //    Enabled = true;
            //    Task t = Task.Run(() => ProcessOrderWorker());
            //    tList.Add(t);
            //}
            //}
        }

        public void Stop()
        {
            //lock (this)  //Sa6a: you do not need this lock, as this is not a method that can be accessed by more than one thread at a time
            //{
            Enabled = false;
            tList.Clear();
            //}
        }

        public OrderItemTask OrderItem(OrderItemParams @params)
        {
            var task = new OrderItemTask() { Params = @params };
            QueueOrder(task);
            return task;
        }

        public void QueueOrder(OrderItemTask task)
        {
            /* Sa6a: MSN documentation does not say that Eqnqueue can throw an error, but call it a 6th sense, just have the catch
             * https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1?redirectedfrom=MSDN&view=netframework-4.8
             */
            try
            {
                if (Enabled)
                {
                    //Remove the completed tasks
                foreach(Task t in tList)
                {
                    if (t.IsCompleted)
                    {
                        tList.Remove(t);
                    }
                }

                orderQueue.Enqueue(task);

                //Sa6a: Start the task here if it is not runningg anymore.
                if (tList.Count == 0)
                {
                    Task t = Task.Run(() => ProcessOrderWorker());
                    tList.Add(t);
                }                    }
                else
                {
                    Console.WriteLine("I do not know if we need this, but the idea is if this is stopped, " +
                            "you should stop enqueuing items, and you can do this onkly if the start method is called. Another way would be to set Enabled to true automatically here?");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("This should never happen in theoery - " + ex);
            }
        }

        /* Sa6a: So the way I have it below is that once the items are dequeued, it should exit the task,
         *       however I am not sure what these maxConcurrency objects do, so if they make it run again, you should remove them
         */
        async Task ProcessOrderWorker()
        {
            /* Sa6a: You can put this somewhere outside or anywhere else,
             *       The idea is that while, items are being added to the queue, they are being dequeued,
             *       so without this you might end up in an infinite loop, if items are being added constantly and fater than they
             *       are being dequeued(do not argue how fast the dequeue goes, does not matter)
             */
            int num_tasks_in_a_batch = 100;
            int counter = 0;

            //while true or while SiteController is enabled
            //while (Enabled) --> Sa6a: you should not need this. If an item is added to the queue and the queue has item, the method will be called again
            //{
            try
            {
                await maxConcurrency.WaitAsync(); //Sa6a: What is this for?

                //lock (orderQueue) //Sa6a: I do not think you need a lock on the queue if it is concurrent
                //{
                if (orderQueue.Count > 0)
                {
                    var batch = new List<OrderItemTask>();
                    while (orderQueue.Count > 0)
                    {
                        OrderItemTask my_task = null;
                        if (orderQueue.TryDequeue(out my_task))
                        {
                            batch.Add(my_task);
                        }

                        /* Sa6a: Explanation of this above, where the variables got declared
                         */
                        if (counter == num_tasks_in_a_batch)
                        {
                            placeOrderStrategy.PlaceOrder(batch); //Sa6a: I guess this is what you might believe would take all the time, and while this is happening items can be added to the queue
                            batch = new List<OrderItemTask>();
                        }

                        /*Sa6a: As the queue is concurrent and you will end up adding items, while they are being add here,
                         *      the user might try to stop the application and you might want to let them
                         */
                        if (Enabled == false)
                        {
                            break; //it should exit out of here
                        }
                    }

                    //Sa6a: You might have had 120 items in the queue. The first 100 got placed, now this will place the remainder 20
                    if (batch.Count > 0)
                    {
                        placeOrderStrategy.PlaceOrder(batch); //Sa6a: I guess this is what you might believe would take all the time, and while this is happening items can be added to the queue
                    }

                }
                //}
            }
            catch (Exception e)
            {
                Console.WriteLine("Let's printed it, so we know it has happened, if it ever does - " + ex);
            }
            finally
            {
                maxConcurrency.Release(); //Sa6a: I do not know what this is for either
            }
            //}
        }
</code>```

Body:
I have a class that acts as a controller for websites. These exchanges take orders (think shopping cart). Some of the sites only allow you to have one active order/shoppingcart at a time, while others have no limitation.

My program will have a constant stream of items that need to be ordered/addedtocarts. For sites that can have an unlimited number of concurrent orders, this is not an issue, as I can just start up a new order as an item request comes in, but for sites that are limited, items will build up in a queue waiting to be processed when the current order is finished. The following is the code I have so far, and although admittingly there might be some holes or gotchas that I am not aware of (please point them out if this is the case), I think it is functional and will get the job done.

However, since the processing of an item, or queued items, can only be triggered by the addition of an item the while(Enabled) seems inefficent and wrong to me. I would like to restructure what I have to incorporate this logic, but I am not sure how to with the concurrency limitation in a thread-safe way.

class OrderItemTask
{
    public OrderStatus Status { get; private set; }
    public OrderItemParams Params { get; }
}

class SiteController
{
    public bool Enabled { get; private set; }

    //set in constructor, or options somewhere
    SemaphoreSlim maxConcurrency = new SemaphoreSlim( 1, 1 );

    Queue<OrderItemTask> itemQueue = new Queue<OrderItemTask>();

    public void Start()
    {
        lock (this)
        {
            Enabled = true;
            Task.Run( () => ProcessOrderWorker() );
        }
    }

    public void Stop()
    {
        lock (this)
        {
            Enabled = false;
        }
    }

    public OrderItemTask OrderItem(OrderItemParams @params)
    {
        var task = new OrderItemTask() { Params = @params};
        QueueItem( task );
        return task;
    }

    void QueueItem(OrderItemTask task)
     {
        lock (itemQueue)
        {
            itemQueue.Enqueue( task );
        }
    }

    async Task ProcessOrderWorker()
    {
        //while true or while SiteController is enabled
        while (Enabled)
        {
            try
            {
                await maxConcurrency.WaitAsync();
                lock (itemQueue)
                {
                    if (itemQueue.Count > 0)
                    {
                        var itemBatch = new List<OrderItemTask>();
                        while (itemQueue.Count > 0)
                            itemBatch.Add( itemQueue.Dequeue() );

                        placeOrderStrategy.PlaceOrder( itemBatch );
                    }
                }
            }
            catch(Exception e)
            { }
            finally
            {
                maxConcurrency.Release();
            }
    }
}

Body:
please look at the comments. I have the changes so it addresses your concerns

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trader.Classes
{
    public class OrderItemParams
    {

    }

    public class OrderStatus
    {

    }

    public class SemaphoreSlim
    {
        public SemaphoreSlim(int a, int b)
        {

        }

        internal Task WaitAsync()
        {
            //do stuff, not sure what?
            throw new NotImplementedException();
        }

        internal void Release()
        {
            throw new NotImplementedException();
        }
    }

    class OrderItemTask
    {
        public OrderStatus Status
        {
            get;
            private set;
        }

        public OrderItemParams Params
        {
            get;
            /*Sa6a: Added the set, as you were trying to assign it in public "OrderItemTask OrderItem(OrderItemParams @params)"
                    and it was telling you it is readonly */
            set;
        }
    }

    class SiteController
    {
        public bool Enabled { get; private set; }

        //set in constructor, or options somewhere
        SemaphoreSlim maxConcurrency = new SemaphoreSlim(1, 1);

        //Queue<OrderItemTask> orderQueue = new Queue<OrderItemTask>();
        ConcurrentQueue<OrderItemTask> orderQueue = new ConcurrentQueue<OrderItemTask>(); //Sa6a: NET 4.0 and above
        List<Task> tList = new List<Task>(); //Sa6a: It is good to have reference to the tasks you are starting, so you can manage them better

        /*Sa6a: I think you do not need that look at the QueueOrder method, I am leaving only start to true for now,
                so we know that the whole thing is started and we can have a way to stop it if we want */
        public void Start()
        {
            Enabled = true;

            //lock (this)   //Sa6a: you do not need this lock, as this is not a method that can be accessed by more than one thread at a time
            //{
            //if (Enabled == false) //Sa6a: this might already be true, and if this is the case, you will end up starting another process
            //{
            //    Enabled = true;
            //    Task t = Task.Run(() => ProcessOrderWorker());
            //    tList.Add(t);
            //}
            //}
        }

        public void Stop()
        {
            //lock (this)  //Sa6a: you do not need this lock, as this is not a method that can be accessed by more than one thread at a time
            //{
            Enabled = false;
            tList.Clear();
            //}
        }

        public OrderItemTask OrderItem(OrderItemParams @params)
        {
            var task = new OrderItemTask() { Params = @params };
            QueueOrder(task);
            return task;
        }

        public void QueueOrder(OrderItemTask task)
        {
            /* Sa6a: MSN documentation does not say that Eqnqueue can throw an error, but call it a 6th sense, just have the catch
             * https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1?redirectedfrom=MSDN&view=netframework-4.8
             */
            try
            {
                if (Enabled)
                {
                    //Remove the completed tasks
                foreach(Task t in tList)
                {
                    if (t.IsCompleted)
                    {
                        tList.Remove(t);
                    }
                }

                orderQueue.Enqueue(task);

                //Sa6a: Start the task here if it is not runningg anymore.
                if (tList.Count == 0)
                {
                    Task t = Task.Run(() => ProcessOrderWorker());
                    tList.Add(t);
                }                    }
                else
                {
                    Console.WriteLine("I do not know if we need this, but the idea is if this is stopped, " +
                            "you should stop enqueuing items, and you can do this onkly if the start method is called. Another way would be to set Enabled to true automatically here?");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("This should never happen in theoery - " + ex);
            }
        }

        /* Sa6a: So the way I have it below is that once the items are dequeued, it should exit the task,
         *       however I am not sure what these maxConcurrency objects do, so if they make it run again, you should remove them
         */
        async Task ProcessOrderWorker()
        {
            /* Sa6a: You can put this somewhere outside or anywhere else,
             *       The idea is that while, items are being added to the queue, they are being dequeued,
             *       so without this you might end up in an infinite loop, if items are being added constantly and fater than they
             *       are being dequeued(do not argue how fast the dequeue goes, does not matter)
             */
            int num_tasks_in_a_batch = 100;
            int counter = 0;

            //while true or while SiteController is enabled
            //while (Enabled) --> Sa6a: you should not need this. If an item is added to the queue and the queue has item, the method will be called again
            //{
            try
            {
                await maxConcurrency.WaitAsync(); //Sa6a: What is this for?

                //lock (orderQueue) //Sa6a: I do not think you need a lock on the queue if it is concurrent
                //{
                if (orderQueue.Count > 0)
                {
                    var batch = new List<OrderItemTask>();
                    while (orderQueue.Count > 0)
                    {
                        OrderItemTask my_task = null;
                        if (orderQueue.TryDequeue(out my_task))
                        {
                            batch.Add(my_task);
                        }

                        /* Sa6a: Explanation of this above, where the variables got declared
                         */
                        if (counter == num_tasks_in_a_batch)
                        {
                            placeOrderStrategy.PlaceOrder(batch); //Sa6a: I guess this is what you might believe would take all the time, and while this is happening items can be added to the queue
                            batch = new List<OrderItemTask>();
                        }

                        /*Sa6a: As the queue is concurrent and you will end up adding items, while they are being add here,
                         *      the user might try to stop the application and you might want to let them
                         */
                        if (Enabled == false)
                        {
                            break; //it should exit out of here
                        }
                    }

                    //Sa6a: You might have had 120 items in the queue. The first 100 got placed, now this will place the remainder 20
                    if (batch.Count > 0)
                    {
                        placeOrderStrategy.PlaceOrder(batch); //Sa6a: I guess this is what you might believe would take all the time, and while this is happening items can be added to the queue
                    }

                }
                //}
            }
            catch (Exception e)
            {
                Console.WriteLine("Let's printed it, so we know it has happened, if it ever does - " + ex);
            }
            finally
            {
                maxConcurrency.Release(); //Sa6a: I do not know what this is for either
            }
            //}
        }


答:
Define a customized multiplication function:</p>

```<code>def mul(lst):
    s = 1
    for x in lst:
        s *= x
    return s

[*a[:2], *map(mul, (a[i: i + 2] for i in range(2, len(a), 2)))]
</code>```

Title: How to multiply the two nearby elements in a list?

Body:
I have a list like below:

a = [ 1, 2 , 3, 4, s, s+1]

I want to keep the first two elements and then multiply the rest two nearby elements.
The result would be like below:

b = [1, 2, 12, s**2 + s]

I know if I want the summation, I can use the code below:

b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)

and I will get the result which is : [1, 2, 7, 2*s + 1]
However, I don't know how to get the multpilication result.
Thanks

Body:
Define a customized multiplication function:

def mul(lst):
    s = 1
    for x in lst:
        s *= x
    return s

[*a[:2], *map(mul, (a[i: i + 2] for i in range(2, len(a), 2)))]


问:
How to plot a cyclical graph on x-y plot
Not sure how to word this correctly. I have longitude data, which sometimes goes from -150 to 150 in consecutive data points, for example. I would like to express the minimum difference graphically.
So for points x1 = -150 and x2 = 150, the minimum difference is really only 60, since after reaching -180, it flips sign and counts down to 150 (as opposed to going the other way, from -150 to 0, then from 0 to 150, which would be a difference of 300).
Considering the min and max of the data (-140 and 160, for example), I'd like to create a graph where y-axis would go like (from top to bottom):

[160, 170, +-180, -170, -160, -150, -140]

so here's the graph i have:

here's how i converted all the big jumps into small jumps:

However, I would like the y-axis not to have values less than -180. Instead, I'd like it to flip back to positive numbers, so it's more accurate (so below -180, it would go to 179, 178, etc).

答: You can use numpy's built-in unwrap method after converting your angle data to radians.  It will automatically add 2*pi each time your data crosses from -180 to 180.


问:
Element <element> is not a known element warning in Visual Studio when using User controls
I have a Visual Studio 2008 project that is showing the following warning when using User Controls, and I haven’t been able to find a solution anywhere.

Element <element>is not a known element

How can I fix this?

答:
From the OP:

The apparent solution to this is to make sure that the TagName is the
  name of control class.

So for my example, the following displayed the warning:

```<code><%@ Register Src="~/path/to/Control.ascx" TagName="tagName" TagPrefix="tagprefix" %>
</code>```

<tagprefix:tagName runat="server" id="controlID" />

But changing it to:

```<code><%@ Register Src="~/path/to/Control.ascx" TagName="Control" TagPrefix="tagprefix" %>
</code>```

<tagprefix:Control runat="server" id="controlID" />

fixes it.

OwnerDisplayName: chris

Body:
From the OP:

The apparent solution to this is to make sure that the TagName is the
  name of control class.

So for my example, the following displayed the warning:

<%@ Register Src="~/path/to/Control.ascx" TagName="tagName" TagPrefix="tagprefix" %>

<tagprefix:tagName runat="server" id="controlID" />

But changing it to:

<%@ Register Src="~/path/to/Control.ascx" TagName="Control" TagPrefix="tagprefix" %>

<tagprefix:Control runat="server" id="controlID" />

fixes it.


问:
How to send JSON data to a bottle server and store the value in sqlite3?
I have JSON file data.json that I want to send via curl to a bottle server which then take the values from the file. The problem is that it doesn't store anything in the database. How can I do to store the values I pass through the JSON file?

curl command

```<code>curl -X POST -i -d @data.json --header "Content-Type: application/json" http://192.168.1.12:8080/
</code>```

bottle.py

```<code>@route('/', method='POST')
def index():
    n1 = request.POST.get("maclist", "").strip()
    n2 = request.POST.get("signallist", "").strip()

    conn = sqlite3.connect('db/users.db')
    c = conn.cursor()
    c.execute("INSERT INTO users (MAC,SIGNAL) VALUES(?,?)", (n1,n2))

    conn.commit()
    return "Items added."
</code>```

data.json

```<code>{
    "maclist": [
        "a1:b2:c3:d4:e5:f6"
    ],
    "signallist": [
        "-25"
    ]
}
</code>```

答:
Try this way,,,

client-side

```<code>curl -X POST -i -d @data.json --header "Content-Type: application/json" http://192.168.1.12:8080/
</code>```

server-side

```<code>@route('/', method='POST')
def index():
    body = request.body.read().decode('utf8') # read directly HTTP input
    get_dict = json.loads(body) # decode json and get native python dict
    maclist = get_dict.get('maclist', [])
    signallist = get_dict.get('signallist', [])
    data_list = list(zip(maclist, signallist)) # cast to list... You should have same number of elements in both collections (maclist, signallist). Otherwise, zip() function will take collection length which is less.
    conn = sqlite3.connect('db/users.db')
    c = conn.cursor()
    c.executemany("INSERT INTO users (MAC,SIGNAL) VALUES(?,?)", data_list)

    conn.commit()
    return "Items added."
</code>```

I hope,,, it helps you.

Body:
I have JSON file data.json that I want to send via curl to a bottle server which then take the values from the file. The problem is that it doesn't store anything in the database. How can I do to store the values I pass through the JSON file?

curl command

curl -X POST -i -d @data.json --header "Content-Type: application/json" http://192.168.1.12:8080/

bottle.py

@route('/', method='POST')
def index():
    n1 = request.POST.get("maclist", "").strip()
    n2 = request.POST.get("signallist", "").strip()

    conn = sqlite3.connect('db/users.db')
    c = conn.cursor()
    c.execute("INSERT INTO users (MAC,SIGNAL) VALUES(?,?)", (n1,n2))

    conn.commit()
    return "Items added."

data.json

{
    "maclist": [
        "a1:b2:c3:d4:e5:f6"
    ],
    "signallist": [
        "-25"
    ]
}

Body:
Try this way,,,

client-side

curl -X POST -i -d @data.json --header "Content-Type: application/json" http://192.168.1.12:8080/

server-side

@route('/', method='POST')
def index():
    body = request.body.read().decode('utf8') # read directly HTTP input
    get_dict = json.loads(body) # decode json and get native python dict
    maclist = get_dict.get('maclist', [])
    signallist = get_dict.get('signallist', [])
    data_list = list(zip(maclist, signallist)) # cast to list... You should have same number of elements in both collections (maclist, signallist). Otherwise, zip() function will take collection length which is less.
    conn = sqlite3.connect('db/users.db')
    c = conn.cursor()
    c.executemany("INSERT INTO users (MAC,SIGNAL) VALUES(?,?)", data_list)

    conn.commit()
    return "Items added."

I hope,,, it helps you.


答:
You can get the values of the attributes in a temporary list or string or other holder of data and then check in one IF statement if the holder contains undesired values. My guess is that you are not interested to recieve a list with the undesired values but you are ineterested in the number of occurences of the undesired value:</p>

```<code>//Java 9 syntax of list.of
List<String> allValues = List.of(object.getAttributeA(),object.getAttributeB(),object.getAttributeC());

//frequency will give you the number of occurences.
int numberOfOccurences = Collections.frequency(allValues , undesiredString);
if (numberOfOccurences  > 0) throw new Exception(undesiredString + " : " + numberOfOccurences );
</code>```

Title: Is there a way to write this “if” list in a more elegant way?

Body:
Suppose I have an object POJO style and for some of its attributes I have to check if are equals to a particular value; if so I have to add this attribute to a list and throw an exception (just once if one of the attributes is equal to the particular value). Is there a better way to do it than this way?

// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
     list.add(object.getAttributeA());
     haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
    list.add(object.getAttributeB());
    haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
    list.add(object.getAttributeC());
    haveToThrowException = true;
}//and so on

if (haveToThrownException) {
    throw new Exception(list.toString());
}

Body:
You can get the values of the attributes in a temporary list or string or other holder of data and then check in one IF statement if the holder contains undesired values. My guess is that you are not interested to recieve a list with the undesired values but you are ineterested in the number of occurences of the undesired value:

//Java 9 syntax of list.of
List<String> allValues = List.of(object.getAttributeA(),object.getAttributeB(),object.getAttributeC());

//frequency will give you the number of occurences.
int numberOfOccurences = Collections.frequency(allValues , undesiredString);
if (numberOfOccurences  > 0) throw new Exception(undesiredString + " : " + numberOfOccurences );


问:
Linq query on datatable
I have 2 datasets ds1 and ds2 ds1 contains valid values used in ds2 for e.g. ds1 contains subject table containing Maths, Science, History. ds2 contains Student table Student table contains Subject column. ds2->Student->Subject values should be present in ds->subject table.

How to implement this type of validation in effective way. I don't want to iterate through each row and column of student table.

e.g.
Students Table

Name      Subject        Status

Peter       Maths          Fail

George    Science        Pass

Joe           IT                Pass

Roger     History          Other

Subjects Table

Subject

Maths

Science

Maths

History

Status Table

Status

Pass

Fail

Now I want to validate the data in Students Table against Subject table Check if the Subject is present in Subjects table or not. Here I want row Joe IT since IT is not present in Subjects table it is invalid.

Similarly , I need to check Students table data with Status table.

Expected Output

Subject         IT

Status      Other

I want LINQ query.

答:
A simple approach:

```<code>var noSubject =
  ds.Student.AsEnumerable().Where(s => ds.Subject.Rows.Find(s.Subject) == null);
</code>```

Assuming Subject is PK in the Subject ds.

Title: Linq query on datatable

Body:
A simple approach:

var noSubject =
  ds.Student.AsEnumerable().Where(s => ds.Subject.Rows.Find(s.Subject) == null);

Assuming Subject is PK in the Subject ds.


问:
Qlik Sense: Change date field format from Google Analytics API
I've pulled in data in Qlik Sense (cloud) from the Google Analytics connector. I'm trying to convert the standard date [ga_dateHourMinute] field to a more eligible date format.

The current format is YearMonthDayhHourMinute, for instance: 201810250004, I would like to convert this to the standard date format 2018-10-25 00:04:00. How do I do this? Answers concerning methods in the data load script or master formula's or variables are all welcome.

Click to see screenshot: left = current date format and right = desired date format

答: I ended up creating a text fields that combined the different digits from the one field into a new order, then pushed the data format into a date/time. Quite a bit of work, but fairly solid.</p>