问:
Orchestrated vs Choreographed Service-Oriented Architecture in large scale?
I'm an architect in a large scale financial company and we are in the beginning of implementing a new business oriented infosystem across our different countries.

From the very early on the core idea has been to follow microservice oriented principles as much as possible (and making sure engineers have read Building Microservices book by Sam Newman).

By now I've come to crossroads. Our services are primarily JSON REST services using Swagger for automated documentation, but in order to use these services in our business processes and making sure not to write business logic into services outside the domain of those services, we've been using Camunda as an orchestration tool. And Camunda is fine (though some have considered Corezoid as an alternative), but somewhat clumsy in what is an otherwise an elegant set of services.

Now service orchestration is a concept pretty familiar to most engineers. But it is one that I am not entirely happy with due to still having a central engine that drives everything. It is incredibly expensive to replace later down the road (though still cheaper to replace than a monolith). And even if this central engine is split into multiple engines (which is actually the case today), it does not necessarily make it much better.

In recent years there has been a movement with microservices towards choreographed (close to event-driven) architecture. It is at this point where I am looking for advice from engineers and architects who have faced similar crossroad decision points.

I absolutely love the idea of decoupled architecture and despite feeling good about killing monoliths and having elegant independent services, I still detect a lot of dependencies in business process as a whole in current orchestrated solution in where it should not actually exist.

And it's not like we are avoiding events. We have actually implemented events on our architecture as well in order to decouple many processes with the core principle that if you don't need a synchronized response and just need to notify of something happening to initiate another process an event is put up that may be caught by another process that starts executing. And orchestration is easier to explain and visualize, it is easier to tweak and modify by more technical minded business users. And I think it is easier to test and validate from business perspective. Orchestrated architecture like this also (usually) expects a good service discovery and quality automated documentation and non-functional requirements which are all things I value greatly.

All of those things that are a question to me in choreographed approach since I don't have first-hand experience in running this in large scale - just some local test prototypes.

But I think you see where I am coming from. I'm trying to consider alternatives without having to regret driving the company all the other way in the end.

Perhaps you can share your own experience with a similar situation or share an interesting link or two? Or am I looking for a silver bullet that doesn't exist yet?

答:
Services need to interact  - services that don't interact are not part of the same system. The search needs access to the catalog, the cart doesn't get the price info from the page, the account needs the purchase history, the recommender needs purchase history, the cart needs to verify the currently available coupons, the inventory needs to know something was purchased etc.

Service boundaries are set to minimize the needed interactions. It can make sense to cut a service to smaller components but if they share a database (internal structure) they are different aspects of the service.

When services interact it creates a level of coupling - at the least, this coupling is some API (JSON or otherwise) that the service has to "maintain" for so other services can interact with it.

Another coupling type is temporal coupling - which is what you get in request-reply situations (and you can eliminate in event driven systems) However, Orchestration vs. Choreography is not about these differences (even though orchestration is mostly associated with request/reply) - it is about central control and governance  vs.flexibility and serendipity.

Orchestration has risks like migrating business logic out of services into the orchestration while choreography runs the risk of chaos. By the way, direct request/reply integration has the worst of both worlds but wins on simplicity when systems are small enough.

Choosing between the two is a balancing act (like most architectural decisions) for instance, Netflix built on choreography for a lot of time but then found they need some control back and introduced an orchestration engine. Nothing is a silver bullet :)

Personally, I like choreography better because of the reduced coupling and flexibility and favor tools like open Zipkin to bring some order into the chaos.

You can see a partial example for an orchestration based arch in slides 10-22 of a presentation I did about microservices


来源: stackexchange

问:
c++ loops and boolean expressions
I'm having trouble trying to do this assignment for my class for a couple of days now and would like some help.

The assignment is to write a program that informs the user of their acceptance status based on their heigh and weight qualifications depending on their gender.

At the end of the program it wants to output the number of candidates that were accepted and the average of those accepted to the overall number of candidates.

Assignment - https://www.saddleback.edu/faculty/slinker/CS1A/CS1A_Fall2013/Assignment8.pdf

We can't use switch, conditional operators, and selection (only for  outputting the correct message to the results). We can only use loops and complex boolean expressions

The problems I'm having is:

If all 3 of my inputs are valid, why are they not outputting if they are accepted and if one of the input (height or weight) or both were rejected then why isn't it outputting it. Is my boolean variable incorrect? If so, how do I fix it.

Why am i unable to exit the loop/program when I enter X. Is my while loop correct or no?

Is there any selection statements I can change into "not selection-statements".

Here is my code

```<code>#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

    char gender;
    int  height;
    int  weight;
    bool heightOK;
    bool weightOK;
    int candidateCount;
    int validCandidateCount;
    bool invalidGender;
    bool invalidHeight;
    bool invalidWeight;
    float percentOutput;

    candidateCount = 0;
    validCandidateCount = 0;

    cout << "Please enter the candidate's information (enter 'X' to exit)."
     << endl;

    do
    {
        cout << "Gender: ";
        cin.get(gender);

        cin.ignore (1000,'\n');
        invalidGender = ( !(gender == 'm' ||
                            gender == 'M' ||
                            gender == 'f' ||
                            gender == 'F' ));

        candidateCount = candidateCount + 1;

        if(invalidGender)
        {
            cout << "***** Invalid gender; please enter M or F*****" <<     endl;
        }

    }while(invalidGender);

    while (gender != 'X' || gender != 'x')
    {
        candidateCount = candidateCount + 1;

        do
        {
            cout << "Height: ";
            cin  >> height;

            invalidHeight = height < 24 || height > 110;

            heightOK = ((gender == 'm' || gender == 'M') &&
                        (height > 65 && height < 80));

            heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
                                    (height > 62 && height < 75));

            if(invalidHeight)
            {
                cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
                     << endl;
            }

        }while(invalidHeight);

        do
        {
         cout << "Weight: ";
         cin  >> weight;

         invalidWeight = weight < 50 || weight > 1400;

         weightOK = ((gender == 'm' || gender == 'M') &&
                        (weight > 130 && weight < 250));

         weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
                    (weight > 110 && weight < 185));

        if(invalidWeight)
            {

                cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
                   << endl;
            }

         }while(invalidWeight);

        if(heightOK && weightOK)
        {
            cout << "This candidate has been ACCEPTED!" << endl;

            validCandidateCount = validCandidateCount + 1;
        }
        else if (!heightOK)
        {
            cout << "This candidate has been rejected based on the HEIGHT requirement."
                 << endl;
        }
        else if (!weightOK)
        {
            cout << "This candidate has been rejected based on the WEIGHT requirement."
                 << endl;
        }
        else if (!(heightOK && weightOK))
        {
            cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
                 << endl;
        }
        do
        {
            cout << "Gender: ";
            cin.get(gender);
            cin.ignore (1000,'\n');

            candidateCount = candidateCount + 1;

            if(invalidGender)
            {
            cout << "***** Invalid gender; please enter M or F*****" <<        endl;
            }
        }while(invalidGender);

    }

    cout << validCandidateCount << " candidate(s) accepted!" << endl;

    percentOutput = validCandidateCount / candidateCount;

    cout << "That's " << percentOutput <<"%!" << endl;

return 0;
}
</code>```

答:
The main while loop should have and condition.

```<code>while(gender !='X' && gender!='x)
</code>```

And your selection code has wrong conditional statements.

```<code>   if(heightOK && weightOK)
    {
        cout << "This candidate has been ACCEPTED!" << endl;

        validCandidateCount = validCandidateCount + 1;
    }
    else if (!heightOK) // you have written else if(heightOK)
    {
        cout << "This candidate has been rejected based on the HEIGHT requirement."
             << endl;
    }
    else if (!weightOK)  // you have written else if(weightOK)
    {
        cout << "This candidate has been rejected based on the WEIGHT requirement."
             << endl;
    }
    else if (!(heightOK && weightOK))
    {
        cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
             << endl;
    }
</code>```

You should remove that invalidgender condition in the last do while loop, otherwise it will cause an infinite loop even if you wish to exit by pressing X.
Instead the invalid gender condition can be placed at the starting of main While loop.

And invalidGender variable should be assigned its value again otherwise it will pick up the previously stored value.

```<code>  invalidGender = ( !(gender == 'm' ||
                        gender == 'M' ||
                        gender == 'f' ||
                        gender == 'F' ));
</code>```

the whole code

```<code>#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

char gender;
int  height;
int  weight;
bool heightOK;
bool weightOK;
int candidateCount;
int validCandidateCount;
bool invalidGender;
bool invalidHeight;
bool invalidWeight;
double percentOutput;

candidateCount = 0;
validCandidateCount = 0;

cout << "Please enter the candidate's information (enter 'X' to exit)."
 << endl;

  cout << "Gender: ";
  cin.get(gender);

while (gender != 'X' && gender != 'x')
{
    candidateCount = candidateCount + 1;

    do
    {
        invalidGender = ( !(gender == 'm' ||
                        gender == 'M' ||
                        gender == 'f' ||
                        gender == 'F' ));

        if(invalidGender)
        {
           cout << "***** Invalid gender; please enter M or F*****" <<        endl;
           cout << "Gender: ";
           cin>>gender;
           cin.ignore (1000,'\n');
        }
    }while(invalidGender);

    do
    {
        cout << "Height: ";
        cin  >> height;

        invalidHeight = height < 24 || height > 110;

        heightOK = ((gender == 'm' || gender == 'M') &&
                    (height > 65 && height < 80));

        heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
                                (height > 62 && height < 75));

        if(invalidHeight)
        {
            cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
                 << endl;
        }

    }while(invalidHeight);

    do
    {
     cout << "Weight: ";
     cin  >> weight;

     invalidWeight = weight < 50 || weight > 1400;

     weightOK = ((gender == 'm' || gender == 'M') &&
                    (weight > 130 && weight < 250));

     weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
                (weight > 110 && weight < 185));

    if(invalidWeight)
        {

            cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
               << endl;
        }

     }while(invalidWeight);

    if(heightOK && weightOK)
    {
        cout << "This candidate has been ACCEPTED!" << endl;

        validCandidateCount = validCandidateCount + 1;
    }
    else if (!heightOK)
    {
        cout << "This candidate has been rejected based on the HEIGHT requirement."
             << endl;
    }
    else if (!weightOK)
    {
        cout << "This candidate has been rejected based on the WEIGHT requirement."
             << endl;
    }
    else if (!(heightOK && weightOK))
    {
        cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
             << endl;
    }

        cout << "Gender: ";
        cin>>gender;
        cin.ignore (1000,'\n');

}

cout << validCandidateCount << " candidate(s) accepted!" << endl;

percentOutput = (double)validCandidateCount / (double)candidateCount;

cout << "That's " << percentOutput*100 <<"%!" << endl;

return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: c++ loops and boolean expressions

Body:
I'm having trouble trying to do this assignment for my class for a couple of days now and would like some help.

The assignment is to write a program that informs the user of their acceptance status based on their heigh and weight qualifications depending on their gender.

At the end of the program it wants to output the number of candidates that were accepted and the average of those accepted to the overall number of candidates.

Assignment - https://www.saddleback.edu/faculty/slinker/CS1A/CS1A_Fall2013/Assignment8.pdf

We can't use switch, conditional operators, and selection (only for  outputting the correct message to the results). We can only use loops and complex boolean expressions

The problems I'm having is:

If all 3 of my inputs are valid, why are they not outputting if they are accepted and if one of the input (height or weight) or both were rejected then why isn't it outputting it. Is my boolean variable incorrect? If so, how do I fix it.

Why am i unable to exit the loop/program when I enter X. Is my while loop correct or no?

Is there any selection statements I can change into "not selection-statements".

Here is my code

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

    char gender;
    int  height;
    int  weight;
    bool heightOK;
    bool weightOK;
    int candidateCount;
    int validCandidateCount;
    bool invalidGender;
    bool invalidHeight;
    bool invalidWeight;
    float percentOutput;

    candidateCount = 0;
    validCandidateCount = 0;

    cout << "Please enter the candidate's information (enter 'X' to exit)."
     << endl;

    do
    {
        cout << "Gender: ";
        cin.get(gender);

        cin.ignore (1000,'\n');
        invalidGender = ( !(gender == 'm' ||
                            gender == 'M' ||
                            gender == 'f' ||
                            gender == 'F' ));

        candidateCount = candidateCount + 1;

        if(invalidGender)
        {
            cout << "***** Invalid gender; please enter M or F*****" <<     endl;
        }

    }while(invalidGender);

    while (gender != 'X' || gender != 'x')
    {
        candidateCount = candidateCount + 1;

        do
        {
            cout << "Height: ";
            cin  >> height;

            invalidHeight = height < 24 || height > 110;

            heightOK = ((gender == 'm' || gender == 'M') &&
                        (height > 65 && height < 80));

            heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
                                    (height > 62 && height < 75));

            if(invalidHeight)
            {
                cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
                     << endl;
            }

        }while(invalidHeight);

        do
        {
         cout << "Weight: ";
         cin  >> weight;

         invalidWeight = weight < 50 || weight > 1400;

         weightOK = ((gender == 'm' || gender == 'M') &&
                        (weight > 130 && weight < 250));

         weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
                    (weight > 110 && weight < 185));

        if(invalidWeight)
            {

                cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
                   << endl;
            }

         }while(invalidWeight);

        if(heightOK && weightOK)
        {
            cout << "This candidate has been ACCEPTED!" << endl;

            validCandidateCount = validCandidateCount + 1;
        }
        else if (!heightOK)
        {
            cout << "This candidate has been rejected based on the HEIGHT requirement."
                 << endl;
        }
        else if (!weightOK)
        {
            cout << "This candidate has been rejected based on the WEIGHT requirement."
                 << endl;
        }
        else if (!(heightOK && weightOK))
        {
            cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
                 << endl;
        }
        do
        {
            cout << "Gender: ";
            cin.get(gender);
            cin.ignore (1000,'\n');

            candidateCount = candidateCount + 1;

            if(invalidGender)
            {
            cout << "***** Invalid gender; please enter M or F*****" <<        endl;
            }
        }while(invalidGender);

    }

    cout << validCandidateCount << " candidate(s) accepted!" << endl;

    percentOutput = validCandidateCount / candidateCount;

    cout << "That's " << percentOutput <<"%!" << endl;

return 0;
}

Body:
The main while loop should have and condition.

while(gender !='X' && gender!='x)

And your selection code has wrong conditional statements.

   if(heightOK && weightOK)
    {
        cout << "This candidate has been ACCEPTED!" << endl;

        validCandidateCount = validCandidateCount + 1;
    }
    else if (!heightOK) // you have written else if(heightOK)
    {
        cout << "This candidate has been rejected based on the HEIGHT requirement."
             << endl;
    }
    else if (!weightOK)  // you have written else if(weightOK)
    {
        cout << "This candidate has been rejected based on the WEIGHT requirement."
             << endl;
    }
    else if (!(heightOK && weightOK))
    {
        cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
             << endl;
    }

You should remove that invalidgender condition in the last do while loop, otherwise it will cause an infinite loop even if you wish to exit by pressing X.
Instead the invalid gender condition can be placed at the starting of main While loop.

And invalidGender variable should be assigned its value again otherwise it will pick up the previously stored value.

  invalidGender = ( !(gender == 'm' ||
                        gender == 'M' ||
                        gender == 'f' ||
                        gender == 'F' ));

the whole code

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

char gender;
int  height;
int  weight;
bool heightOK;
bool weightOK;
int candidateCount;
int validCandidateCount;
bool invalidGender;
bool invalidHeight;
bool invalidWeight;
double percentOutput;

candidateCount = 0;
validCandidateCount = 0;

cout << "Please enter the candidate's information (enter 'X' to exit)."
 << endl;

  cout << "Gender: ";
  cin.get(gender);

while (gender != 'X' && gender != 'x')
{
    candidateCount = candidateCount + 1;

    do
    {
        invalidGender = ( !(gender == 'm' ||
                        gender == 'M' ||
                        gender == 'f' ||
                        gender == 'F' ));

        if(invalidGender)
        {
           cout << "***** Invalid gender; please enter M or F*****" <<        endl;
           cout << "Gender: ";
           cin>>gender;
           cin.ignore (1000,'\n');
        }
    }while(invalidGender);

    do
    {
        cout << "Height: ";
        cin  >> height;

        invalidHeight = height < 24 || height > 110;

        heightOK = ((gender == 'm' || gender == 'M') &&
                    (height > 65 && height < 80));

        heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
                                (height > 62 && height < 75));

        if(invalidHeight)
        {
            cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
                 << endl;
        }

    }while(invalidHeight);

    do
    {
     cout << "Weight: ";
     cin  >> weight;

     invalidWeight = weight < 50 || weight > 1400;

     weightOK = ((gender == 'm' || gender == 'M') &&
                    (weight > 130 && weight < 250));

     weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
                (weight > 110 && weight < 185));

    if(invalidWeight)
        {

            cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
               << endl;
        }

     }while(invalidWeight);

    if(heightOK && weightOK)
    {
        cout << "This candidate has been ACCEPTED!" << endl;

        validCandidateCount = validCandidateCount + 1;
    }
    else if (!heightOK)
    {
        cout << "This candidate has been rejected based on the HEIGHT requirement."
             << endl;
    }
    else if (!weightOK)
    {
        cout << "This candidate has been rejected based on the WEIGHT requirement."
             << endl;
    }
    else if (!(heightOK && weightOK))
    {
        cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
             << endl;
    }

        cout << "Gender: ";
        cin>>gender;
        cin.ignore (1000,'\n');

}

cout << validCandidateCount << " candidate(s) accepted!" << endl;

percentOutput = (double)validCandidateCount / (double)candidateCount;

cout << "That's " << percentOutput*100 <<"%!" << endl;

return 0;
}


问:
mySQL: is it possible to make this query any faster?
I have a table "test" containing millions of entries. Each row contains a floating point "feature" and a "count" how often this feature is present in item "id". The primary key for this table is the combination of "id" and "feature", i.e. every item may have multiple features. There are usually a couple of hundred to a couple of thousand feature entries per item id.

```<code>create table test
(
    id      int not null,
    feature double not null,
    count   int not null
);
</code>```

The task is to find the 500 most similar items to a given reference item. Similarity is measured in number of identical feature values in both items. The query I have come up with is quoted below, but despite properly using indices its execution plan still contains "using temporary" and "using filesort", giving unacceptable performance for my use case.

```<code>select
    t1.id,
    t2.id,
    sum( least( t1.count, t2.count )) as priority
from test as t1
inner join test as t2
     on t2.feature = t1.feature
where t1.id = {some user supplied id value}
group by t1.id, t2.id
order by priority desc
limit 500;
</code>```

Any ideas on how to improve on this? The schema can be modified and indices added as needed.

答:
With the current schema, this query hardly can be improved.

You already have an index on feature and this is the best you can do with the current schema design.

The problem is more similar than is not a relationship of order. If a is more similar to b than it is to c, it does not imply that c is less similar to a than it is to b. Hence, you cannot build a single index describing this relationship, and need to do it for each item separately, which would make your index N^2 entries long, where N is the number of items.

If you always need only top 500 items, you can limit your index to that figure (in which case it will hold 500 * N entries).

MySQL does not support indexed or materialized views, so you will have to do it yourself:

Create a table like this:

```<code>CREATE TABLE similarity
        (
        id1 INT NOT NULL,
        id2 INT NOT NULL,
        similarity DOUBLE NOT NULL,
        PRIMARY KEY (id1, id2),
        KEY (id1, similarity)
        )
</code>```

Whenever you insert a new feature into the table, reflect the changes in the similarity:

```<code>INSERT
INTO    similarity
SELECT  @newid, id,
        LEAST(@newcount, count) AS ns
FROM    test
WHERE   feature = @newfeature
        AND id <> @newid
ON DUPLICATE KEY UPDATE
SET     similarity = similarity + ns;

INSERT
INTO    similarity
SELECT  @newid, id,
        LEAST(@newcount, count) AS ns
FROM    test
WHERE   feature = @newfeature
        AND id <> @newid
ON DUPLICATE KEY UPDATE
SET     similarity = similarity + ns;
</code>```

On a timely basis, remove the excess similarities:

```<code>DELETE  s
FROM    (
        SELECT  id1,
                (
                SELECT  similarity
                FROM    similarity si
                WHERE   si.id1 = s.id1
                ORDER BY
                        si.id1 DESC, si.similarity DESC
                LIMIT 499, 1
                ) AS cs
        FROM    (
                SELECT  DISTINCT id1
                FROM    similarity
                ) s
        ) q
JOIN    similarity s
ON      s.id1 = q.id1
        AND s.similarity < q.cs
</code>```

Query your data:

```<code>SELECT  id2
FROM    similarity
WHERE   id1 = @myid
ORDER BY
        similarity DESC
LIMIT 500
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a table "test" containing millions of entries. Each row contains a floating point "feature" and a "count" how often this feature is present in item "id". The primary key for this table is the combination of "id" and "feature", i.e. every item may have multiple features. There are usually a couple of hundred to a couple of thousand feature entries per item id.

create table test
(
    id      int not null,
    feature double not null,
    count   int not null
);

The task is to find the 500 most similar items to a given reference item. Similarity is measured in number of identical feature values in both items. The query I have come up with is quoted below, but despite properly using indices its execution plan still contains "using temporary" and "using filesort", giving unacceptable performance for my use case.

select
    t1.id,
    t2.id,
    sum( least( t1.count, t2.count )) as priority
from test as t1
inner join test as t2
     on t2.feature = t1.feature
where t1.id = {some user supplied id value}
group by t1.id, t2.id
order by priority desc
limit 500;

Any ideas on how to improve on this? The schema can be modified and indices added as needed.

Body:
With the current schema, this query hardly can be improved.

You already have an index on feature and this is the best you can do with the current schema design.

The problem is more similar than is not a relationship of order. If a is more similar to b than it is to c, it does not imply that c is less similar to a than it is to b. Hence, you cannot build a single index describing this relationship, and need to do it for each item separately, which would make your index N^2 entries long, where N is the number of items.

If you always need only top 500 items, you can limit your index to that figure (in which case it will hold 500 * N entries).

MySQL does not support indexed or materialized views, so you will have to do it yourself:

Create a table like this:

CREATE TABLE similarity
        (
        id1 INT NOT NULL,
        id2 INT NOT NULL,
        similarity DOUBLE NOT NULL,
        PRIMARY KEY (id1, id2),
        KEY (id1, similarity)
        )

Whenever you insert a new feature into the table, reflect the changes in the similarity:

INSERT
INTO    similarity
SELECT  @newid, id,
        LEAST(@newcount, count) AS ns
FROM    test
WHERE   feature = @newfeature
        AND id <> @newid
ON DUPLICATE KEY UPDATE
SET     similarity = similarity + ns;

INSERT
INTO    similarity
SELECT  @newid, id,
        LEAST(@newcount, count) AS ns
FROM    test
WHERE   feature = @newfeature
        AND id <> @newid
ON DUPLICATE KEY UPDATE
SET     similarity = similarity + ns;

On a timely basis, remove the excess similarities:

DELETE  s
FROM    (
        SELECT  id1,
                (
                SELECT  similarity
                FROM    similarity si
                WHERE   si.id1 = s.id1
                ORDER BY
                        si.id1 DESC, si.similarity DESC
                LIMIT 499, 1
                ) AS cs
        FROM    (
                SELECT  DISTINCT id1
                FROM    similarity
                ) s
        ) q
JOIN    similarity s
ON      s.id1 = q.id1
        AND s.similarity < q.cs

Query your data:

SELECT  id2
FROM    similarity
WHERE   id1 = @myid
ORDER BY
        similarity DESC
LIMIT 500


问:
Semantic differences in Algol and C in casting
Suppose we have the following instructions in Algol 68 and C, respectively:
ref int x := 5; and (int*) x = 5;. What are their semantic difference?, it's the same?, because I think that the second one says something like "x will point to a constant" (it can't be compiled) and the first one says "x will point to a memory cell that points to another memory cell that contains a constant, 5". Is it correct?, if not, can you explain it a bit and give some examples to understand this?

答:
Algol 68 has many implicit coercions available depending on context  (Strong, Firm, Meek, Weak & Soft Context): cf Wikipedia & Algol68's Coercion Hierarchy.

Algol68 can implicitly handle:

widening of precision and dimension (Strong)

uniting different types (Firm)

targeted dereferencing (Both Meek and Weak)

proceduring, deproceduring (Soft)

C casting has more restricted implicit casting:

limited to implicit of 'widening' of precision and float to int in some cases only.  Widening to arrays requires pointers and manual coding using the "&" operator.

Unions must be manually coded/created.

There is no dereferencing during casting (C forces the coder to explicitly work out how many times dereference a pointer using the "*"
operator).

procedure without arguments must be explicitly defined by name and called using the "()" operator.

Example code with output...

File: deref_and_cast.c

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

main(){
  auto int*** crrri;
  crrri=(int***)malloc(sizeof(int**));
  *crrri=(int**)malloc(sizeof(int*));
  **crrri=(int*)malloc(sizeof(int));
  ***crrri=255; /* coder to explicitly work out how many times dereference */
  printf("%5.1f\n",(float)***crrri); /* Again deref is muilt-explicit */
}
</code>```

Output:

```<code>255.0
</code>```

File: coerce_and_cast.a68

```<code>#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

LOC REF REF REF INT crrri;
REF REF REF REF INT(crrri):=HEAP REF REF INT;
REF REF REF INT(crrri):=HEAP REF INT;
REF REF INT(crrri):=HEAP INT;
REF INT(crrri):=255; # targeted dereferencing (3x) depending on contect #
printf(($"example meek coercion:"g(-5,1)l$,REAL(crrri)));
</code>```

Examples of Hierarchy of implicit coercions

```<code>PROC VOID raise exception = end; # Implicitly cast a "GO TO" to a PROC #

# Soft: deprocedure a PROC to a VALUE #
printf(($"Soft:"gl$,random)); # Implicit Coercion #
printf(($"Soft:"gl$,REAL(random))); # Explicitly cast/deprocedure #

# Weak: dereference pointer chain to a "name" (LHS in C lingo) #
COMPL compl:= 0;
re OF compl := crrri; # Implicit Coercion #
REF REAL(re OF compl) := crrri; # Explicitly cast/dereference #
printf(($"Weak:"g(-0,4)g(7,4)"i"l$,compl));

# Meek: dereference to a value #
printf(($"Meek:"gl$,sin(crrri))); # Implicit Coercion #
printf(($"Meek:"gl$,sin(REAL(crrri)))); # Explicitly cast/dereference #

# Firm: unite to a UNION #
MODE IRC=UNION(INT,REAL,COMPL);
OP SIN = (IRC z)IRC: (z|(INT i):sin(i),(REAL r):sin(r),(COMPL z):complex sin(z));
printf(($"Firm:"gl$,SIN 1)); # Implicit Coercion #
printf(($"Firm:"gl$,SIN IRC(1))); # Explicitly cast/unite #

# Strong: widen to higher precision OR to an array #
FLEX [0]BOOL bool array := BIN crrri; # Implicit Coercion #
bool array := []BOOL(BIN crrri); # Explicitly cast/widen #
printf(($"Strong:"$,$g$,bool array,$l$));

end: SKIP
</code>```

Output:

```<code>example meek coercion:255.0
Soft:+2.11679610884246e  -1
Soft:+4.01945464342605e  -1
Weak:255.0000+0.0000i
Meek:-5.06391634924491e  -1
Meek:-5.06391634924491e  -1
Firm:+8.41470984807897e  -1
Firm:+8.41470984807897e  -1
Strong:FFFFFFFFFFFFFFFFFFFFFFFFTTTTTTTT
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Algol 68 has many implicit coercions available depending on context  (Strong, Firm, Meek, Weak & Soft Context): cf Wikipedia & Algol68's Coercion Hierarchy.

Algol68 can implicitly handle:

widening of precision and dimension (Strong)

uniting different types (Firm)

targeted dereferencing (Both Meek and Weak)

proceduring, deproceduring (Soft)

C casting has more restricted implicit casting:

limited to implicit of 'widening' of precision and float to int in some cases only.  Widening to arrays requires pointers and manual coding using the "&" operator.

Unions must be manually coded/created.

There is no dereferencing during casting (C forces the coder to explicitly work out how many times dereference a pointer using the "*"
operator).

procedure without arguments must be explicitly defined by name and called using the "()" operator.

Example code with output...

File: deref_and_cast.c

#include <stdio.h>
#include <stdlib.h>

main(){
  auto int*** crrri;
  crrri=(int***)malloc(sizeof(int**));
  *crrri=(int**)malloc(sizeof(int*));
  **crrri=(int*)malloc(sizeof(int));
  ***crrri=255; /* coder to explicitly work out how many times dereference */
  printf("%5.1f\n",(float)***crrri); /* Again deref is muilt-explicit */
}

Output:

255.0

File: coerce_and_cast.a68

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

LOC REF REF REF INT crrri;
REF REF REF REF INT(crrri):=HEAP REF REF INT;
REF REF REF INT(crrri):=HEAP REF INT;
REF REF INT(crrri):=HEAP INT;
REF INT(crrri):=255; # targeted dereferencing (3x) depending on contect #
printf(($"example meek coercion:"g(-5,1)l$,REAL(crrri)));

Examples of Hierarchy of implicit coercions

PROC VOID raise exception = end; # Implicitly cast a "GO TO" to a PROC #

# Soft: deprocedure a PROC to a VALUE #
printf(($"Soft:"gl$,random)); # Implicit Coercion #
printf(($"Soft:"gl$,REAL(random))); # Explicitly cast/deprocedure #

# Weak: dereference pointer chain to a "name" (LHS in C lingo) #
COMPL compl:= 0;
re OF compl := crrri; # Implicit Coercion #
REF REAL(re OF compl) := crrri; # Explicitly cast/dereference #
printf(($"Weak:"g(-0,4)g(7,4)"i"l$,compl));

# Meek: dereference to a value #
printf(($"Meek:"gl$,sin(crrri))); # Implicit Coercion #
printf(($"Meek:"gl$,sin(REAL(crrri)))); # Explicitly cast/dereference #

# Firm: unite to a UNION #
MODE IRC=UNION(INT,REAL,COMPL);
OP SIN = (IRC z)IRC: (z|(INT i):sin(i),(REAL r):sin(r),(COMPL z):complex sin(z));
printf(($"Firm:"gl$,SIN 1)); # Implicit Coercion #
printf(($"Firm:"gl$,SIN IRC(1))); # Explicitly cast/unite #

# Strong: widen to higher precision OR to an array #
FLEX [0]BOOL bool array := BIN crrri; # Implicit Coercion #
bool array := []BOOL(BIN crrri); # Explicitly cast/widen #
printf(($"Strong:"$,$g$,bool array,$l$));

end: SKIP

Output:

example meek coercion:255.0
Soft:+2.11679610884246e  -1
Soft:+4.01945464342605e  -1
Weak:255.0000+0.0000i
Meek:-5.06391634924491e  -1
Meek:-5.06391634924491e  -1
Firm:+8.41470984807897e  -1
Firm:+8.41470984807897e  -1
Strong:FFFFFFFFFFFFFFFFFFFFFFFFTTTTTTTT


问:
How to write a cell array of cell array with a header into a text file?
I have a header as a row vector (gene_common of size 1*12725) and I want to write it into a text file with its corresponding cell array (X1 of size 1*217  and its nested cell array 1*12728).
I want to insert this header from cell 4 of X1 (X1 has 12728 columns so the header will start from cell 4 to 12728).

I tried this code:

```<code>fid5= fopen('fileX.txt', 'w');
temp = vertcat(gene_common, X1{:}).';
fmt = [repmat('%s,', 1, length(X1)), '%s\n'];
fprintf(fid5, fmt, temp{:});
fclose(fid5);
</code>```

but I got this error :

Error using vertcat

CAT arguments dimensions are not consistent.

Error in endfile (line 22)

temp = vertcat(GENE_common,X1{:}).';

答:
```<code>    fid5= fopen('file.txt', 'w');
fprintf(fid5, repmat('%s\t', [1 col]),'','','',GENE_common{1,:});
fprintf(fid5,'\n');
for h1=1:217
    fprintf(fid5, '%s\t ', X{h1}{:});
    fprintf(fid5,'\t');
    fprintf(fid5,'\n');
end
fclose(fid5);
</code>```

Body:
I have a header as a row vector (gene_common of size 1*12725) and I want to write it into a text file with its corresponding cell array (X1 of size 1*217  and its nested cell array 1*12728).
I want to insert this header from cell 4 of X1 (X1 has 12728 columns so the header will start from cell 4 to 12728).

I tried this code:

fid5= fopen('fileX.txt', 'w');
temp = vertcat(gene_common, X1{:}).';
fmt = [repmat('%s,', 1, length(X1)), '%s\n'];
fprintf(fid5, fmt, temp{:});
fclose(fid5);

but I got this error :

Error using vertcat

CAT arguments dimensions are not consistent.

Error in endfile (line 22)

temp = vertcat(GENE_common,X1{:}).';


问:
In JDK1.8, is it necessary to use ConcurrentHashMap on all occasions that require synchronization?
In JDK1.8, is it necessary to use ConcurrentHashMap on all occasions that require synchronization？And never use Collections.synchronizedMap (Map)?</p>

答:
No, it is not necessary to replace use of Collections.synchronizedMap with ConcurrentHashMap when used by multiple threads.

The Concurrent Collections section in the javadoc for package java.util.concurrent says:

"Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable.

As you can see, both Collections.synchronizedMap and ConcurrentHashMap can have their uses.

See also "What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?".


问:
The best temmplate for codeigniter
Can you tell me what's the best template for CI pls?
I'm using CI 3.x
I just want to show my html files in veiws
Thank you

答: You can use Smarty Template Engine for HTML view.</p>

Title: The best temmplate for codeigniter


问:
Using Mockito to test abstract classes
I'd like to test an abstract class. Sure, I can manually write a mock that inherits from the class.

Can I do this using a mocking framework (I'm using Mockito) instead of hand-crafting my mock? How?

答:
The following suggestion lets you test abstract classes without creating a "real" subclass - the Mock is the subclass and only a partial mock.

Use Mockito.mock(My.class, Answers.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.

Example:

```<code>public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}
</code>```

Note: The beauty of this solution is that you do not have to implement the abstract methods. CALLS_REAL_METHODS causes all real methods to be run as is, as long as you don't stub them in your test.

In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiable subclass of your abstract class.

Title: Using Mockito to test abstract classes

Body:
The following suggestion lets you test abstract classes without creating a "real" subclass - the Mock is the subclass and only a partial mock.

Use Mockito.mock(My.class, Answers.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.

Example:

public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}

Note: The beauty of this solution is that you do not have to implement the abstract methods. CALLS_REAL_METHODS causes all real methods to be run as is, as long as you don't stub them in your test.

In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiable subclass of your abstract class.


问:
Adding 1 to elements of an empty list using another list to count up (maybe with += ?)
I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

```<code>input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]
</code>```

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

答:
Python basically is telling you, you can't use a list as an index to another list. When you try to index the input list with the data list, Python raises an error because the index object is not valid(Also, while I'm at it, input is a reserved keyword in Python and should not be used as variable name. But for sake of clarity, I'll keep using it).

This code

```<code>input[data] += 1
</code>```

is equivalent to this

```<code>input[[5, 1, 2, 5]] += 1
</code>```

Which of course makes no sense, and Python complains.

Now if I understand you right, you want to increment the element in input which corresponds to the element in data, each time an occurrences of the element is found. If this is the case, a dictionary would be a much better choice.

Each key in the dictionary would the a number from data, and the value of each key is zero. Each time an occurrence of a key is found, the corresponding value will be incremented. eg.

```<code>input = {5: 0, 2:0, 1:0}
data = [5, 1, 2, 5]

for element in data:
    inpt[element] += 1
</code>```

However, a much better idea would be to use the collections.Counter() class:

```<code>from collections import Counter

data = [5, 1, 2, 5]
input = Counter(data)
</code>```

Body:
I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

Body:
Python basically is telling you, you can't use a list as an index to another list. When you try to index the input list with the data list, Python raises an error because the index object is not valid(Also, while I'm at it, input is a reserved keyword in Python and should not be used as variable name. But for sake of clarity, I'll keep using it).

This code

input[data] += 1

is equivalent to this

input[[5, 1, 2, 5]] += 1

Which of course makes no sense, and Python complains.

Now if I understand you right, you want to increment the element in input which corresponds to the element in data, each time an occurrences of the element is found. If this is the case, a dictionary would be a much better choice.

Each key in the dictionary would the a number from data, and the value of each key is zero. Each time an occurrence of a key is found, the corresponding value will be incremented. eg.

input = {5: 0, 2:0, 1:0}
data = [5, 1, 2, 5]

for element in data:
    inpt[element] += 1

However, a much better idea would be to use the collections.Counter() class:

from collections import Counter

data = [5, 1, 2, 5]
input = Counter(data)


问:
MySQL, query with "NOT IN ( SELECT ... )" very slow
Here is the query runs over 10 minutes.

```<code>SELECT *
FROM tableA
WHERE name NOT IN(
SELECT a.name
FROM tableA a
INNER JOIN tableB b ON a.code = b.code
INNER JOIN tableC c ON c.number = b.number
INNER JOIN tableD d ON d.code = b.code
INNER JOIN tableE e ON e.content= d.content)
</code>```

Is there alternative query runs faster or any solutions? Thanks a lot.

答:
Your query should work fine provided proper indexes are in place. You can maybe try using left join.

```<code>select a.*
from tableA a
left join (
    select distinct a.name
    from tableA a
    inner join tableB b on a.code = b.code
    inner join tableC c on c.number = b.number
    inner join tableD d on d.code = b.code
    inner join tableE e on e.content = d.content
    ) b on a.name = b.name
where b.name is null;
</code>```

The performance will mostly depend on indexes.
For performance, I'd recommend following indexes:

```<code>create index idx_tablea_code_name    on tableA(code, name);
create index idx_tableb_code_number  on tableB(code, number);
create index idx_tablec_number       on tableC(number);
create index idx_tabled_code_content on tableD(code, content);
create index idx_tablee_content      on tableE(content);
</code>```

Body:
Here is the query runs over 10 minutes.

SELECT *
FROM tableA
WHERE name NOT IN(
SELECT a.name
FROM tableA a
INNER JOIN tableB b ON a.code = b.code
INNER JOIN tableC c ON c.number = b.number
INNER JOIN tableD d ON d.code = b.code
INNER JOIN tableE e ON e.content= d.content)

Is there alternative query runs faster or any solutions? Thanks a lot.

Body:
Your query should work fine provided proper indexes are in place. You can maybe try using left join.

select a.*
from tableA a
left join (
    select distinct a.name
    from tableA a
    inner join tableB b on a.code = b.code
    inner join tableC c on c.number = b.number
    inner join tableD d on d.code = b.code
    inner join tableE e on e.content = d.content
    ) b on a.name = b.name
where b.name is null;

The performance will mostly depend on indexes.
For performance, I'd recommend following indexes:

create index idx_tablea_code_name    on tableA(code, name);
create index idx_tableb_code_number  on tableB(code, number);
create index idx_tablec_number       on tableC(number);
create index idx_tabled_code_content on tableD(code, content);
create index idx_tablee_content      on tableE(content);


问:
Bitwise Operations to change 2 LSB
Suppose I have an list of numbers:

```<code>l = [30, 31, 32, 33]
</code>```

In binary this would the same as

```<code>l = [00011110, 00011111, 00100000, 00100001]
</code>```

Using binary operations I want to set the least 2 significant bits to any random value, but retain the 6 most significant bits. An example of this might be:

```<code>l_new = [00011111, 00011101, 00100010, 00100010]
</code>```

How can I do this, using the numpy library in python?

答:
You can use bitwise xor:

```<code>a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, a.shape)
a
# array([131,  79, 186,  90, 102, 179, 247,  28,  58,  60])
b
# array([2, 0, 2, 1, 0, 0, 2, 0, 3, 3])
a^b
# array([129,  79, 184,  91, 102, 179, 245,  28,  57,  63])
</code>```

Demonstrate correctness:

```<code>a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, (1000000,) + a.shape)

# show it leaves high 6 unchanged:
print(np.all(252&a == 252&(a^b)))
# show all low 2 values equally likely:
print(np.abs(np.array([np.histogram(c, np.arange(5)-0.5, normed=True)[0] for c in ((a^b)&3).T])-0.25).max())

# True
# 0.001595
</code>```

Title: Bitwise Operations to change 2 LSB

Body:
Suppose I have an list of numbers:

l = [30, 31, 32, 33]

In binary this would the same as

l = [00011110, 00011111, 00100000, 00100001]

Using binary operations I want to set the least 2 significant bits to any random value, but retain the 6 most significant bits. An example of this might be:

l_new = [00011111, 00011101, 00100010, 00100010]

How can I do this, using the numpy library in python?

Body:
You can use bitwise xor:

a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, a.shape)
a
# array([131,  79, 186,  90, 102, 179, 247,  28,  58,  60])
b
# array([2, 0, 2, 1, 0, 0, 2, 0, 3, 3])
a^b
# array([129,  79, 184,  91, 102, 179, 245,  28,  57,  63])

Demonstrate correctness:

a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, (1000000,) + a.shape)

# show it leaves high 6 unchanged:
print(np.all(252&a == 252&(a^b)))
# show all low 2 values equally likely:
print(np.abs(np.array([np.histogram(c, np.arange(5)-0.5, normed=True)[0] for c in ((a^b)&3).T])-0.25).max())

# True
# 0.001595


Title: Convert list of numpy ndarray to multiple list of lists

Body:
I have an list of numpy.ndarray (5,6) (total size (5,6,5)) which i want to convert into 5 list of lists. each list should contain the information of each row, of each numpy.ndarray.

One way of doing this would be doing to manually, but this can become troublesome for bigger numpy.ndarrays, time consuming, so what how can i do this effectively?

example:

>>> import numpy
>>> a = numpy.zeros((6,5))
>>> b = numpy.ones((6,5))
>>> c = numpy.ones((6,5))*2
>>> d = [a,b,c]
>>> print d
[array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]]), array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]]), array([[ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.]])]
>>> e = list(d)
>>> print e
[array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]]), array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]]), array([[ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.,  2.]])]
# not wanted
>>> print e[0].tolist()
[[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]
#wanted
>>> [[0.0, 0.0, 0.0, 0.0, 0.0], [1,1,1,1,1], [2, 2, 2, 2, 2], ]

Body:
d is a list of 3 arrays.  list(d) doesn't change anything.

e = np.array(d) will produce a (3,6,5), 3d array.

In [37]: e=np.array(d)
In [38]: e.shape
Out[38]: (3, 6, 5)
In [39]: e[:,0,:]
Out[39]:
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2]])
In [40]: list(e[:,0,:])
Out[40]: [array([0, 0, 0, 0, 0]), array([1, 1, 1, 1, 1]), array([2, 2, 2, 2, 2])]
In [41]: e[:,0,:].tolist()
Out[41]: [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2]]


问:
How to compile a CGAL program in ubuntu terminal
I am sorry for the possibly stupid question but I am really a noob in programming and linux.
I have copied a program from the examples of CGAL and I am trying to compile it with the terminal. I am using the order :

g++ convex_hull.cpp -o convex_hull

which I found on the internet, but the errors are many, and I suspect from what I read that it does not recognise the cgal orders in it. It says things like:

"    undefined reference to `CGAL::assertion_fail(char const*, char const*, int, char const*)'     "   etc.

Do you have any idea how to fix this?

Note: I have installed cgal successfully, so I do not think this is the problem.

答:
try it
 g++ filename -lCGAL -gmp
 mesh.txt</p>


问:
req.body returning empty object (I've included bodyparser)
I'm new to backend javascript and I have a form that on submit is supposed to show the submitted object, but it's displaying an empty object instead. I've included body-parser so I'm not sure where the issue is. Here is my app.js file:

```<code>const express = require("express");
const app = express();
const mustacheExpress = require("mustache-express");
const bodyParser = require("body-parser");
const pgp = require("pg-promise")();

app.engine("html", mustacheExpress());
app.set("view engine", "html");
app.set("views", __dirname + "/views");
app.use("/", express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/new_creature',function(req,res){
    res.render('new_creature/index');
});
app.post('/new_creature', function(req,res){
    res.end(JSON.stringify(req.body));
    console.log(req.body);
    // res.render('new_creature/index');
});
</code>```

and here is my views/creatures/new_creature/index.html file:

```<code><form method="POST" action="/new_creature">
    Species:<input type="text">
    Family:<input type="text">
    Habitat:<input type="text">
    Diet:<input type="text">
    Planet:<input type="text">
    <input type="submit" placeholder="submit">
</form>
</code>```

答:
If you want bodyparser to work you need to have name attributes on your form elements that you want posted.  For example:

```<code><form method="POST" action="/new_creature">
    Species:<input name='species' type="text">
    Family:<input name='family' type="text">
    Habitat:<input name='habitat' type="text">
    Diet:<input name='diet' type="text">
    Planet:<input name='planet' type="text">
    <input type="submit" value="submit">
</form>
</code>```

Also, placeholder doesn't make sense on a submit button; placeholder is the ghost text that's supposed to show in an input that hasnt' been filled.

Body:
I'm new to backend javascript and I have a form that on submit is supposed to show the submitted object, but it's displaying an empty object instead. I've included body-parser so I'm not sure where the issue is. Here is my app.js file:

const express = require("express");
const app = express();
const mustacheExpress = require("mustache-express");
const bodyParser = require("body-parser");
const pgp = require("pg-promise")();

app.engine("html", mustacheExpress());
app.set("view engine", "html");
app.set("views", __dirname + "/views");
app.use("/", express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/new_creature',function(req,res){
    res.render('new_creature/index');
});
app.post('/new_creature', function(req,res){
    res.end(JSON.stringify(req.body));
    console.log(req.body);
    // res.render('new_creature/index');
});

and here is my views/creatures/new_creature/index.html file:

<form method="POST" action="/new_creature">
    Species:<input type="text">
    Family:<input type="text">
    Habitat:<input type="text">
    Diet:<input type="text">
    Planet:<input type="text">
    <input type="submit" placeholder="submit">
</form>

Body:
If you want bodyparser to work you need to have name attributes on your form elements that you want posted.  For example:

<form method="POST" action="/new_creature">
    Species:<input name='species' type="text">
    Family:<input name='family' type="text">
    Habitat:<input name='habitat' type="text">
    Diet:<input name='diet' type="text">
    Planet:<input name='planet' type="text">
    <input type="submit" value="submit">
</form>

Also, placeholder doesn't make sense on a submit button; placeholder is the ghost text that's supposed to show in an input that hasnt' been filled.


问:
What's the correct way to redirect to a different relative URL path in AngularJS? (i.e. change URL - with maybe $location.path - and then refresh)
Suppose this is my HTML (which gets served when accessing the path /:

```<code><form ng-submit="ctrl.loginUser()" name="myLoginForm">
    <div class="form-group">
        <label>Username</label>
        <input type="text" name="uname" class="form-control" ng-model="ctrl.loginuser.username" required>
    </div>

    <div class="form-group">
        <label>Password</label>
        <input type="password" name="pwd" class="form-control" ng-model="ctrl.loginuser.password" required>
    </div>

    <input type="submit" value="Login">
</form>
</code>```

This is the HTML page which shows up when I access /home (mainPage.html):

```<code><h5>TESTTT</h5>
</code>```

And this is what gets called when the form is submitted:

```<code>angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

self.loginUser = function(loginuser) {
    return $http.post("/custom-api-auth/login", loginuser)
    .then(function(response) {
        $location.url("/home");
    });
};
</code>```

I tried testing this and submitting the form. The URL does change to /home but the page which gets served when going to the URL www.url.com/home does not appear. The page does not refresh either.

As mentioned earlier, wen I go to www.url.com/home, mainPage.html does in fact show up.

What steps do I take to have it so that it correct redirects to the /home URL?

答:
The way I would to use ui-router you can read more here.

https://github.com/angular-ui/ui-router/wiki

You can use resolve to provide your controller with content or data that is custom to the state. In this case if you want to go to test, but previously you need to fullfill a promise this would be an example.

```<code>$stateProvider.state('test', {
  resolve:{

     // Example using function with simple return value.
     // Since it's not a promise, it resolves immediately.
     simpleObj:  function(){
        return {value: 'simple!'};
     },

     // Example using function with returned promise.
     // This is the typical use case of resolve.
     // You need to inject any services that you are
     // using, e.g. $http in this example
     promiseObj:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/someUrl'});
     },

  },
</code>```

Body:
Suppose this is my HTML (which gets served when accessing the path /:

<form ng-submit="ctrl.loginUser()" name="myLoginForm">

        Username
        <input type="text" name="uname" class="form-control" ng-model="ctrl.loginuser.username" required>

        Password
        <input type="password" name="pwd" class="form-control" ng-model="ctrl.loginuser.password" required>

    <input type="submit" value="Login">
</form>

This is the HTML page which shows up when I access /home (mainPage.html):

TESTTT

And this is what gets called when the form is submitted:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

self.loginUser = function(loginuser) {
    return $http.post("/custom-api-auth/login", loginuser)
    .then(function(response) {
        $location.url("/home");
    });
};

I tried testing this and submitting the form. The URL does change to /home but the page which gets served when going to the URL www.url.com/home does not appear. The page does not refresh either.

As mentioned earlier, wen I go to www.url.com/home, mainPage.html does in fact show up.

What steps do I take to have it so that it correct redirects to the /home URL?

Body:
The way I would to use ui-router you can read more here.

https://github.com/angular-ui/ui-router/wiki

You can use resolve to provide your controller with content or data that is custom to the state. In this case if you want to go to test, but previously you need to fullfill a promise this would be an example.

$stateProvider.state('test', {
  resolve:{

     // Example using function with simple return value.
     // Since it's not a promise, it resolves immediately.
     simpleObj:  function(){
        return {value: 'simple!'};
     },

     // Example using function with returned promise.
     // This is the typical use case of resolve.
     // You need to inject any services that you are
     // using, e.g. $http in this example
     promiseObj:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/someUrl'});
     },

  },


问:
Best way to link a FCM token to a device?
I'm making a server that sends messages using FCM to clients depending on what happens (temperature and/or humidity change, a door is opened, etc.).

But if the token can change, how can I keep track of the device to send messages to the correct one (w/o using a login system)?

I was thinking to link the token to the sim iccid in a database, is this correct?

答:
Update 05/18/2017:

Starting Android O, ANDROID_ID will now be different per app per user in the device.

Original Answer:

If you're looking for a long lasting (possibly permanent) ID that you can use, I guess you can make use of ANDROID_ID:

 String ANDROID_ID

A 64-bit number (as a hex string) that is randomly generated when the user first sets up the device and should remain constant for the lifetime of the user's device. The value may change if a factory reset is performed on the device.

Note: When a device has multiple users (available on certain devices running Android 4.2 or higher), each user appears as a completely separate device, so the ANDROID_ID value is unique to each user.

Constant Value: "android_id"

However, there are still some factors that you should consider depending on your use-case. I recommend going through the Best Practices for Unique Identifiers documentation.

FCM wise, it is usually associated with a user, hence it is commonly paired with the user details.


问:
How do I download a file by knowing the file name only using jQuery?
I am trying to download a file using jQuery. The problem is I have no reference about the file extension. I only know the file name. The file name is unique because it shares the same name with the primary key. So, no file is the same.

This is the jQuery I use:

```<code>$("#tbl_surat_all tbody").on('click','.row_surat', function(e) {
    var no_s    = $(this).find('a').html(); //get the file name
    var b_url   = $('#base_url').val()+"assets/uploads/surat/"; //base_url

    var url     = b_url+no_s; //download_url

    window.location = url; //script_to_download
});
</code>```

How do I download the file by only knowing the file name??

Note:

I have no privilage to change table structure, so I can't update the upload script.

The file are images, pdfs, and rars

答:
There is no way to open the file from the server without sending a valid request.

If you don't request the complete file name with extension, you will get an error.

So the only workaround would be to request all possible file extensions.

We could try to include the following:

```<code>.jpeg .jpg .png .pdf .rar
</code>```

And then iterate it with requests.

Since this would open a **** load of windows, we will be immediately closing them, so it will look relatively smooth.

Here is the code:

```<code>var url_base='http://127.0.0.1/base_url/file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];

for (i=0;i<ext_arr.length;i++){
    var url=url_base+ext_arr[i];
    window.open(url)
        .addEventListener('load', function(){
            this.close();
    }, false);
}
</code>```

Note: do note that in order for it work properly, requested files must meet the same origin policy.

Edit: I have modified the above code to load resources in background via xhttp requests and then output it directly for download.

This method should work flawlessly for all types of files, and it's also the fastest!

```<code>var url_base='http://127.0.0.1/';
var file_name='file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];

for (i=0;i<ext_arr.length;i++){
    // Define request url
    var url=url_base+file_name+ext_arr[i];
    // Use XMLHttpRequest instead of Jquery $ajax
    var xhttp = new XMLHttpRequest();
    // Set the url as a property
    xhttp['user_filename']=file_name;
    // Bind on ready function
    xhttp.onreadystatechange = function() {
        var a;
        // Check if page has loaded successfully
        if (this.readyState === 4 && this.status === 200) {
            // Trick for making downloadable link
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(this.response);
            // Filename for downloading
            a.download = this.user_filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.parentNode.removeChild(a);
        }
    };
    // Set request url and method
    xhttp.open("GET", url);
    // Set responseType as blob for binary response
    xhttp.responseType = 'blob';
    // Send request
    xhttp.send();
}
</code>```

Body:
I am trying to download a file using jQuery. The problem is I have no reference about the file extension. I only know the file name. The file name is unique because it shares the same name with the primary key. So, no file is the same.

This is the jQuery I use:

$("#tbl_surat_all tbody").on('click','.row_surat', function(e) {
    var no_s    = $(this).find('a').html(); //get the file name
    var b_url   = $('#base_url').val()+"assets/uploads/surat/"; //base_url

    var url     = b_url+no_s; //download_url

    window.location = url; //script_to_download
});

How do I download the file by only knowing the file name??

Note:

I have no privilage to change table structure, so I can't update the upload script.

The file are images, pdfs, and rars

Body:
There is no way to open the file from the server without sending a valid request.

If you don't request the complete file name with extension, you will get an error.

So the only workaround would be to request all possible file extensions.

We could try to include the following:

.jpeg .jpg .png .pdf .rar

And then iterate it with requests.

Since this would open a **** load of windows, we will be immediately closing them, so it will look relatively smooth.

Here is the code:

var url_base='http://127.0.0.1/base_url/file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];

for (i=0;i<ext_arr.length;i++){
    var url=url_base+ext_arr[i];
    window.open(url)
        .addEventListener('load', function(){
            this.close();
    }, false);
}

Note: do note that in order for it work properly, requested files must meet the same origin policy.

Edit: I have modified the above code to load resources in background via xhttp requests and then output it directly for download.

This method should work flawlessly for all types of files, and it's also the fastest!

var url_base='http://127.0.0.1/';
var file_name='file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];

for (i=0;i<ext_arr.length;i++){
    // Define request url
    var url=url_base+file_name+ext_arr[i];
    // Use XMLHttpRequest instead of Jquery $ajax
    var xhttp = new XMLHttpRequest();
    // Set the url as a property
    xhttp['user_filename']=file_name;
    // Bind on ready function
    xhttp.onreadystatechange = function() {
        var a;
        // Check if page has loaded successfully
        if (this.readyState === 4 && this.status === 200) {
            // Trick for making downloadable link
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(this.response);
            // Filename for downloading
            a.download = this.user_filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.parentNode.removeChild(a);
        }
    };
    // Set request url and method
    xhttp.open("GET", url);
    // Set responseType as blob for binary response
    xhttp.responseType = 'blob';
    // Send request
    xhttp.send();
}


问:
nhibernate libraries for medium trust environment
There have been so many discussions about this topic [nhibernate for medium trust]. Keen to know if there is a location where Nhibernate and dependent libraries compatible for medium trust are available.

That would be of great help.

答:
As a matter of fact, there is a place to get the files to run NHibernate in a medium trust environment without doing something crazy like disabling lazy loading. I wrote a blog post about it and have provided the link below.

How To Run NHibernate In A Medium Trust Environment Easily And Quickly

Getting the files is very simple so please have a look.

Good luck!


问:
jquery triggered after validation error
i am using laravel 5.3 with laravelcollective/html 5.2..
i made a checkbox that if that checked, a hidden input will come out and if i uncheck it the input will be hidden.. and after the validation request error from laravel the checkbox remain checked but the hidden input didnt show up.. please i need help.. thanks..

my checkbox html:

```<code><label>
{!! Form::checkbox('penerima_beda', '1', null, ['id' => 'penerima_beda']) !!}Penerima Berbeda
</label>
</code>```

and here is my jquery:

```<code>$("#penerima_beda").click(function() {
        if(this.checked){
            $("#panel_penerima").css("display", "block");
            $("#nama_penerima").attr("required", "required");
            $("#no_telp_penerima").attr("required", "required");
            $("#alamat_penerima").attr("required", "required");
            //console.log(this);
        }else if(!this.checked){
            $("#panel_penerima").css("display", "none");
            $("#nama_penerima").removeAttr("required");
            $("#no_telp_penerima").removeAttr("required");
            $("#alamat_penerima").removeAttr("required");
        }
    });
</code>```

答:
You need to add an check clause on document load to show the hidden input field</p>

```<code>$(document).ready(function () {

    // Show the input if the checkbox is checked
    if ($("#penerima_beda").is(":checked")) {
        $("#panel_penerima").css("display", "block");
        $("#nama_penerima").attr("required", "required");
        $("#no_telp_penerima").attr("required", "required");
        $("#alamat_penerima").attr("required", "required");
    }

    // This works only on click event
    $("#penerima_beda").click(function() {
        if(this.checked){
            $("#panel_penerima").css("display", "block");
            $("#nama_penerima").attr("required", "required");
            $("#no_telp_penerima").attr("required", "required");
            $("#alamat_penerima").attr("required", "required");
        }else if(!this.checked){
            $("#panel_penerima").css("display", "none");
            $("#nama_penerima").removeAttr("required");
            $("#no_telp_penerima").removeAttr("required");
            $("#alamat_penerima").removeAttr("required");
        }
    });

});
</code>```

Title: jquery triggered after validation error

Body:
i am using laravel 5.3 with laravelcollective/html 5.2..
i made a checkbox that if that checked, a hidden input will come out and if i uncheck it the input will be hidden.. and after the validation request error from laravel the checkbox remain checked but the hidden input didnt show up.. please i need help.. thanks..

my checkbox html:

{!! Form::checkbox('penerima_beda', '1', null, ['id' => 'penerima_beda']) !!}Penerima Berbeda

and here is my jquery:

$("#penerima_beda").click(function() {
        if(this.checked){
            $("#panel_penerima").css("display", "block");
            $("#nama_penerima").attr("required", "required");
            $("#no_telp_penerima").attr("required", "required");
            $("#alamat_penerima").attr("required", "required");
            //console.log(this);
        }else if(!this.checked){
            $("#panel_penerima").css("display", "none");
            $("#nama_penerima").removeAttr("required");
            $("#no_telp_penerima").removeAttr("required");
            $("#alamat_penerima").removeAttr("required");
        }
    });

Body:
You need to add an check clause on document load to show the hidden input field

$(document).ready(function () {

    // Show the input if the checkbox is checked
    if ($("#penerima_beda").is(":checked")) {
        $("#panel_penerima").css("display", "block");
        $("#nama_penerima").attr("required", "required");
        $("#no_telp_penerima").attr("required", "required");
        $("#alamat_penerima").attr("required", "required");
    }

    // This works only on click event
    $("#penerima_beda").click(function() {
        if(this.checked){
            $("#panel_penerima").css("display", "block");
            $("#nama_penerima").attr("required", "required");
            $("#no_telp_penerima").attr("required", "required");
            $("#alamat_penerima").attr("required", "required");
        }else if(!this.checked){
            $("#panel_penerima").css("display", "none");
            $("#nama_penerima").removeAttr("required");
            $("#no_telp_penerima").removeAttr("required");
            $("#alamat_penerima").removeAttr("required");
        }
    });

});


答:
list is accessed by its index
suppose list1 = [3,4,1,2,5]
to access list element i need to provide index of that element. index start with 0 to n. suppose i want to access second element of list

```<code>print list1[1]

#out: 4
</code>```

to iterate through list element

```<code>for i in list1:
   print list1[i]
</code>```

in your code you are accessing list index by  another list.

Title: Adding 1 to elements of an empty list using another list to count up (maybe with += ?)

Body:
list is accessed by its index
suppose list1 = [3,4,1,2,5]
to access list element i need to provide index of that element. index start with 0 to n. suppose i want to access second element of list

print list1[1]

#out: 4

to iterate through list element

for i in list1:
   print list1[i]

in your code you are accessing list index by  another list.


问:
function return tuple. sometimes get lists, sometimes get tuple
I write a function to return multiple lists(at least one). It is looks like below:

```<code>def get_stock_atrributes_data(stock, attrList):
    dbClient = MongoClient()
    db = dbClient.StockAnnual
    #only query the data we need
    query = {attr: 1 for attr in attrList}
    #exclude id
    query['_id'] = 0
    cursor = db[stock].find({}, query).sort([('date', pymongo.ASCENDING)])
    #tranform cursor to list so it becomes iterative
    l = list(cursor)
    res = []
    for attr in attrList:
        res.append([d[attr] for d in l])
    return tuple(res)
</code>```

In order to do it, I use tuple so I can use

```<code>list1, list2 = get_stock_atrributes_data()
</code>```

to query multiple attributes lists determined by the attrList. When I return multiple lists(more than one), it works quite well. But if I only return one list, the result is a tuple containing one list, for example:

```<code>list1 = get_stock_atrributes_data()
</code>```

The list1 is a tuple rather than a list now. I read some explanation about returning tuples. It is said that the elements in tuple will be unpacked and assigned automatically. For returned tuple with more than one elements, it works. But for tuple only containing one element, the result is not unpacked. I was confused by this and hope someone can give me explanation.

答:
Here's an example, you should be able to use it to modify your code and get the result you're after.

```<code>def retTup(x):
    return tuple(x)

a,b = retTup([[1,2,3],[4,5,6]])
</code>```

This will give:

```<code>a = [1,2,3]
b = [4,5,6]
</code>```

Now, if I do:

```<code>a = retTup([[1,2,3]])
</code>```

I will get a tuple for a:

```<code>a = ([1,2,3],)
</code>```

So instead I retrieve the list as: (notice the comma)

```<code>a, = retTup([[1,2,3]])
</code>```

And now:

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

As desired.

Body:
I write a function to return multiple lists(at least one). It is looks like below:

def get_stock_atrributes_data(stock, attrList):
    dbClient = MongoClient()
    db = dbClient.StockAnnual
    #only query the data we need
    query = {attr: 1 for attr in attrList}
    #exclude id
    query['_id'] = 0
    cursor = db[stock].find({}, query).sort([('date', pymongo.ASCENDING)])
    #tranform cursor to list so it becomes iterative
    l = list(cursor)
    res = []
    for attr in attrList:
        res.append([d[attr] for d in l])
    return tuple(res)

In order to do it, I use tuple so I can use

list1, list2 = get_stock_atrributes_data()

to query multiple attributes lists determined by the attrList. When I return multiple lists(more than one), it works quite well. But if I only return one list, the result is a tuple containing one list, for example:

list1 = get_stock_atrributes_data()

The list1 is a tuple rather than a list now. I read some explanation about returning tuples. It is said that the elements in tuple will be unpacked and assigned automatically. For returned tuple with more than one elements, it works. But for tuple only containing one element, the result is not unpacked. I was confused by this and hope someone can give me explanation.

Body:
Here's an example, you should be able to use it to modify your code and get the result you're after.

def retTup(x):
    return tuple(x)

a,b = retTup([[1,2,3],[4,5,6]])

This will give:

a = [1,2,3]
b = [4,5,6]

Now, if I do:

a = retTup([[1,2,3]])

I will get a tuple for a:

a = ([1,2,3],)

So instead I retrieve the list as: (notice the comma)

a, = retTup([[1,2,3]])

And now:

a = [1,2,3]

As desired.


问:
Non-invocable member cannot be used like a method(Batches)
I am writing a C# code for the database. I am getting the following error. Can somebody please help me out.

Error: Severity   Code    Description Project File    Line    Suppression State
  Error CS1955  Non-invocable member 'BatchEntities.Batches' cannot be
  used like a method.   AddBatch    C:\Users\SA051263\documents\visual studio
  2015\Projects\AddBatch\AddBatch\Controllers\HomeController.cs 45  Active

Code:

```<code>    public HomeController()
    {
        _db = new BatchEntities();
    }

    public ActionResult Index()
    {
        ViewData.Model = _db.Batches.ToList();
        return View();
    }
    public ActionResult Add()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(FormCollection form)
    {
        var batchToAdd = new Batch();

        // Deserialize (Include white list!)
        TryUpdateModel(batchToAdd, new string[] { "BatchName", "StartDate" }, form.ToValueProvider());

        // Validate
        if (String.IsNullOrEmpty(batchToAdd.BatchName))
            ModelState.AddModelError("Title", "Title is required!");

        // If valid, save movie to database
        if (ModelState.IsValid)
        {

            _db.Batches(batchToAdd);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        // Otherwise, reshow form
        return View(batchToAdd);
    }
</code>```

答:
Your problem is here -

```<code>if (ModelState.IsValid)
{

    **_db.Batches(batchToAdd);**
    _db.SaveChanges();
    return RedirectToAction("Index");
}
</code>```

_db.Batches is a property, (probably with signature DbSet<Batch>), not a function.

Try something like this -

```<code>if (ModelState.IsValid)
{
    **foreach(var b in batchToAdd){
        _db.Batches.Add(b);
    }**
    _db.SaveChanges();
    return RedirectToAction("Index");
}
</code>```

Body:
I am writing a C# code for the database. I am getting the following error. Can somebody please help me out.

Error: Severity   Code    Description Project File    Line    Suppression State
  Error CS1955  Non-invocable member 'BatchEntities.Batches' cannot be
  used like a method.   AddBatch    C:\Users\SA051263\documents\visual studio
  2015\Projects\AddBatch\AddBatch\Controllers\HomeController.cs 45  Active

Code:

    public HomeController()
    {
        _db = new BatchEntities();
    }

    public ActionResult Index()
    {
        ViewData.Model = _db.Batches.ToList();
        return View();
    }
    public ActionResult Add()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(FormCollection form)
    {
        var batchToAdd = new Batch();

        // Deserialize (Include white list!)
        TryUpdateModel(batchToAdd, new string[] { "BatchName", "StartDate" }, form.ToValueProvider());

        // Validate
        if (String.IsNullOrEmpty(batchToAdd.BatchName))
            ModelState.AddModelError("Title", "Title is required!");

        // If valid, save movie to database
        if (ModelState.IsValid)
        {

            _db.Batches(batchToAdd);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        // Otherwise, reshow form
        return View(batchToAdd);
    }

Body:
Your problem is here -

if (ModelState.IsValid)
{

    **_db.Batches(batchToAdd);**
    _db.SaveChanges();
    return RedirectToAction("Index");
}

_db.Batches is a property, (probably with signature DbSet<Batch>), not a function.

Try something like this -

if (ModelState.IsValid)
{
    **foreach(var b in batchToAdd){
        _db.Batches.Add(b);
    }**
    _db.SaveChanges();
    return RedirectToAction("Index");
}


问:
amazon EMR hive execution error
I am trying to run a simple hive job using amazon EMR console. Every time I get an error stating "Error missing argument base-path" and the hive job fails. Can any one suggest me how to resolve it.

I have inserted the input file into the s3://bucket/inputs location, the script in s3:// bucket / script, and my hive query is as follows:

```<code>create external table table_name(
 string var 1,
 string var 2....)
Row format delimited
fields terminated by '/t'
location 's3://bucket/outputs'
load data inpath 's3://bucket/inputs/data.txt' into table table_name )
</code>```

In the amazon EMR job flow I have followed all the instructions provided by the amazon documentation. I am a beginner in this field. Is there any need to pass any argument in the arguments lists section in the hive job creation.

Thanks in advance

答:
Try this:

```<code>-- start
SET mapred.input.dir.recursive=true;
CREATE EXTERNAL TABLE table_name (string line)
LOCATION 's3n://bucket/inputs/';
</code>```

or

```<code>LOCATION 's3n://bucket/*/*';
</code>```

I think it works.

Apache Pig requires protocol s3:// , however hive requires s3n://. I don't know why.

See this site: S3 Support in Apache Hadoop, there are three types of s3 file prefix.

S3A (URI scheme: s3a://) - Hadoop 2.7+

S3N FileSystem (URI scheme: s3n://)

S3 Block FileSystem (URI scheme: s3://)

Title: amazon EMR hive execution error

Body:
I am trying to run a simple hive job using amazon EMR console. Every time I get an error stating "Error missing argument base-path" and the hive job fails. Can any one suggest me how to resolve it.

I have inserted the input file into the s3://bucket/inputs location, the script in s3:// bucket / script, and my hive query is as follows:

create external table table_name(
 string var 1,
 string var 2....)
Row format delimited
fields terminated by '/t'
location 's3://bucket/outputs'
load data inpath 's3://bucket/inputs/data.txt' into table table_name )

In the amazon EMR job flow I have followed all the instructions provided by the amazon documentation. I am a beginner in this field. Is there any need to pass any argument in the arguments lists section in the hive job creation.

Thanks in advance

Body:
Try this:

-- start
SET mapred.input.dir.recursive=true;
CREATE EXTERNAL TABLE table_name (string line)
LOCATION 's3n://bucket/inputs/';

or

LOCATION 's3n://bucket/*/*';

I think it works.

Apache Pig requires protocol s3:// , however hive requires s3n://. I don't know why.

See this site: S3 Support in Apache Hadoop, there are three types of s3 file prefix.

S3A (URI scheme: s3a://) - Hadoop 2.7+

S3N FileSystem (URI scheme: s3n://)

S3 Block FileSystem (URI scheme: s3://)


问:
SQL syntax error
I'm trying to execute this query:

```<code>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion')
THEN ALTER TABLE MyTableName DROP COLUMN ColumnInQuestion;
</code>```

And I get the following error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'articles'' at line 1

I'm using MySQL 5.1.something, so I don't think information_schema not being defined is the issue. Any ideas?

Thank you for your help!

答:
You have a couple of options.

One option is to just run the ALTER TABLE command and ignore the error if the column doesn't exist.

Another option closer in spirit to your original attempt is to conditionally dump the DDL to a SQL script on disk if the column exists, then source that SQL script to run the DDL (if any).

Here's an example:

```<code>-- delete the SQL script if it exists
\! rm /tmp/drop_column.sql

-- Conditionally dump the DDL to a SQL script if the column exists
SELECT concat('ALTER TABLE ',table_schema,'.',table_name,
' DROP COLUMN ',column_name,';') as sql_stmt
into outfile '/tmp/drop_column.sql'
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion';

-- execute the SQL script
\. /tmp/drop_column.sql

-- delete the SQL script from disk
\! rm /tmp/drop_column.sql
</code>```

Title: SQL syntax error

Body:
I'm trying to execute this query:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion')
THEN ALTER TABLE MyTableName DROP COLUMN ColumnInQuestion;

And I get the following error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'articles'' at line 1

I'm using MySQL 5.1.something, so I don't think information_schema not being defined is the issue. Any ideas?

Thank you for your help!

Body:
You have a couple of options.

One option is to just run the ALTER TABLE command and ignore the error if the column doesn't exist.

Another option closer in spirit to your original attempt is to conditionally dump the DDL to a SQL script on disk if the column exists, then source that SQL script to run the DDL (if any).

Here's an example:

-- delete the SQL script if it exists
\! rm /tmp/drop_column.sql

-- Conditionally dump the DDL to a SQL script if the column exists
SELECT concat('ALTER TABLE ',table_schema,'.',table_name,
' DROP COLUMN ',column_name,';') as sql_stmt
into outfile '/tmp/drop_column.sql'
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion';

-- execute the SQL script
\. /tmp/drop_column.sql

-- delete the SQL script from disk
\! rm /tmp/drop_column.sql


答:
Change _db.Batches(batchToAdd) to _db.Batches.Add(batchToAdd).

You are using a class member as a member function.

Title: Non-invocable member cannot be used like a method(Batches)


问:
java : Is it possible to dynamically modify the code of a servlet's method (like doPost)
I'm trying to write a Framework like Spring MVC.
I'm looking for a way to modify the code of the doPost/doGet method of a servlet 3.0 deployed on tomcat using javassist or reflection or whatever so the doPost can call a service method dynamically defined .

```<code>doPost(...){

    ServiceClassName.methodeName(); // dynamic line of code

}
</code>```

Thanks

答: Although I have never tried it before, have a look at http://www.bytebuddy.net for a bytecode creation/manipulation library.</p>

Body:
I'm trying to write a Framework like Spring MVC.
I'm looking for a way to modify the code of the doPost/doGet method of a servlet 3.0 deployed on tomcat using javassist or reflection or whatever so the doPost can call a service method dynamically defined .

doPost(...){

    ServiceClassName.methodeName(); // dynamic line of code

}

Thanks


问:
Convert float number from nonuniform ranges
So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

```<code> {-30.0, 30.0} -> {25.0, 50.0}
</code>```

that would have been easy.
But I have a set of ranges:

```<code> {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}
</code>```

One solution is to do a linear search on each access.
Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

答:
This is an elaboration on the solution presented by @user1034749. It uses an std::set with a class that contains two pairs of values.

```<code>template<class SRC, class DST>
class Range {
 public:
  std::pair<SRC, SRC> src_range;
  std::pair<DST, DST> dst_range;

  bool operator<(const Range& rhs) const {
    return (src_range.first < rhs.src_range.first) && (src_range.second < rhs.src_range.second);
  }

  Range(SRC src_first, SRC src_second,
        DST dst_first, DST dst_second)
  : src_range(src_first, src_second),
    dst_range(dst_first, dst_second) {}

  Range()
  : src_range(0, 0),
    dst_range(0, 0) {}

  Range(SRC value)
  : src_range(value, value),
    dst_range(value, value) {}
};

bool mapping_test() {
  // Mapping
  std::set<Range<double,double>>
          z = {{-30.0, -20.0, -10.0, -5.0},
               {-20.0, 0, -5.0, 5.0},
               {0, 10.0, 5.0, 8.0}};

  // Find range that contains this value
  Range<double,double> f{8.0};

  auto d = z.find(f);
  if(d != z.end()) {
    std::cout << "Found {" << (*d).dst_range.first
                           << ","
                           << (*d).dst_range.second
                           << "}\n";
  }

  return true;
}
</code>```

In this case the range for the value in question could be found including source range as well as destination. Lookup in the std::set container is log(n) complexity.

Body:
So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

 {-30.0, 30.0} -> {25.0, 50.0}

that would have been easy.
But I have a set of ranges:

 {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}

One solution is to do a linear search on each access.
Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

Body:
This is an elaboration on the solution presented by @user1034749. It uses an std::set with a class that contains two pairs of values.

template<class SRC, class DST>
class Range {
 public:
  std::pair<SRC, SRC> src_range;
  std::pair<DST, DST> dst_range;

  bool operator<(const Range& rhs) const {
    return (src_range.first < rhs.src_range.first) && (src_range.second < rhs.src_range.second);
  }

  Range(SRC src_first, SRC src_second,
        DST dst_first, DST dst_second)
  : src_range(src_first, src_second),
    dst_range(dst_first, dst_second) {}

  Range()
  : src_range(0, 0),
    dst_range(0, 0) {}

  Range(SRC value)
  : src_range(value, value),
    dst_range(value, value) {}
};

bool mapping_test() {
  // Mapping
  std::set<Range<double,double>>
          z = {{-30.0, -20.0, -10.0, -5.0},
               {-20.0, 0, -5.0, 5.0},
               {0, 10.0, 5.0, 8.0}};

  // Find range that contains this value
  Range<double,double> f{8.0};

  auto d = z.find(f);
  if(d != z.end()) {
    std::cout << "Found {" << (*d).dst_range.first
                           << ","
                           << (*d).dst_range.second
                           << "}\n";
  }

  return true;
}

In this case the range for the value in question could be found including source range as well as destination. Lookup in the std::set container is log(n) complexity.


问:
Why does this html table definition not validate?
I'm getting this W3C HTML validation error:

```<code>end tag for "table" which is not finished
</code>```

for this code:

```<code><table id="myTable">
</table>
</code>```

This is my DOCTYPE:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</code>```

I thought that table definition was perfectly fine!?

答: I believe there should be a tr and td  tags inside a table to validate. It's the same when you close a head tag without including a title tag</p>

Body:
I'm getting this W3C HTML validation error:

end tag for "table" which is not finished

for this code:

This is my DOCTYPE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

I thought that table definition was perfectly fine!?