问:
How to store different types of nodes in one linked-list?
I am trying to store different types of nodes in one linked-list , i built a structure

```<code>struct node{struct node *next};
</code>```

and two classes ,

the first class is

```<code>class doc1
{
 private : int data ;
}
</code>```

the second class is

```<code>class doc2
{
 private : double number ;
}
</code>```

and a class to contain the whole list

```<code>class list : public doc1 ,public doc2
{
public : void add_node();
private : struct node * head = NULL ;
}
</code>```

Actually i am asking how to make the "head" pointer point to different nodes -each node may contain an object from two different classes-.

Is template good to solve this problem ?!

Thanks .

答:
and a class to contain the whole list

```<code>class list : public doc1 ,public doc2
{
public : void add_node();
private : struct node * head = NULL ;
}
</code>```

Sorry I need to say that, but that doesn't make any sense.

Inheritance is the not the right tool aggregate something.

Your list contains doc1 and doc2 instances, but neither is a doc1 or doc2, but owns these or collects weak references.

The most flexible way to do this is to provide a common (abstract) base class for the doc types and store a std::unique_ptr for them in the node class:

```<code>class doc {
protected:   // make doc abstract, it can only be used with directly inheriting
    doc() {} // classes
public:
    virtual ~doc() {} // make doc polymorphic
};

class doc1 : public doc {
    // special stuff
};

class doc2 : public doc {
    // special stuff
};

struct node {
    node *next;
    std::unique_ptr<doc> doc_data;
};
</code>```

```<code>class list {
public:
    list() : head(nullptr) {}
    template<tyoename T>
    void add_node(const T& data) {
         static_assert("data must derive from doc",std::is_base_of<doc,T>::value);
         node* newNode = new node(); // Note you still need to do the memory
                                     // management for your node instances!
         newNode->doc_data = std::make_unique<T>(data); // T needs to be
                                                        // copy constructible
         // linked list management code ...
    }
private:
    node* head;
}
</code>```

Is template good to solve this problem ?!

As you see from my example above I used a templated add_node() function to make taking doc1 or doc2 types convenient.

A template can also help to make your whole list class working for arbitrary data types:

```<code>template<typename T>
class MyList {
public:
    // I'm using a nested node type here
    struct node {
        node* next;
        T data;
        node() : next(nullptr), data() {}
        node(const T& value): next(nullptr), data(value) {}
    };

    MyList() : head(nullptr) {}
    void add_node(const T& value) {
        node* new_node = new node(value);
        // linked list management code ...
    }
private:
    node* head;
};
</code>```

For the above implementation you can also take advantage of std::unique_ptr for the contained doc instances and mix the types:

```<code>MyList<std::unique_ptr<doc>> myList;
</code>```

That of course also works for unrelated types then like:

```<code>MyList<doc1> myDoc1List;
MyList<doc2> myDoc2List;
MyList<int> myInt1List;
MyList<double> myDouble1List;
</code>```

The way easiest thing of course is to just use the already existing linked list implementation of the c++ standard containers library:

```<code>std::list<std::unique_ptr<doc>> myLinkedDocList;
</code>```

Body:
I am trying to store different types of nodes in one linked-list , i built a structure

struct node{struct node *next};

and two classes ,

the first class is

class doc1
{
 private : int data ;
}

the second class is

class doc2
{
 private : double number ;
}

and a class to contain the whole list

class list : public doc1 ,public doc2
{
public : void add_node();
private : struct node * head = NULL ;
}

Actually i am asking how to make the "head" pointer point to different nodes -each node may contain an object from two different classes-.

Is template good to solve this problem ?!

Thanks .

Body:
and a class to contain the whole list

class list : public doc1 ,public doc2
{
public : void add_node();
private : struct node * head = NULL ;
}

Sorry I need to say that, but that doesn't make any sense.

Inheritance is the not the right tool aggregate something.

Your list contains doc1 and doc2 instances, but neither is a doc1 or doc2, but owns these or collects weak references.

The most flexible way to do this is to provide a common (abstract) base class for the doc types and store a std::unique_ptr for them in the node class:

class doc {
protected:   // make doc abstract, it can only be used with directly inheriting
    doc() {} // classes
public:
    virtual ~doc() {} // make doc polymorphic
};

class doc1 : public doc {
    // special stuff
};

class doc2 : public doc {
    // special stuff
};

struct node {
    node *next;
    std::unique_ptr<doc> doc_data;
};

class list {
public:
    list() : head(nullptr) {}
    template<tyoename T>
    void add_node(const T& data) {
         static_assert("data must derive from doc",std::is_base_of<doc,T>::value);
         node* newNode = new node(); // Note you still need to do the memory
                                     // management for your node instances!
         newNode->doc_data = std::make_unique<T>(data); // T needs to be
                                                        // copy constructible
         // linked list management code ...
    }
private:
    node* head;
}

Is template good to solve this problem ?!

As you see from my example above I used a templated add_node() function to make taking doc1 or doc2 types convenient.

A template can also help to make your whole list class working for arbitrary data types:

template<typename T>
class MyList {
public:
    // I'm using a nested node type here
    struct node {
        node* next;
        T data;
        node() : next(nullptr), data() {}
        node(const T& value): next(nullptr), data(value) {}
    };

    MyList() : head(nullptr) {}
    void add_node(const T& value) {
        node* new_node = new node(value);
        // linked list management code ...
    }
private:
    node* head;
};

For the above implementation you can also take advantage of std::unique_ptr for the contained doc instances and mix the types:

MyList<std::unique_ptr<doc>> myList;

That of course also works for unrelated types then like:

MyList<doc1> myDoc1List;
MyList<doc2> myDoc2List;
MyList<int> myInt1List;
MyList<double> myDouble1List;

The way easiest thing of course is to just use the already existing linked list implementation of the c++ standard containers library:

std::list<std::unique_ptr<doc>> myLinkedDocList;


来源: stackexchange

问:
Business Use Case and just Use Case
What's the difference between a Business Use-Case Model and a Use-Case model? I'm supposed to make both for a website, but I cannot understand what's the difference... Help?

答:
Perhaps an alternative description would help.

'Business' and 'System' Use Cases differ in scope. The former encompasses everything the customer and supplier have to do in order to complete the goal.  Some of that may involve a system interaction - but some may not.  As an example, take buying a book online.  Certain aspects will involve be completed online (e.g. browsing available books, placing order).  But some are not: picking the stock, packaging, shipping, signing for receipt of package.

A Business Use Case is a "black box" description of the entire interaction ("Buy Book").  Completing the task means following a business process.  Some of the steps in the process will involve a user-system interaction, some will not.  Where a step does involve a user and a system ("Browse available books") that step is a System Use Case.  Typically there will be a number of System Use Cases for a given Business Use Case.

So do you need both?  It depends on circumstances.

If you're (a) responsible for the complete business scope, and (b) want to document the business capabilities as Use Cases, then a Business UCD and supporting UC definitions is useful.  The steps in the UC description would represent the business process.

If someone else is responsible for the business-level definitions then you probably don't need to.

One final thing: sometimes the two are coincident.  For example: buying an eBook.  The Business Need is for the customer to be able to get their book.  The entire thing could be delivered in a single system interaction (select book, pay, receive download) - and so could be covered by a single System Use Case.  So the Business- and System Use Cases are equivalent.

hth.

ContentLicense: CC BY-SA 2.5

Title: Business Use Case and just Use Case


问:
How to use preprocessor directives inside a MENU in MFC .rc file?
I want to be able to dynamically change code in my resource file depending on which version of my app is being ran. For example, I have an about menu. I would like the about menuitem to have a different description based on a preprocessor directive. The issue I have is I am able to add the code in. But when I edit the resource file and save it, the .aps file overwrites my preprocessor directives. How can I get around this? The code below is an example of what I would like to have in my resource script.

```<code>IDR_EXAMPLE_MENU MENU
BEGIN

/*

Other Menu items

*/

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
#ifdef TEST_APP
    MENUITEM "&About TEST...",               ID_APP_ABOUT
#else
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
#endif
    END
END
</code>```

If I am running the TEST version I would like it to display "About TEST" in the menuitem and if it the RELEASE version I would like it to display "About RELEASE"
How can I add code like this to my resource file without having the .aps file overwrite the preprocessor directives when saving the .rc file?

Edit: This explains how files are affected by resource editing.

答:
You want to be able to use the resource editor of VS, but it only knows how to generate 1 kind of .rc output, and that is WITHOUT any of your #define values.  You can't have it both ways.  You can use compiler directives and edit the .rc (or .rc2) file by hand, or accept the output of VS.

A possibility may be to let you edit the file in VS using the resource editor, and then write a post-processing program that kind of understands the general content of your .RC and re-generate the "desired" .RC replacing the raw content with your compiler directives.  It's do-able, but the trade-offs are very specific to your application.

ContentLicense: CC BY-SA 3.0

Body:
I want to be able to dynamically change code in my resource file depending on which version of my app is being ran. For example, I have an about menu. I would like the about menuitem to have a different description based on a preprocessor directive. The issue I have is I am able to add the code in. But when I edit the resource file and save it, the .aps file overwrites my preprocessor directives. How can I get around this? The code below is an example of what I would like to have in my resource script.

IDR_EXAMPLE_MENU MENU
BEGIN

/*

Other Menu items

*/

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
#ifdef TEST_APP
    MENUITEM "&About TEST...",               ID_APP_ABOUT
#else
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
#endif
    END
END

If I am running the TEST version I would like it to display "About TEST" in the menuitem and if it the RELEASE version I would like it to display "About RELEASE"
How can I add code like this to my resource file without having the .aps file overwrite the preprocessor directives when saving the .rc file?

Edit: This explains how files are affected by resource editing.


问:
python: applying ** operator on user-defined class
I have created a custom class, and I want to use the ** operator on a instance for passing it to a function. I have already defined __getitem__ and __iter__, but when I try f(**my_object), I'm getting

```<code>`TypeError: argument must be a mapping, not 'MyClass'`
</code>```

What are the minimum required methods so that the custom class qualifies as a mapping?

答:
Emulating container types

The first set of methods is used [...] to emulate a mapping...

It is also recommended that mappings provide the methods keys(), values(), items(), get(), clear(), setdefault(), pop(), popitem(), copy(), and update() behaving similar to those for Python’s standard dictionary objects.

It is recommended that [...] mappings [...] implement the __contains__() method to allow efficient use of the in operator...

It is further recommended that [...] mappings [...] implement the __iter__() method to allow efficient iteration through the container

Body:
I have created a custom class, and I want to use the ** operator on a instance for passing it to a function. I have already defined __getitem__ and __iter__, but when I try f(**my_object), I'm getting

`TypeError: argument must be a mapping, not 'MyClass'`

What are the minimum required methods so that the custom class qualifies as a mapping?


问:
Remove space and Uppercase first letter

I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.

But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?

```<code>    package etzale;

public class etzale {

    public static void main(String[] args) {

        StringBuilder outputString= new StringBuilder();

        String satz;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}
</code>```

How can i erase the space between the last word and "." in each sentence?

```<code>Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  .
</code>```

答:
OK, appart from your code not being very appealing, you have a typo in your code that is causing you trouble:

```<code>outputString.append(" ");
</code>```

Remove that semicolon at the end and you will not have spaces before dots.

Title: Remove space and Uppercase first letter

Body:
I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.

But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?

    package etzale;

public class etzale {

    public static void main(String[] args) {

        StringBuilder outputString= new StringBuilder();

        String satz;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}

How can i erase the space between the last word and "." in each sentence?

Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  .

Body:
OK, appart from your code not being very appealing, you have a typo in your code that is causing you trouble:

outputString.append(" ");

Remove that semicolon at the end and you will not have spaces before dots.


问:
Is it safe to reuse a SqlDataRecord?
When implementing table-valued parameters, one of the most common ways to generate an IEnumerable<SqlDataRecord> for use by the parameter is code like this (e.g., https://stackoverflow.com/a/10779567/18192 ):

```<code>public static IEnumerable<SqlDataRecord> Rows(List<int> simpletable)
{
    var smd = new []{ new SqlMetaData("id", SqlDbType.Int)};
    var sqlRow = new SqlDataRecord(smd);
    foreach (int i in simpletable)
    {
        sqlRow.SetInt32(0, i);
        yield return sqlRow;
    }
}
//...
var param = sqlCmd.Parameters.AddWithValue("@retailerIDs", Rows(mydata));
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "myTypeName";
</code>```

This code does seem to work.  While reusing SqlMetaData does not set off too many alarm bells, declaring the SqlDataRecord outside the foreach loop feels incredibly suspicious to me:

A mutable object is modified and then yielded repeatedly.

As an example of why this is concerning, calling var x = Rows(new[] { 100, 200}.ToList()).ToList().Dump() in LinqPad spits out 200,200.  This approach seems to rely on an implementation detail (that rows are processed individually), but I don't see any documentation which promises this.

Is there some mitigating factor which renders this approach safe?

答:
This approach seems to rely on an implementation detail (that rows are
  processed individually), but I don't see any documentation which
  promises this.

Is there some mitigating factor which renders this approach safe?

As user1249190 points out, Reusing SQLDataRecord is explicitly recommended in the remarks section of https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.server.sqldatarecord#remarks :

This class is used together with SqlPipe to send result sets to the
  client from managed code stored-procedures. When writing common
  language runtime (CLR) applications, you should re-use existing
  SqlDataRecord objects instead of creating new ones every time.
  Creating many new SqlDataRecord objects could severely deplete memory
  and adversely affect performance.

Obviously this recommendation does not apply to usage across threads: The documentation also explicitly warns that "Any instance members are not guaranteed to be thread safe."

Title: Is it safe to reuse a SqlDataRecord?

Body:
When implementing table-valued parameters, one of the most common ways to generate an IEnumerable<SqlDataRecord> for use by the parameter is code like this (e.g., https://stackoverflow.com/a/10779567/18192 ):

public static IEnumerable<SqlDataRecord> Rows(List<int> simpletable)
{
    var smd = new []{ new SqlMetaData("id", SqlDbType.Int)};
    var sqlRow = new SqlDataRecord(smd);
    foreach (int i in simpletable)
    {
        sqlRow.SetInt32(0, i);
        yield return sqlRow;
    }
}
//...
var param = sqlCmd.Parameters.AddWithValue("@retailerIDs", Rows(mydata));
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "myTypeName";

This code does seem to work.  While reusing SqlMetaData does not set off too many alarm bells, declaring the SqlDataRecord outside the foreach loop feels incredibly suspicious to me:

A mutable object is modified and then yielded repeatedly.

As an example of why this is concerning, calling var x = Rows(new[] { 100, 200}.ToList()).ToList().Dump() in LinqPad spits out 200,200.  This approach seems to rely on an implementation detail (that rows are processed individually), but I don't see any documentation which promises this.

Is there some mitigating factor which renders this approach safe?

ContentLicense: CC BY-SA 4.0


问:
Angular: passing large text strings between components
(Advanced warning... I am very new to Angular, so my question may be naive and/or not make sense...)

I'm working on an Angular project (v. 5), and I need to pass a long-ish string (a large XML document - about 1mb) from a parent to a child component.

One option to do this is to use an @Input in the child component. I've tested this and it "works", although I don't know if it's a "good idea" for this large an amount of data.

A second option is to use @ViewChild(). E.g.,

In the parent.ts:

```<code>// set the child component as a @ViewChild
@ViewChild(ChildChartComponent)
private childChartComponent: ChildChartComponent;

// [get the xmlString from a service]
// ... then pass it to the child ...
this.childChartComponent.loadData(xmlString);
</code>```

In the child.ts:

```<code>loadData(xmlString):void {
  // receive the xmlString, parse it, then extract and display the data
}
</code>```

A few notes...

As I mentioned - the XML is pretty large - could be 1mb or more.

After the XML data is obtained by the parent, passed to the child, then parsed and processed, there's no need to "maintain" it. (I.e., I'd like it garbage-collected).

I don't really know how Angular is working under the hood, or actually passing that data from the parent to the child. But the @INPUT approach makes it look like the string is written as an attribute value:

<child-chart [xmlString]="xmlString"></child-chart>

I suspect that Angular isn't actually writing that 1mb string into an attribute property that's bloating the DOM and sitting there after it's now longer needed, but I don't really know...

So - is either one of these methods preferred for passing very long strings? Or is there an altogether different, but preferrable method?

答: As you mentioned both ways get the job done, But angular is meant to be agnostic. We shouldn't be mixing the role of the view(html) with the controller(components). I would prefer @ViewChild() which gives direct communication from component to component as opposed to going through the DOM to get to a component, for bigger files. You can also access the service directly unless you have a reason to bring the file to component then to the child component.</p>

Body:
(Advanced warning... I am very new to Angular, so my question may be naive and/or not make sense...)

I'm working on an Angular project (v. 5), and I need to pass a long-ish string (a large XML document - about 1mb) from a parent to a child component.

One option to do this is to use an @Input in the child component. I've tested this and it "works", although I don't know if it's a "good idea" for this large an amount of data.

A second option is to use @ViewChild(). E.g.,

In the parent.ts:

// set the child component as a @ViewChild
@ViewChild(ChildChartComponent)
private childChartComponent: ChildChartComponent;

// [get the xmlString from a service]
// ... then pass it to the child ...
this.childChartComponent.loadData(xmlString);

In the child.ts:

loadData(xmlString):void {
  // receive the xmlString, parse it, then extract and display the data
}

A few notes...

As I mentioned - the XML is pretty large - could be 1mb or more.

After the XML data is obtained by the parent, passed to the child, then parsed and processed, there's no need to "maintain" it. (I.e., I'd like it garbage-collected).

I don't really know how Angular is working under the hood, or actually passing that data from the parent to the child. But the @INPUT approach makes it look like the string is written as an attribute value:

<child-chart [xmlString]="xmlString"></child-chart>

I suspect that Angular isn't actually writing that 1mb string into an attribute property that's bloating the DOM and sitting there after it's now longer needed, but I don't really know...

So - is either one of these methods preferred for passing very long strings? Or is there an altogether different, but preferrable method?


问:
A good way to refactor code
I have several DTO objects.

```<code>public class MovieRequest {}
public class OtherTitle extends MovieRequest {}
public class ReleaseDate extends MovieRequest {}
</code>```

These objects are uploaded using a generic contribution(DTO object)
public class ContributionNew<T extends MovieRequest> {} to the methods

```<code>void createOtherTitleContribution(
        final ContributionNew<OtherTitle> contribution,
        ...
);
void updateOtherTitleContribution(
        final ContributionUpdate<OtherTitle> contribution,
        ...
);
 void createReleaseDateContribution(
        final ContributionNew<ReleaseDate> contribution,
        ...
);
void updateReleaseDateContribution(
        final ContributionUpdate<ReleaseDate> contribution,
        ...
);
</code>```

Information for films is more and these methods will be duplicated about 30 times f. e. createBoxOfficeContribution e.t.c
For example, the method of updating contributions looks like this

```<code>@Override
public void updateOtherTitleContribution(
        ContributionUpdate<OtherTitle> contribution,
        Long contributionId,
        Long userId
) throws ResourceNotFoundException {
    log.info("Called with contribution {}, contributionId {}, userId {}",
            contribution, contributionId, userId);

    final UserEntity user = this.findUser(userId);
    final ContributionEntity contributionEntity = this.findContribution(contributionId, EditStatus.WAITING, user, MovieField.OTHER_TITLE);

    this.validIds(contributionEntity.getIdsToAdd(), contribution.getElementsToAdd().keySet());
    this.validIds(contributionEntity.getIdsToUpdate().keySet(), contribution.getElementsToUpdate().keySet());
    this.validIds(contributionEntity.getIdsToDelete(), contribution.getIdsToDelete());

    this.cleanUpIdsToAdd(contributionEntity.getIdsToAdd(), contribution.getElementsToAdd().keySet(), contributionEntity.getMovie().getOtherTitles());
    this.cleanUpIdsToUpdate(contributionEntity.getIdsToUpdate(), contribution.getElementsToUpdate().keySet());
    this.cleanUpIdsToDelete(contributionEntity.getIdsToDelete(), contribution.getIdsToDelete());

    contribution.getElementsToAdd().forEach((key, value) -> {
        this.moviePersistenceService.updateOtherTitle(value, key, contributionEntity.getMovie());
    });
    contribution.getElementsToUpdate().forEach((key, value) -> {
        this.moviePersistenceService.updateOtherTitle(value, key, contributionEntity.getMovie());
    });
    contribution.getNewElementsToAdd()
            .forEach(otherTitle -> {
                final Long id = this.moviePersistenceService.createOtherTitle(otherTitle, contributionEntity.getMovie(), user);
                contributionEntity.getIdsToAdd().add(id);
            });

    contributionEntity.setSources(contribution.getSources());
    Optional.ofNullable(contribution.getComment()).ifPresent(contributionEntity::setUserComment);
}
</code>```

As you can see, the only difference in these methods is to call the method

```<code>this.moviePersistenceService.updateOtherTitle(...)
</code>```

And the method updateReleaseDateContribution calls

```<code>this.moviePersistenceService.updateReleaseDate(...)
</code>```

As you can see the difference is only a few lines, and the old way the current code will have several thousand lines. Do you have any idea for a universal generic method? How to do it better?

答:
you can create a method moviePersistenceService.update(MovieRequest req) that will check the type of req before doing the persistence part.

You can also pass a Function (the one that will do the persistence part) as parameter to  updateOtherTitleContribution  (check How to pass a function as a parameter in Java?)

Title: A good way to refactor code

Body:
I have several DTO objects.

public class MovieRequest {}
public class OtherTitle extends MovieRequest {}
public class ReleaseDate extends MovieRequest {}

These objects are uploaded using a generic contribution(DTO object)
public class ContributionNew<T extends MovieRequest> {} to the methods

void createOtherTitleContribution(
        final ContributionNew<OtherTitle> contribution,
        ...
);
void updateOtherTitleContribution(
        final ContributionUpdate<OtherTitle> contribution,
        ...
);
 void createReleaseDateContribution(
        final ContributionNew<ReleaseDate> contribution,
        ...
);
void updateReleaseDateContribution(
        final ContributionUpdate<ReleaseDate> contribution,
        ...
);

Information for films is more and these methods will be duplicated about 30 times f. e. createBoxOfficeContribution e.t.c
For example, the method of updating contributions looks like this

@Override
public void updateOtherTitleContribution(
        ContributionUpdate<OtherTitle> contribution,
        Long contributionId,
        Long userId
) throws ResourceNotFoundException {
    log.info("Called with contribution {}, contributionId {}, userId {}",
            contribution, contributionId, userId);

    final UserEntity user = this.findUser(userId);
    final ContributionEntity contributionEntity = this.findContribution(contributionId, EditStatus.WAITING, user, MovieField.OTHER_TITLE);

    this.validIds(contributionEntity.getIdsToAdd(), contribution.getElementsToAdd().keySet());
    this.validIds(contributionEntity.getIdsToUpdate().keySet(), contribution.getElementsToUpdate().keySet());
    this.validIds(contributionEntity.getIdsToDelete(), contribution.getIdsToDelete());

    this.cleanUpIdsToAdd(contributionEntity.getIdsToAdd(), contribution.getElementsToAdd().keySet(), contributionEntity.getMovie().getOtherTitles());
    this.cleanUpIdsToUpdate(contributionEntity.getIdsToUpdate(), contribution.getElementsToUpdate().keySet());
    this.cleanUpIdsToDelete(contributionEntity.getIdsToDelete(), contribution.getIdsToDelete());

    contribution.getElementsToAdd().forEach((key, value) -> {
        this.moviePersistenceService.updateOtherTitle(value, key, contributionEntity.getMovie());
    });
    contribution.getElementsToUpdate().forEach((key, value) -> {
        this.moviePersistenceService.updateOtherTitle(value, key, contributionEntity.getMovie());
    });
    contribution.getNewElementsToAdd()
            .forEach(otherTitle -> {
                final Long id = this.moviePersistenceService.createOtherTitle(otherTitle, contributionEntity.getMovie(), user);
                contributionEntity.getIdsToAdd().add(id);
            });

    contributionEntity.setSources(contribution.getSources());
    Optional.ofNullable(contribution.getComment()).ifPresent(contributionEntity::setUserComment);
}

As you can see, the only difference in these methods is to call the method

this.moviePersistenceService.updateOtherTitle(...)

And the method updateReleaseDateContribution calls

this.moviePersistenceService.updateReleaseDate(...)

As you can see the difference is only a few lines, and the old way the current code will have several thousand lines. Do you have any idea for a universal generic method? How to do it better?


问:
Convert factors to Year-Mon Date format without NAs

Preface

I've done research on Stack Overflow and found several similar questions. However, my situation is quite different:

```<code>date<-factor(c('1990-01','1991-01','1991-02','1992-01'))
</code>```

Notice I only have Year and Month, I would like to convert date to date format.

Problem

Here's what I've done according to the answers to other SO posts:

```<code>date<-as.Date(as.character(data), '%Y-%m')
date
</code>```

However, I got NAs.

How do I solve this? (better not use other packages like zoo, anytime)

Thank you in advance! Let me know if my question is clear and worth of asking.

答:
Alternative to is to use ymd from the lubridate package. It may be faster if you have a lot of rows.

Here's a million random dates with the yyyy-mm format you have:

```<code>x <- as.character(Sys.Date()-sample(40000, 1e6, TRUE))
x <- str_sub(x, 1, str_length(x)-3)
</code>```

Time with as.Date.

```<code>system.time({
  x1 <- as.Date(paste0(x,"-01"))
})
   user  system elapsed
   7.91    0.00    7.95
</code>```

Compared to ymd from lubridate.

```<code>system.time({
  x2 <- ymd(paste0(x, '-01'))
})
   user  system elapsed
   0.26    0.04    0.31
</code>```

Body:
Preface

I've done research on Stack Overflow and found several similar questions. However, my situation is quite different:

date<-factor(c('1990-01','1991-01','1991-02','1992-01'))

Notice I only have Year and Month, I would like to convert date to date format.

Problem

Here's what I've done according to the answers to other SO posts:

date<-as.Date(as.character(data), '%Y-%m')
date

However, I got NAs.

How do I solve this? (better not use other packages like zoo, anytime)

Thank you in advance! Let me know if my question is clear and worth of asking.

Body:
Alternative to is to use ymd from the lubridate package. It may be faster if you have a lot of rows.

Here's a million random dates with the yyyy-mm format you have:

x <- as.character(Sys.Date()-sample(40000, 1e6, TRUE))
x <- str_sub(x, 1, str_length(x)-3)

Time with as.Date.

system.time({
  x1 <- as.Date(paste0(x,"-01"))
})
   user  system elapsed
   7.91    0.00    7.95

Compared to ymd from lubridate.

system.time({
  x2 <- ymd(paste0(x, '-01'))
})
   user  system elapsed
   0.26    0.04    0.31


问:
Moving from Django 1.3 to Django 1.11 object_list
I'm trying to update some python files from Django 1.3 to Django 1.11. In the views.py file I have a method with the following line

```<code>return object_list(request, queryset=results['flips'], extra_context=context, **kwargs)
</code>```

I've read that object_list is now deprecated and instead of that I have to use ListView from django.views.generic.list and use Class View.

I've tried with this:

Django 1.3

views.py

```<code>def flow(request, **kwargs):
agent = 'default'
lang = request.LANGUAGE_CODE.lower()
cache_key = '%s%s%s' % (request.build_absolute_uri(), request.user.id, lang)
results = cache.get(cache_key)
if results is None:
    results = {}
    flips = pushitem.visibles.visibles().by_lang(lang=lang)
    sort = request.GET.get('sort', '')
    if sort == 'popular':
        flips = flips.order_by('-votes_total')
    else:
        flips = flips.order_by('-timestamp')
    scope = request.GET.get('scope', '')
    if scope:
        today = datetime.now()
        if scope == 'day':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day)
        if scope == 'month':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month)
        if scope == 'year':
            flips = flips.filter(timestamp__year=today.year)
    #Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster)
    query = request.GET.get('q', '')
    if query:
        people = User.objects.filter(Q(username__contains=query))
        people |= User.objects.filter(Q(first_name__contains=query))
        people |= User.objects.filter(Q(last_name__contains=query))
        flips = flips.filter(Q(searchfield__contains=query))
        topics = Tag.objects.filter(Q(name__contains=unidecode(query.lower())))
        results['people'] = people
        results['topics'] = topics
    results['flips'] = flips
    cache.set(cache_key, results)
context = {
    'title': _('Flipter.com, Ask everything!'),
    'description': _('The world\'s largest community of opinions, made with awesome polls.')
}
if results.has_key('people'):
    context['people'] = results['people']
if results.has_key('topics'):
    context['topics'] = results['topics']
return object_list(request, queryset=results['flips'], extra_context=context, **kwargs)
</code>```

urls.py

```<code>url(r'^$', flow, dict(template_name='flow.html', paginate_by=12,), name='flow'),
</code>```

Django 1.11

views.py
    class FlipView(ListView):
    paginate_by = 12
    template_name = 'flow.html'

```<code>def flow(request, **kwargs):
agent = 'default'
lang = LANGUAGE_CODE.lower()
cache_key = '%s%s%s' % (request.build_absolute_uri(), request.user.id, lang)
results = cache.get(cache_key)
if results is None:
    results = {}
    flips = pushitem.visibles.visibles()
    sort = request.GET.get('sort', '')
    if sort == 'popular':
        flips = flips.order_by('-votes_total')
    else:
        flips = flips.order_by('-timestamp')
    scope = request.GET.get('scope', '')
    if scope:
        today = datetime.now()
        if scope == 'day':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day)
        if scope == 'month':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month)
        if scope == 'year':
            flips = flips.filter(timestamp__year=today.year)
    #Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster)
    query = request.GET.get('q', '')
    if query:
        people = User.objects.filter(Q(username__contains=query))
        people |= User.objects.filter(Q(first_name__contains=query))
        people |= User.objects.filter(Q(last_name__contains=query))
        flips = flips.filter(Q(searchfield__contains=query))
        topics = Tag.objects.filter(Q(name__contains=unidecode(query.lower())))
        results['people'] = people
        results['topics'] = topics
    results['flips'] = flips
    cache.set(cache_key, results)
context = {
    'title': _('Flipter.com, Ask everything!'),
    'description': _('The world\'s largest community of opinions, made with awesome polls.')
}
if 'people' in results:
    context['people'] = results['people']
if 'topics' in results:
    context['topics'] = results['topics']
return FlipView(queryset=results['flips'], extra_context=context)
</code>```

urls.py

```<code>url(r'^$', views.flow, name='flow'),
</code>```

But when I try to get into the page I'm getting the following error:

```<code>'FlipView' object has no attribute 'kwargs'
</code>```

or

```<code>'FlipView' object has no attribute 'status_code'
</code>```

Full error description:

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.11.3
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'django.contrib.staticfiles',
 'django.contrib.flatpages',
 'django_countries',
 'django_extensions',
 'django_comments',
 'sparkty_app',
 'widget_tweaks',
 'compressor',
 'tagging',
 'easy_thumbnails',
 'social_django',
 'registration']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'social_django.middleware.SocialAuthExceptionMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware']

Traceback:

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\utils\deprecation.py" in __call__
  142.             response = self.process_response(request, response)

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\middleware\clickjacking.py" in process_response
  32.         if response.get('X-Frame-Options') is not None:

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\views\generic\list.py" in get
  175.         context = self.get_context_data()

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\views\generic\list.py" in get_context_data
  135.             paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\views\generic\list.py" in paginate_queryset
  70.         page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1

Exception Type: AttributeError at /
Exception Value: 'FlipView' object has no attribute 'kwargs'
</code>```

答:
```<code>class FlowListView(ListView):

    model = Flow # Unsure of this one, probably don't even need it.

    def get_queryset(self):
        results = cache.get(cache_key)
        if results is None:
             results = {}
             flips = pushitem.visibles.visibles()
             sort = request.GET.get('sort', '')
             if sort == 'popular':
                 flips = flips.order_by('-votes_total')
             else:
                 flips = flips.order_by('-timestamp')
             scope = request.GET.get('scope', '')
             if scope:
                 today = datetime.now()
             if scope == 'day':
                 flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day)
             if scope == 'month':
                 flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month)
             if scope == 'year':
                  flips = flips.filter(timestamp__year=today.year)
             # Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster)
             query = request.GET.get('q', '')
             if query:
                 people = User.objects.filter(Q(username__contains=query))
                 people |= User.objects.filter(Q(first_name__contains=query))
                 people |= User.objects.filter(Q(last_name__contains=query))
                 flips = flips.filter(Q(searchfield__contains=query))
                 topics =   Tag.objects.filter(Q(name__contains=unidecode(query.lower())))
                 results['people'] = people
                 results['topics'] = topics
                 results['flips'] = flips
                 cache.set(cache_key, results)
        return results

    def get_context_data(self, **kwargs):
        context = super(FlowListView, self).get_context_data(**kwargs)
        context['title'] = _('Flipter.com, Ask everything!')
        context['description'] = _('The world\'s largest community of opinions, made with awesome polls.')
        # This is something you'll have to do a bit differently, unsure if it will work
        results = kwargs['object_list']
        if 'people' in results:
            context['people'] = results['people']
        if 'topics' in results:
            context['topics'] = results['topics']
        return context
</code>```

urls.py

```<code>urlpatterns = [
    url(r'^$', FlowListView.as_view(), name='flow-list'),
]
</code>```

Body:
I'm trying to update some python files from Django 1.3 to Django 1.11. In the views.py file I have a method with the following line

return object_list(request, queryset=results['flips'], extra_context=context, **kwargs)

I've read that object_list is now deprecated and instead of that I have to use ListView from django.views.generic.list and use Class View.

I've tried with this:

Django 1.3

views.py

def flow(request, **kwargs):
agent = 'default'
lang = request.LANGUAGE_CODE.lower()
cache_key = '%s%s%s' % (request.build_absolute_uri(), request.user.id, lang)
results = cache.get(cache_key)
if results is None:
    results = {}
    flips = pushitem.visibles.visibles().by_lang(lang=lang)
    sort = request.GET.get('sort', '')
    if sort == 'popular':
        flips = flips.order_by('-votes_total')
    else:
        flips = flips.order_by('-timestamp')
    scope = request.GET.get('scope', '')
    if scope:
        today = datetime.now()
        if scope == 'day':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day)
        if scope == 'month':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month)
        if scope == 'year':
            flips = flips.filter(timestamp__year=today.year)
    #Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster)
    query = request.GET.get('q', '')
    if query:
        people = User.objects.filter(Q(username__contains=query))
        people |= User.objects.filter(Q(first_name__contains=query))
        people |= User.objects.filter(Q(last_name__contains=query))
        flips = flips.filter(Q(searchfield__contains=query))
        topics = Tag.objects.filter(Q(name__contains=unidecode(query.lower())))
        results['people'] = people
        results['topics'] = topics
    results['flips'] = flips
    cache.set(cache_key, results)
context = {
    'title': _('Flipter.com, Ask everything!'),
    'description': _('The world\'s largest community of opinions, made with awesome polls.')
}
if results.has_key('people'):
    context['people'] = results['people']
if results.has_key('topics'):
    context['topics'] = results['topics']
return object_list(request, queryset=results['flips'], extra_context=context, **kwargs)

urls.py

url(r'^$', flow, dict(template_name='flow.html', paginate_by=12,), name='flow'),

Django 1.11

views.py
    class FlipView(ListView):
    paginate_by = 12
    template_name = 'flow.html'

def flow(request, **kwargs):
agent = 'default'
lang = LANGUAGE_CODE.lower()
cache_key = '%s%s%s' % (request.build_absolute_uri(), request.user.id, lang)
results = cache.get(cache_key)
if results is None:
    results = {}
    flips = pushitem.visibles.visibles()
    sort = request.GET.get('sort', '')
    if sort == 'popular':
        flips = flips.order_by('-votes_total')
    else:
        flips = flips.order_by('-timestamp')
    scope = request.GET.get('scope', '')
    if scope:
        today = datetime.now()
        if scope == 'day':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day)
        if scope == 'month':
            flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month)
        if scope == 'year':
            flips = flips.filter(timestamp__year=today.year)
    #Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster)
    query = request.GET.get('q', '')
    if query:
        people = User.objects.filter(Q(username__contains=query))
        people |= User.objects.filter(Q(first_name__contains=query))
        people |= User.objects.filter(Q(last_name__contains=query))
        flips = flips.filter(Q(searchfield__contains=query))
        topics = Tag.objects.filter(Q(name__contains=unidecode(query.lower())))
        results['people'] = people
        results['topics'] = topics
    results['flips'] = flips
    cache.set(cache_key, results)
context = {
    'title': _('Flipter.com, Ask everything!'),
    'description': _('The world\'s largest community of opinions, made with awesome polls.')
}
if 'people' in results:
    context['people'] = results['people']
if 'topics' in results:
    context['topics'] = results['topics']
return FlipView(queryset=results['flips'], extra_context=context)

urls.py

url(r'^$', views.flow, name='flow'),

But when I try to get into the page I'm getting the following error:

'FlipView' object has no attribute 'kwargs'

or

'FlipView' object has no attribute 'status_code'

Full error description:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.11.3
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'django.contrib.staticfiles',
 'django.contrib.flatpages',
 'django_countries',
 'django_extensions',
 'django_comments',
 'sparkty_app',
 'widget_tweaks',
 'compressor',
 'tagging',
 'easy_thumbnails',
 'social_django',
 'registration']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'social_django.middleware.SocialAuthExceptionMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware']

Traceback:

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\utils\deprecation.py" in __call__
  142.             response = self.process_response(request, response)

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\middleware\clickjacking.py" in process_response
  32.         if response.get('X-Frame-Options') is not None:

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\views\generic\list.py" in get
  175.         context = self.get_context_data()

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\views\generic\list.py" in get_context_data
  135.             paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)

File "C:\Users\darth\AppData\Local\conda\conda\envs\SparktyEnv\lib\site-packages\django\views\generic\list.py" in paginate_queryset
  70.         page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1

Exception Type: AttributeError at /
Exception Value: 'FlipView' object has no attribute 'kwargs'

Body:
class FlowListView(ListView):

    model = Flow # Unsure of this one, probably don't even need it.

    def get_queryset(self):
        results = cache.get(cache_key)
        if results is None:
             results = {}
             flips = pushitem.visibles.visibles()
             sort = request.GET.get('sort', '')
             if sort == 'popular':
                 flips = flips.order_by('-votes_total')
             else:
                 flips = flips.order_by('-timestamp')
             scope = request.GET.get('scope', '')
             if scope:
                 today = datetime.now()
             if scope == 'day':
                 flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day)
             if scope == 'month':
                 flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month)
             if scope == 'year':
                  flips = flips.filter(timestamp__year=today.year)
             # Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster)
             query = request.GET.get('q', '')
             if query:
                 people = User.objects.filter(Q(username__contains=query))
                 people |= User.objects.filter(Q(first_name__contains=query))
                 people |= User.objects.filter(Q(last_name__contains=query))
                 flips = flips.filter(Q(searchfield__contains=query))
                 topics =   Tag.objects.filter(Q(name__contains=unidecode(query.lower())))
                 results['people'] = people
                 results['topics'] = topics
                 results['flips'] = flips
                 cache.set(cache_key, results)
        return results

    def get_context_data(self, **kwargs):
        context = super(FlowListView, self).get_context_data(**kwargs)
        context['title'] = _('Flipter.com, Ask everything!')
        context['description'] = _('The world\'s largest community of opinions, made with awesome polls.')
        # This is something you'll have to do a bit differently, unsure if it will work
        results = kwargs['object_list']
        if 'people' in results:
            context['people'] = results['people']
        if 'topics' in results:
            context['topics'] = results['topics']
        return context

urls.py

urlpatterns = [
    url(r'^$', FlowListView.as_view(), name='flow-list'),
]


Title: Aggregate time series in numpy

Body:
I am trying to aggregate a variable onto time slots, but I am not sure how to do this in a Pythonic way. My plan is to aggregate it every ten seconds.
My time data is the first column and it is stated in seconds from midnight. The second column is the variable I want to aggregate. Most of the entries are zero, but the others are actual numbers that I want to sum.

So the idea is to sum column two for every ten seconds elapsed from column 1.
The matrix vector would have the time every ten seconds for the first column and the aggregated variable for the second column.

My first idea was to do a while loop on column two and summing all the numbers while we are inside the same time slot. And place it inside a for loop for each 10 second increment. This seems incredibly heavy and slow.

Any suggestions are really appreciated. Thank you.

Sample data:

3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009535350000078e+04    0.000000000000000000e+00
3.420009723610000219e+04    0.000000000000000000e+00
3.420009926809999888e+04    0.000000000000000000e+00
3.420019142339999962e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420025728430000163e+04    0.000000000000000000e+00
3.420030975760000001e+04    0.000000000000000000e+00
3.420031578240000090e+04    0.000000000000000000e+00
3.420033592689999932e+04    0.000000000000000000e+00
3.420046674769999663e+04    0.000000000000000000e+00
3.420046679600000061e+04    0.000000000000000000e+00
3.420074155890000111e+04    3.000000000000000000e+02
3.420074291200000152e+04    0.000000000000000000e+00
3.420076289620000171e+04    -3.000000000000000000e+02
3.420076459099999920e+04    2.000000000000000000e+02
3.420080930030000309e+04    0.000000000000000000e+00
3.420088430179999705e+04    0.000000000000000000e+00
3.420089157010000054e+04    6.000000000000000000e+00
3.420103050939999957e+04    3.000000000000000000e+02
3.420118753419999848e+04    3.000000000000000000e+02
3.420118888490000245e+04    0.000000000000000000e+00
3.420141332990000228e+04    0.000000000000000000e+00
3.420191020060000301e+04    0.000000000000000000e+00
3.420282872450000286e+04    6.000000000000000000e+00
3.420304732930000318e+04    0.000000000000000000e+00
3.420305702279999969e+04    0.000000000000000000e+00
3.420308584690000134e+04    0.000000000000000000e+00
3.420310770000000048e+04    0.000000000000000000e+00
3.420319724010000209e+04    0.000000000000000000e+00
3.420338125820000278e+04    -6.000000000000000000e+00
3.420341430170000240e+04    0.000000000000000000e+00
3.420341743809999753e+04    0.000000000000000000e+00
3.420365752020000218e+04    -1.000000000000000000e+02
3.420377651160000096e+04    0.000000000000000000e+00
3.420377900809999846e+04    0.000000000000000000e+00
3.420394856640000216e+04    0.000000000000000000e+00
3.420477753839999787e+04    0.000000000000000000e+00
3.420477777210000204e+04    0.000000000000000000e+00
3.420509855940000125e+04    0.000000000000000000e+00
3.420509857180000108e+04    0.000000000000000000e+00
3.420509858389999863e+04    0.000000000000000000e+00
3.420509858600000007e+04    0.000000000000000000e+00
3.420510251910000079e+04    3.000000000000000000e+02
3.420540111949999846e+04    0.000000000000000000e+00
3.420560046090000105e+04    0.000000000000000000e+00
3.420650914059999923e+04    3.000000000000000000e+02
3.420677362859999994e+04    0.000000000000000000e+00
3.420677385650000360e+04    0.000000000000000000e+00
3.420680100729999685e+04    0.000000000000000000e+00
3.420680135709999740e+04    0.000000000000000000e+00
3.420740102699999989e+04    0.000000000000000000e+00
3.420760059799999726e+04    0.000000000000000000e+00
3.420827570510000078e+04    0.000000000000000000e+00
3.420827846660000068e+04    -1.000000000000000000e+02
3.420860100809999858e+04    0.000000000000000000e+00
3.420860318459999689e+04    0.000000000000000000e+00
3.420860717129999830e+04    3.000000000000000000e+02
3.420920105229999899e+04    0.000000000000000000e+00
3.420949705469999753e+04    0.000000000000000000e+00
3.420949705469999753e+04    1.000000000000000000e+02
3.420949874789999740e+04    0.000000000000000000e+00
3.420949964329999784e+04    1.000000000000000000e+02
3.420950525599999673e+04    1.000000000000000000e+02
3.420950532879999810e+04    1.000000000000000000e+02
3.420950537430000259e+04    1.000000000000000000e+02
3.420950638910000271e+04    2.000000000000000000e+02
3.420950643239999772e+04    0.000000000000000000e+00
3.420950668009999936e+04    -2.000000000000000000e+02
3.420950796770000306e+04    0.000000000000000000e+00
3.420951590530000249e+04    2.000000000000000000e+02
3.420951602249999996e+04    1.000000000000000000e+02
3.420951673219999793e+04    -2.000000000000000000e+02
3.420951805140000215e+04    2.000000000000000000e+02
3.420951861829999689e+04    -1.000000000000000000e+02
3.420951993930000026e+04    -2.000000000000000000e+02
3.420951995310000348e+04    0.000000000000000000e+00
3.420952149579999968e+04    -1.000000000000000000e+02
3.420953443149999657e+04    0.000000000000000000e+00
3.420955497840000317e+04    -1.000000000000000000e+02
3.420980103039999813e+04    0.000000000000000000e+00
3.420980107300000236e+04    0.000000000000000000e+00
3.420980108509999991e+04    0.000000000000000000e+00
3.420989885620000132e+04    0.000000000000000000e+00
3.420989886560000014e+04    0.000000000000000000e+00
3.420989887540000200e+04    0.000000000000000000e+00
3.421022118190000037e+04    6.000000000000000000e+00
3.421028878499999701e+04    0.000000000000000000e+00
3.421029493570000341e+04    -6.000000000000000000e+00
3.421030143400000088e+04    6.000000000000000000e+00
3.421040105849999964e+04    0.000000000000000000e+00
3.421048329460000241e+04    -6.000000000000000000e+00
3.421048642470000050e+04    6.000000000000000000e+00
3.421085856629999762e+04    0.000000000000000000e+00
3.421091312309999921e+04    2.000000000000000000e+02
3.421091378969999641e+04    -2.000000000000000000e+02
3.421091715290000138e+04    1.000000000000000000e+02
3.421118993179999961e+04    0.000000000000000000e+00
3.421119293469999684e+04    6.000000000000000000e+00
3.421120108150000306e+04    0.000000000000000000e+00
3.421125067030000355e+04    1.000000000000000000e+02
3.421125067030000355e+04    2.000000000000000000e+02
3.421125072869999713e+04    0.000000000000000000e+00
3.421125074440000026e+04    1.000000000000000000e+02
3.421125075079999806e+04    1.000000000000000000e+02
3.421125081070000306e+04    0.000000000000000000e+00
3.421125213139999687e+04    -2.000000000000000000e+02
3.421125223679999908e+04    1.000000000000000000e+02
3.421128031339999870e+04    -1.000000000000000000e+02
3.421128036189999693e+04    -1.000000000000000000e+02
3.421129058039999654e+04    0.000000000000000000e+00
3.421136299729999882e+04    -6.000000000000000000e+00
3.421136675249999826e+04    6.000000000000000000e+00
3.421144104959999822e+04    -6.000000000000000000e+00
3.421144451439999830e+04    6.000000000000000000e+00
3.421180177070000354e+04    1.000000000000000000e+02
3.421180182290000084e+04    1.000000000000000000e+02
3.421180183370000304e+04    1.000000000000000000e+02
3.421180184079999890e+04    0.000000000000000000e+00
3.421180240860000049e+04    -2.000000000000000000e+02
3.421182461470000271e+04    -1.000000000000000000e+02
3.421182466330000170e+04    -1.000000000000000000e+02
3.421183488509999734e+04    0.000000000000000000e+00
3.421209945889999653e+04    7.500000000000000000e+01
3.421213015650000307e+04    1.000000000000000000e+02
3.421250285479999729e+04    2.500000000000000000e+01
3.421250285479999729e+04    3.000000000000000000e+02
3.421250292720000289e+04    1.000000000000000000e+02
3.421250293499999680e+04    1.000000000000000000e+02
3.421250294089999807e+04    0.000000000000000000e+00
3.421250461730000097e+04    2.000000000000000000e+02
3.421250660069999867e+04    2.000000000000000000e+02
3.421250661260000197e+04    0.000000000000000000e+00
3.421250662810000358e+04    -2.000000000000000000e+02
3.421250862849999976e+04    2.000000000000000000e+02
3.421250865109999722e+04    -2.000000000000000000e+02
3.421251071360000060e+04    2.000000000000000000e+02
3.421251073390000238e+04    -2.000000000000000000e+02
3.421251200200000312e+04    2.000000000000000000e+02
3.421251202500000363e+04    -2.000000000000000000e+02
3.421251290870000230e+04    2.000000000000000000e+02
3.421251292259999900e+04    0.000000000000000000e+00
3.421251417010000296e+04    0.000000000000000000e+00
3.421252315950000047e+04    -3.750000000000000000e+02
3.421253324080000311e+04    -1.000000000000000000e+02
3.421253324419999990e+04    -1.000000000000000000e+02
3.421253325169999880e+04    0.000000000000000000e+00
3.421280107870000211e+04    0.000000000000000000e+00
3.421280108050000126e+04    0.000000000000000000e+00
3.421280109909999737e+04    0.000000000000000000e+00
3.421300649369999883e+04    -1.000000000000000000e+02
3.421300649369999883e+04    -5.000000000000000000e+00
3.421301662930000020e+04    0.000000000000000000e+00
3.421301664270000038e+04    0.000000000000000000e+00
3.421308269650000148e+04    -1.000000000000000000e+00
3.421308569990000251e+04    1.000000000000000000e+00
3.421340113990000100e+04    -2.000000000000000000e+02
3.421360080849999940e+04    0.000000000000000000e+00
3.421360081950000313e+04    0.000000000000000000e+00
3.421429604950000066e+04    0.000000000000000000e+00
3.421429604950000066e+04    2.000000000000000000e+02
3.421465075329999672e+04    1.750000000000000000e+02
3.421465535619999719e+04    0.000000000000000000e+00
3.421480113819999679e+04    2.000000000000000000e+02
3.421500744149999809e+04    2.000000000000000000e+02
3.421500745640000241e+04    -2.000000000000000000e+02
3.421501012210000044e+04    0.000000000000000000e+00
3.421501918660000229e+04    2.000000000000000000e+02
3.421506023750000168e+04    2.000000000000000000e+02
3.421506026279999787e+04    0.000000000000000000e+00
3.421506290029999946e+04    0.000000000000000000e+00
3.421529837140000018e+04    -2.000000000000000000e+02
3.421540116690000286e+04    0.000000000000000000e+00
3.421549945029999799e+04    0.000000000000000000e+00
3.421554515879999963e+04    0.000000000000000000e+00
3.421556687119999697e+04    -3.000000000000000000e+02
3.421556832669999858e+04    0.000000000000000000e+00
3.421560137959999702e+04    0.000000000000000000e+00
3.421591907280000305e+04    0.000000000000000000e+00
3.421640112349999981e+04    0.000000000000000000e+00
3.421660092140000052e+04    0.000000000000000000e+00
3.421780116010000347e+04    0.000000000000000000e+00
3.421860098989999824e+04    0.000000000000000000e+00
3.422180125080000289e+04    0.000000000000000000e+00
3.422181661359999998e+04    0.000000000000000000e+00
3.422946705189999921e+04    0.000000000000000000e+00
3.422947095989999798e+04    3.000000000000000000e+02
3.422947237350000069e+04    -2.000000000000000000e+02
3.422980151579999801e+04    0.000000000000000000e+00
3.423008524700000271e+04    0.000000000000000000e+00
3.423035811159999867e+04    0.000000000000000000e+00
3.423036595089999901e+04    0.000000000000000000e+00
3.423315292909999698e+04    -1.000000000000000000e+00
3.423315298620000249e+04    -1.000000000000000000e+02
3.423315299590000359e+04    -1.000000000000000000e+02
3.423315301110000291e+04    0.000000000000000000e+00
3.423315437930000189e+04    0.000000000000000000e+00
3.423315469930000108e+04    -2.000000000000000000e+02
3.423315568000000349e+04    0.000000000000000000e+00
3.423317673620000278e+04    1.000000000000000000e+02
3.423318700569999783e+04    1.000000000000000000e+02

Body:
Consider the following approach:

import pandas as pd

df = pd.read_csv(filename, header=None, names=['ts','val'])

In [31]: df.groupby(df['ts']//10*10)['val'].sum()
Out[31]:
ts
34200.0    1806.0
34210.0     907.0
34220.0     100.0
34230.0    -201.0
Name: val, dtype: float64

Source DF:

In [33]: df
Out[33]:
               ts    val
0    34200.095354    0.0
1    34200.095354    0.0
2    34200.095354    0.0
3    34200.095354    0.0
4    34200.095354    0.0
5    34200.095354    0.0
6    34200.095354    0.0
7    34200.095354    0.0
8    34200.095354    0.0
9    34200.095354    0.0
..            ...    ...
237  34230.365951    0.0
238  34233.152929   -1.0
239  34233.152986 -100.0
240  34233.152996 -100.0
241  34233.153011    0.0
242  34233.154379    0.0
243  34233.154699 -200.0
244  34233.155680    0.0
245  34233.176736  100.0
246  34233.187006  100.0

[247 rows x 2 columns]

df['ts']//10*10 - will round timestamps up to 10 seconds, so we can use it for groupping later on:

In [34]: df['ts']//10*10
Out[34]:
0      34200.0
1      34200.0
2      34200.0
3      34200.0
4      34200.0
5      34200.0
6      34200.0
7      34200.0
8      34200.0
9      34200.0
        ...
237    34230.0
238    34230.0
239    34230.0
240    34230.0
241    34230.0
242    34230.0
243    34230.0
244    34230.0
245    34230.0
246    34230.0
Name: ts, Length: 247, dtype: float64


问:
Eclipse keyboard command to add import statement
I am a C# developer who is doing some Android development in Eclipse. One of my favorite keyboard shortcuts in Visual Studio is CTRL + . which brings up the SmartTag menu. This is incredibly useful for adding using statements on the fly.

As an example if I don't have an import statement for System.Xml.Linq but create a variable of type XDocument I can quickly add the appropriate using with the keyboard command.

Is there a similar keyboard command available in Eclipse?

答: I'm pretty sure he has Ctrl + Shift + O in mind, but I may be wrong.


问:
Align 3 dynamic views in one row
i want to align 3 Views in a row:
|Icon| |Title| |Buttons|
The Title can be more than one line. The buttons are 0-3 Buttons, so their width is unknown to me.

Now the problem is, if I got more than one line in the title the buttons are cut off. How can i solve this and make sure the buttons are always on the screen and the title just has the space that is left?

On this screenshot 2 listitems are visible. Both should have 3 buttons on the right, but with the long title in the second row, the buttons are cut off

```<code>        render() {
        return (
            <TouchableHighlight style={styles.view} underlayColor={'#eee'} onPress={this.props.navigateToDetails}>
                <View style={{flex: 1}}>
                    <View style={styles.header}>
                        <View style={styles.headerTitle}>
                           <MaterialIcons style={styles.icon} name={"worker"}/>
                            <MentionsText style={styles.title}
                            >
                                {this.props.siteVisitNote.title}
                            </MentionsText>
                        </View>
                        <View style={styles.buttons}>
                            <FontAwesomeIcons style={styles.icon} name="tag"/>
                            {Utils.objectExists(this.props.siteVisitNote.attachments) || true ?
                                <FontAwesomeIcons style={styles.icon} name="paperclip"/> : null}
                            {Utils.objectExists(this.props.siteVisitNote.images) || true ?
                                <FontAwesomeIcons style={styles.icon} name="picture-o"/> : null}
                        </View>
                    </View>
                    <MentionsText style={styles.text}
                    >{this.getText()}</MentionsText>
                </View>
            </TouchableHighlight>
        )
    }
}

const styles = StyleSheet.create({
    header: {
        flexDirection: 'row',
        justifyContent: "space-between",
    },
    headerTitle: {
        flexDirection: 'row'
    },
    view: {
        flex: 1,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#efeff4',
        padding: 8,
        minHeight: 40,
    },
    buttons: {
        flexDirection: "row",
        alignSelf: 'flex-end',
    },
    icon: {
        fontSize: 20,
        paddingRight: 5,
        color: "#333333",
        padding: 8
    },
    title: {
        color: "#333333",
        fontSize: 14,
        fontWeight: 'bold',
        padding: 8,
    },
    text: {
        color: "#333333",
        fontSize: 14,
        padding: 8
    }
});
</code>```

Thanks!

答:
Add flex: 1 to headerTitle, and title.

If that doesn't work see my working example of this layout here which you can compare.

https://gist.github.com/WilliamIPark/2ad3ecf47c5c1e559086e4b10d0cf018

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView
} from 'react-native';

export default class App extends Component {
  render() {
    return (
      <ScrollView
        style={{ backgroundColor: '#edf2f9'}}
        contentContainerStyle={styles.container}
      >
        <View style={styles.card}>
          <View style={styles.header}>
            <View style={styles.iconTitle}>
              <View style={styles.icon} />
              <Text>Hello world</Text>
            </View>
            <View style={styles.buttonWrap}>
              <View style={styles.button} />
              <View style={styles.button} />
              <View style={styles.button} />
            </View>
          </View>
          <View>
            <Text>
            Some other content...
            </Text>
          </View>
        </View>

        <View style={styles.card}>
          <View style={styles.header}>
            <View style={styles.iconTitle}>
              <View style={styles.icon} />
              <Text style={styles.title}>
                Hello world this is some really long title right here, that
                goes on and on and on. And then some!
              </Text>
            </View>
            <View style={styles.buttonWrap}>
              <View style={styles.button} />
              <View style={styles.button} />
              <View style={styles.button} />
            </View>
          </View>
          <View>
            <Text>
              Some other content...
            </Text>
          </View>
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#edf2f9',
  },
  card: {
    backgroundColor: 'white',
    height: 200,
    width: 320,
    shadowColor: 'black',
    shadowOpacity: 0.25,
    shadowOffset: {x: 10, y: 10},
    padding: 10,
    marginTop: 10,
  },
  header: {
    borderBottomWidth: 0.5,
    borderBottomColor: 'lightgrey',
    flexDirection: 'row',
    marginBottom: 10,
    justifyContent: 'space-between',
  },
  iconTitle:{
    flexDirection: 'row',
    flex: 1,
    marginBottom: 10,
  },
  icon: {
    height: 24,
    width: 24,
    backgroundColor: 'black',
    marginRight: 5,
  },
  title: {
    flex: 1,
  },
  buttonWrap: {
    flexDirection: 'row',
  },
  button: {
    height: 24,
    width: 24,
    backgroundColor: 'red',
    marginLeft: 5,
  }
});
</code>```

Title: Align 3 dynamic views in one row

Body:
i want to align 3 Views in a row:
|Icon| |Title| |Buttons|
The Title can be more than one line. The buttons are 0-3 Buttons, so their width is unknown to me.

Now the problem is, if I got more than one line in the title the buttons are cut off. How can i solve this and make sure the buttons are always on the screen and the title just has the space that is left?

On this screenshot 2 listitems are visible. Both should have 3 buttons on the right, but with the long title in the second row, the buttons are cut off

        render() {
        return (
            <TouchableHighlight style={styles.view} underlayColor={'#eee'} onPress={this.props.navigateToDetails}>
                <View style={{flex: 1}}>
                    <View style={styles.header}>
                        <View style={styles.headerTitle}>
                           <MaterialIcons style={styles.icon} name={"worker"}/>
                            <MentionsText style={styles.title}
                            >
                                {this.props.siteVisitNote.title}
                            </MentionsText>
                        </View>
                        <View style={styles.buttons}>
                            <FontAwesomeIcons style={styles.icon} name="tag"/>
                            {Utils.objectExists(this.props.siteVisitNote.attachments) || true ?
                                <FontAwesomeIcons style={styles.icon} name="paperclip"/> : null}
                            {Utils.objectExists(this.props.siteVisitNote.images) || true ?
                                <FontAwesomeIcons style={styles.icon} name="picture-o"/> : null}
                        </View>
                    </View>
                    <MentionsText style={styles.text}
                    >{this.getText()}</MentionsText>
                </View>
            </TouchableHighlight>
        )
    }
}

const styles = StyleSheet.create({
    header: {
        flexDirection: 'row',
        justifyContent: "space-between",
    },
    headerTitle: {
        flexDirection: 'row'
    },
    view: {
        flex: 1,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#efeff4',
        padding: 8,
        minHeight: 40,
    },
    buttons: {
        flexDirection: "row",
        alignSelf: 'flex-end',
    },
    icon: {
        fontSize: 20,
        paddingRight: 5,
        color: "#333333",
        padding: 8
    },
    title: {
        color: "#333333",
        fontSize: 14,
        fontWeight: 'bold',
        padding: 8,
    },
    text: {
        color: "#333333",
        fontSize: 14,
        padding: 8
    }
});

Thanks!

Body:
Add flex: 1 to headerTitle, and title.

If that doesn't work see my working example of this layout here which you can compare.

https://gist.github.com/WilliamIPark/2ad3ecf47c5c1e559086e4b10d0cf018

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView
} from 'react-native';

export default class App extends Component {
  render() {
    return (
      <ScrollView
        style={{ backgroundColor: '#edf2f9'}}
        contentContainerStyle={styles.container}
      >
        <View style={styles.card}>
          <View style={styles.header}>
            <View style={styles.iconTitle}>
              <View style={styles.icon} />
              <Text>Hello world</Text>
            </View>
            <View style={styles.buttonWrap}>
              <View style={styles.button} />
              <View style={styles.button} />
              <View style={styles.button} />
            </View>
          </View>
          <View>
            <Text>
            Some other content...
            </Text>
          </View>
        </View>

        <View style={styles.card}>
          <View style={styles.header}>
            <View style={styles.iconTitle}>
              <View style={styles.icon} />
              <Text style={styles.title}>
                Hello world this is some really long title right here, that
                goes on and on and on. And then some!
              </Text>
            </View>
            <View style={styles.buttonWrap}>
              <View style={styles.button} />
              <View style={styles.button} />
              <View style={styles.button} />
            </View>
          </View>
          <View>
            <Text>
              Some other content...
            </Text>
          </View>
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#edf2f9',
  },
  card: {
    backgroundColor: 'white',
    height: 200,
    width: 320,
    shadowColor: 'black',
    shadowOpacity: 0.25,
    shadowOffset: {x: 10, y: 10},
    padding: 10,
    marginTop: 10,
  },
  header: {
    borderBottomWidth: 0.5,
    borderBottomColor: 'lightgrey',
    flexDirection: 'row',
    marginBottom: 10,
    justifyContent: 'space-between',
  },
  iconTitle:{
    flexDirection: 'row',
    flex: 1,
    marginBottom: 10,
  },
  icon: {
    height: 24,
    width: 24,
    backgroundColor: 'black',
    marginRight: 5,
  },
  title: {
    flex: 1,
  },
  buttonWrap: {
    flexDirection: 'row',
  },
  button: {
    height: 24,
    width: 24,
    backgroundColor: 'red',
    marginLeft: 5,
  }
});


问:
router stopped working after an update
I used to have the attached code working just fine, but then an update caused it to stop working. I was not able to make the adjustments so hopefully someone here has gone through it. The last block after the HTML is just smarty code to include the js file. The URL I am getting is: mySite.com/policies#!/#refund
which does not load anything. If I manually delete the second # to make it /policies#!/refund it does work.

This is the js file:

```<code>var app = angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'dialogs.main',
'summernote', 'angular-loading-bar', 'ngAnimate', 'fiestah.money', 'ui.ace',
'ui.select', 'ngCart']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
    .when('/', {
        templateUrl: '/templates/main-app/policy/policy-reviews.tpl',
        controller: 'mainCtrl'
    })
    .when('/reviews', {
        templateUrl: '/templates/main-app/policy/policy-reviews.tpl',
        controller: 'mainCtrl'
    })
    .when('/currency', {
        templateUrl: '/templates/main-app/policy/policy-currency.tpl',
        controller: 'mainCtrl'
    })
    .when('/refund', {
        templateUrl: '/templates/main-app/policy/policy-refund.tpl',
        controller: 'mainCtrl'
    });
</code>```

});
    app.controller('mainCtrl', function ($scope, $rootScope, $filter, $http, $location, dialogs) {
    console.log("in ctrl");
});

This is the template:

```<code><div ng-controller="mainCtrl">
<div class="act-dash">
    <nav class="navbar-default content-header blue" role="navigation" style="position:relative;">
        <!-- We use the fluid option here to avoid overriding the fixed width of a normal container within the narrow content columns. -->
        <div id="admin-collapse" class="pad-left-fix" style="bottom:0px;">
            <div class="container"><h1>Terms and Policies</h1></div>
            <ul class="nav navbar-nav" style="position:relative; bottom:0px">
                <li><a href="#reviews"><span class="glyphicon glyphicon-eye-open"> </span>Comments and Reviews</a></li>
                <li><a href="#currency"><span class="glyphicon glyphicon-usd"> </span>Currency Conversion</a></li>
                <li><a href="#refund"><span class="glyphicon glyphicon-usd"> </span>Refund Policy</a></li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </nav>
    <div class="content narrow-content margin-fix">
        <div class="row margin-fix margin-bottom-fix div-table" style="width:100%;">
            <div class="col-md-12 pad-left-fix pad-right-fix div-table-cell">
                <div style="text-align: left;">
                    <div id="main">
                        <!-- angular templating -->
                        <!-- this is where content will be injected -->
                        <div ng-view>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

```<code>{assign var="extra_js" scope="global" value="
    <script type=\"text/javascript\" src=\"/js/angular-apps/policy.js\">
</script>
</code>```

"}

答:
You can Add Following line of code in your app.config, Just below
  $routeProvider and see if it will work. Before run Please clear cache
  and coockies on your browser.

```<code>$locationProvider.hashPrefix('');
</code>```

Title: router stopped working after an update

Body:
I used to have the attached code working just fine, but then an update caused it to stop working. I was not able to make the adjustments so hopefully someone here has gone through it. The last block after the HTML is just smarty code to include the js file. The URL I am getting is: mySite.com/policies#!/#refund
which does not load anything. If I manually delete the second # to make it /policies#!/refund it does work.

This is the js file:

var app = angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'dialogs.main',
'summernote', 'angular-loading-bar', 'ngAnimate', 'fiestah.money', 'ui.ace',
'ui.select', 'ngCart']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
    .when('/', {
        templateUrl: '/templates/main-app/policy/policy-reviews.tpl',
        controller: 'mainCtrl'
    })
    .when('/reviews', {
        templateUrl: '/templates/main-app/policy/policy-reviews.tpl',
        controller: 'mainCtrl'
    })
    .when('/currency', {
        templateUrl: '/templates/main-app/policy/policy-currency.tpl',
        controller: 'mainCtrl'
    })
    .when('/refund', {
        templateUrl: '/templates/main-app/policy/policy-refund.tpl',
        controller: 'mainCtrl'
    });

});
    app.controller('mainCtrl', function ($scope, $rootScope, $filter, $http, $location, dialogs) {
    console.log("in ctrl");
});

This is the template:

Terms and Policies

 Comments and Reviews

 Currency Conversion

 Refund Policy

{assign var="extra_js" scope="global" value="

"}

Body:
You can Add Following line of code in your app.config, Just below
  $routeProvider and see if it will work. Before run Please clear cache
  and coockies on your browser.

$locationProvider.hashPrefix('');


问:
What causes WPF App to close
I've ran into a weird bug where a WPF app is closing after the first window closes.  This has made me curious what is triggering it to close

For example this is what I was the unworking version.  After the EULAWindow would close it would shut down the application.

```<code>EULAWindow eula = new EULAWindow();
eula.ShowDialog();
MainMenuWindow mainWindow = new MainMenuWindow();
mainWindow.ShowDialog();
</code>```

I thought it would open the EULA and then open the Menu window.   I've found that if I rearranged the code it will operate like expected.

For example this will fix it:

```<code>EULAWindow eula = new EULAWindow();
MainMenuWindow mainWindow = new MainMenuWindow();
eula.ShowDialog();
mainWindow.ShowDialog();
</code>```

This brings me to the question of what actually is causing the application to shut down in the first situation?

答:
ShowDialog() is a blocking call. So, in the first case you have single window, then show it, then let user to close it. What should an app to do once last UI window is closed? Maybe, follow to app shutdown code? I suspect so.

In the 2nd case you create two windows before the blocking inside ShowDialog(). So, once you closed the first window, there is another one that could accommodate the user, and the app is not shutting down, it just waits for the next window to be shown.

Title: What causes WPF App to close

Body:
I've ran into a weird bug where a WPF app is closing after the first window closes.  This has made me curious what is triggering it to close

For example this is what I was the unworking version.  After the EULAWindow would close it would shut down the application.

EULAWindow eula = new EULAWindow();
eula.ShowDialog();
MainMenuWindow mainWindow = new MainMenuWindow();
mainWindow.ShowDialog();

I thought it would open the EULA and then open the Menu window.   I've found that if I rearranged the code it will operate like expected.

For example this will fix it:

EULAWindow eula = new EULAWindow();
MainMenuWindow mainWindow = new MainMenuWindow();
eula.ShowDialog();
mainWindow.ShowDialog();

This brings me to the question of what actually is causing the application to shut down in the first situation?


问:
How to get output from python2 subprocess which run a script using multiprocessing?
Here is my demo code. It contains two scripts.

The first is main.py, it will call print_line.py with subprocess module.

The second is print_line.py, it prints something to the stdout.

main.py

```<code>import subprocess

p = subprocess.Popen('python2 print_line.py',
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     close_fds=True,
                     shell=True,
                     universal_newlines=True)

while True:
    line = p.stdout.readline()
    if line:
        print(line)
    else:
        break
</code>```

print_line.py

```<code>from multiprocessing import Process, JoinableQueue, current_process

if __name__ == '__main__':
    task_q = JoinableQueue()

    def do_task():
        while True:
            task = task_q.get()
            pid = current_process().pid
            print 'pid: {}, task: {}'.format(pid, task)
            task_q.task_done()

    for _ in range(10):
        p = Process(target=do_task)
        p.daemon = True
        p.start()

    for i in range(100):
        task_q.put(i)

    task_q.join()
</code>```

Before, print_line.py is written with threading and Queue module, everything is fine. But now, after changing to multiprocessing module, the main.py cannot get any output from print_line. I tried to use Popen.communicate() to get the output or set preexec_fn=os.setsid inPopen(). Neither of them work.

So, here is my question:

Why subprocess cannot get the output with multiprocessing? why it is ok with threading?

If I comment out stdout=subprocess.PIPE and stderr=subprocess.PIPE, the output is printed in my console. Why? How does this happen?

Is there any chance to get the output from print_line.py?

答:
It's not a multiprocessing issue, but it is a subprocess issue—or more precisely, it has to to with standard I/O and buffering, as in Hannu's answer.  The trick is that by default, the output of any process, whether in Python or not, is line buffered if the output device is a "terminal device" as determined by os.isatty(stream.fileno()):

```<code>>>> import sys
>>> sys.stdout.fileno()
1
>>> import os
>>> os.isatty(1)
True
</code>```

There is a shortcut available to you once the stream is open:

```<code>>>> sys.stdout.isatty()
True
</code>```

but the os.isatty() operation is the more fundamental one.  That is, internally, Python inspects the file descriptor first using os.isatty(fd), then chooses the stream's buffering based on the result (and/or arguments and/or the function used to open the stream).  The sys.stdout stream is opened early on during Python's startup, before you generally have much control.1

When you call open or codecs.open or otherwise do your own operation to open a file, you can specify the buffering via one of the optional arguments.  The default for open is the system default, which is line buffering if isatty(), otherwise fully buffered.  Curiously, the default for codecs.open is line buffered.

A line buffered stream gets an automatic flush() applied when you write a newline to it.

An unbuffered stream writes each byte to its output immediately.  This is very inefficient in general.  A fully buffered stream writes its output when the buffer gets sufficiently full—the definition of "sufficient" here tends to be pretty variable, anything from 1024 (1k) to 1048576 (1 MB)—or when explicitly directed.

When you run something as a process, it's the process itself that decides how to do any buffering.  Your own Python code, reading from the process, cannot control it.  But if you know something—or a lot—about the processes that you will run, you can set up their environment so that they run line-buffered, or even unbuffered.  (Or, as in your case, since you write that code, you can write it to do what you want.)

1There are hooks that fire up very early, where you can fuss with this sort of thing.  They are tricky to work though.

Body:
Here is my demo code. It contains two scripts.

The first is main.py, it will call print_line.py with subprocess module.

The second is print_line.py, it prints something to the stdout.

main.py

import subprocess

p = subprocess.Popen('python2 print_line.py',
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     close_fds=True,
                     shell=True,
                     universal_newlines=True)

while True:
    line = p.stdout.readline()
    if line:
        print(line)
    else:
        break

print_line.py

from multiprocessing import Process, JoinableQueue, current_process

if __name__ == '__main__':
    task_q = JoinableQueue()

    def do_task():
        while True:
            task = task_q.get()
            pid = current_process().pid
            print 'pid: {}, task: {}'.format(pid, task)
            task_q.task_done()

    for _ in range(10):
        p = Process(target=do_task)
        p.daemon = True
        p.start()

    for i in range(100):
        task_q.put(i)

    task_q.join()

Before, print_line.py is written with threading and Queue module, everything is fine. But now, after changing to multiprocessing module, the main.py cannot get any output from print_line. I tried to use Popen.communicate() to get the output or set preexec_fn=os.setsid inPopen(). Neither of them work.

So, here is my question:

Why subprocess cannot get the output with multiprocessing? why it is ok with threading?

If I comment out stdout=subprocess.PIPE and stderr=subprocess.PIPE, the output is printed in my console. Why? How does this happen?

Is there any chance to get the output from print_line.py?

Body:
It's not a multiprocessing issue, but it is a subprocess issue—or more precisely, it has to to with standard I/O and buffering, as in Hannu's answer.  The trick is that by default, the output of any process, whether in Python or not, is line buffered if the output device is a "terminal device" as determined by os.isatty(stream.fileno()):

>>> import sys
>>> sys.stdout.fileno()
1
>>> import os
>>> os.isatty(1)
True

There is a shortcut available to you once the stream is open:

>>> sys.stdout.isatty()
True

but the os.isatty() operation is the more fundamental one.  That is, internally, Python inspects the file descriptor first using os.isatty(fd), then chooses the stream's buffering based on the result (and/or arguments and/or the function used to open the stream).  The sys.stdout stream is opened early on during Python's startup, before you generally have much control.1

When you call open or codecs.open or otherwise do your own operation to open a file, you can specify the buffering via one of the optional arguments.  The default for open is the system default, which is line buffering if isatty(), otherwise fully buffered.  Curiously, the default for codecs.open is line buffered.

A line buffered stream gets an automatic flush() applied when you write a newline to it.

An unbuffered stream writes each byte to its output immediately.  This is very inefficient in general.  A fully buffered stream writes its output when the buffer gets sufficiently full—the definition of "sufficient" here tends to be pretty variable, anything from 1024 (1k) to 1048576 (1 MB)—or when explicitly directed.

When you run something as a process, it's the process itself that decides how to do any buffering.  Your own Python code, reading from the process, cannot control it.  But if you know something—or a lot—about the processes that you will run, you can set up their environment so that they run line-buffered, or even unbuffered.  (Or, as in your case, since you write that code, you can write it to do what you want.)

1There are hooks that fire up very early, where you can fuss with this sort of thing.  They are tricky to work though.


问:
In mongodb Which is better to use- MapReduce or Aggregation pipeline?
Some blogs says that mapreduce is slower than aggregation. So which one is ideal to use?</p>

答:
If you go through the official document  you can clearly see it written:

For most aggregation operations, the Aggregation Pipeline provides better performance and more coherent interface. However, map-reduce operations provide some flexibility that is not presently available in the aggregation pipeline.