问:
@RelatedTo(elementClass = Concept.class) RelatedTo.elementClass must be a class liter
Reading this documentation, I tryed to apply to my code in this way:

Triple

```<code>@Entity
@Table(name = "triple")
@NodeEntity
public class TripleDBMoldelNeoImpl implements TripleDBModel{
    protected List<Annotation> annotations;

    @RelatedTo(type = "subject", elementClass = (Class<? extends NodeBacked>) Concept.class) //This is the suggestion Eclipse gives me
    public Concept subject;
    @RelatedTo(type = "object", elementClass = Concept.class)
    public Concept object;
    @RelatedTo(type = "predicate", elementClass = Concept.class)
    public Concept predicate;

    @ManyToMany(
            cascade={CascadeType.ALL },
            fetch=FetchType.LAZY
    )
    @JoinTable(name = "triple_has_annotation",
            joinColumns={@JoinColumn(name="uri_concept_subject"), @JoinColumn(name="uri_concept_object"), @JoinColumn(name="uri_concept_predicate") },
            inverseJoinColumns=@JoinColumn(name="annotation_id") )
    public List<Annotation> getAnnotations() {
        return annotations;
    }
    public void setAnnotations(List<Annotation> annotations) {
        this.annotations = annotations;
    }
    @Id
    @Column(name = "subject", length = 100)
    public Concept getSubject() {
        return subject;
    }
    public void setSubject(Concept subject) {
        this.subject = subject;
    }

    @Id
    @Column(name = "object", length = 100)
    public Concept getObject() {
        return object;
    }
    public void setObject(Concept object) {
        this.object = object;
    }
    @Id
    @Column(name = "predicate", length = 100)
    public Concept getPredicate() {
        return predicate;
    }
    public void setPredicate(Concept predicate) {
        this.predicate = predicate;
    }
</code>```

Concept

```<code>@NodeEntity(partial = true)
public class ConceptNeoImpl implements java.io.Serializable, Concept {

    private static final long serialVersionUID = 1L;
    private String uri;
    private String label;
    private String ontologyElement;
    private List<Annotation> annotations;
    @RelatedTo(type = "conceptSub", elementClass = TripleDBModel.class)
    private TripleDBModel triple;

    public TripleDBModel getTriple() {
        return triple;
    }

    public void setTriple(TripleDBModel triple) {
        this.triple = triple;
    }
</code>```

The use I want to is explained on the image below

Then, the table triple will be using neo4j and concept will be using jpa and neo4j. I am programming using Eclipse IDE and it gives me suggestions to correct the errors. The first one is:

```<code>@RelatedTo(type = "conceptUriSubject", elementClass = Concept.class)
</code>```

correct to

```<code>@RelatedTo(type = "conceptUriSubject", elementClass = (Class<? extends NodeBacked>) Concept.class)
</code>```

And then, the problem is not solved, and gives me the nex message

Multiple markers at this line
    - The value for annotation attribute RelatedTo.elementClass must be a class
  literal
    - Type safety: Unchecked cast from Class to Class
  NodeBacked>
    - The value for annotation attribute RelatedTo.elementClass must be a class
  literal
    - Type safety: Unchecked cast from Class to Class
  NodeBacked>

Any ideas¿¿ I am new on this, so I am quite lost and I already asked on spring forums, with no success. Thanks in advance

EDIT
Plugins on my pom.xml

```<code><plugins>
          <plugin>
            <!-- Execute the main class -->
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <mainClass>org.springframework.data.neo4j.examples.hellograph.App</mainClass>
            </configuration>
          </plugin>
          <plugin>
            <!-- IntelliJ Idea Support -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-idea-plugin</artifactId>
            <version>2.2</version>
            <configuration>
              <downloadSources>true</downloadSources>
              <dependenciesAsLibraries>true</dependenciesAsLibraries>
            </configuration>
          </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.0</version>
                <dependencies>
                    <!-- NB: You must use Maven 2.0.9 or above or these are ignored (see
                        MNG-2972) -->
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjrt</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjtools</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <outxml>true</outxml>
                    <aspectLibraries>
                        <aspectLibrary>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-aspects</artifactId>
                        </aspectLibrary>
                        <aspectLibrary>
                            <groupId>org.springframework.data</groupId>
                            <artifactId>spring-data-neo4j</artifactId>
                        </aspectLibrary>
                    </aspectLibraries>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

        </plugins>
</code>```

Software installed in eclipse

答:
Please install the AspectJ Plugin in your eclipse IDE using this update site:

http://download.eclipse.org/tools/ajdt/36/dev/update

Then you should be able to enable AspectJ support for your project using the context menu.

Your domain class will be enhanced to implement the NodeBacked interface and then the IDE won't give you any errors in the annotations or elsewhere.

Sorry for the confusion. We are going to address those issues in the next release.

Update:

Sorry I didn't notice that earlier but the Concept you put into the elementClass is actually an interface and as it is neither annotated with @NodeEntity nor extending NodeBacked this is the real problem.

I think you also asked the question in the Spring forums, here are my suggestions from there:

Your Concept is an interface and does not extend NodeBacked right now.

In general: the NodeBacked interface is added to classes that have the @NodeEntity annotation.

Then you might try the same solution.

either annotate Concept with @NodeEntity too.

or have Concept extend NodeBacked on itself

Important: elementClass should rather refer to the concrete implementation (this might work with the interface though as it is just used to check for compatibility with the target).

Body:
Reading this documentation, I tryed to apply to my code in this way:

Triple

@Entity
@Table(name = "triple")
@NodeEntity
public class TripleDBMoldelNeoImpl implements TripleDBModel{
    protected List<Annotation> annotations;

    @RelatedTo(type = "subject", elementClass = (Class<? extends NodeBacked>) Concept.class) //This is the suggestion Eclipse gives me
    public Concept subject;
    @RelatedTo(type = "object", elementClass = Concept.class)
    public Concept object;
    @RelatedTo(type = "predicate", elementClass = Concept.class)
    public Concept predicate;

    @ManyToMany(
            cascade={CascadeType.ALL },
            fetch=FetchType.LAZY
    )
    @JoinTable(name = "triple_has_annotation",
            joinColumns={@JoinColumn(name="uri_concept_subject"), @JoinColumn(name="uri_concept_object"), @JoinColumn(name="uri_concept_predicate") },
            inverseJoinColumns=@JoinColumn(name="annotation_id") )
    public List<Annotation> getAnnotations() {
        return annotations;
    }
    public void setAnnotations(List<Annotation> annotations) {
        this.annotations = annotations;
    }
    @Id
    @Column(name = "subject", length = 100)
    public Concept getSubject() {
        return subject;
    }
    public void setSubject(Concept subject) {
        this.subject = subject;
    }

    @Id
    @Column(name = "object", length = 100)
    public Concept getObject() {
        return object;
    }
    public void setObject(Concept object) {
        this.object = object;
    }
    @Id
    @Column(name = "predicate", length = 100)
    public Concept getPredicate() {
        return predicate;
    }
    public void setPredicate(Concept predicate) {
        this.predicate = predicate;
    }

Concept

@NodeEntity(partial = true)
public class ConceptNeoImpl implements java.io.Serializable, Concept {

    private static final long serialVersionUID = 1L;
    private String uri;
    private String label;
    private String ontologyElement;
    private List<Annotation> annotations;
    @RelatedTo(type = "conceptSub", elementClass = TripleDBModel.class)
    private TripleDBModel triple;

    public TripleDBModel getTriple() {
        return triple;
    }

    public void setTriple(TripleDBModel triple) {
        this.triple = triple;
    }

The use I want to is explained on the image below

Then, the table triple will be using neo4j and concept will be using jpa and neo4j. I am programming using Eclipse IDE and it gives me suggestions to correct the errors. The first one is:

@RelatedTo(type = "conceptUriSubject", elementClass = Concept.class)

correct to

@RelatedTo(type = "conceptUriSubject", elementClass = (Class<? extends NodeBacked>) Concept.class)

And then, the problem is not solved, and gives me the nex message

Multiple markers at this line
    - The value for annotation attribute RelatedTo.elementClass must be a class
  literal
    - Type safety: Unchecked cast from Class to Class
  NodeBacked>
    - The value for annotation attribute RelatedTo.elementClass must be a class
  literal
    - Type safety: Unchecked cast from Class to Class
  NodeBacked>

Any ideas¿¿ I am new on this, so I am quite lost and I already asked on spring forums, with no success. Thanks in advance

EDIT
Plugins on my pom.xml

<plugins>
          <plugin>

            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <mainClass>org.springframework.data.neo4j.examples.hellograph.App</mainClass>
            </configuration>
          </plugin>
          <plugin>

            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-idea-plugin</artifactId>
            <version>2.2</version>
            <configuration>
              <downloadSources>true</downloadSources>
              <dependenciesAsLibraries>true</dependenciesAsLibraries>
            </configuration>
          </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.0</version>
                <dependencies>

                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjrt</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjtools</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <outxml>true</outxml>
                    <aspectLibraries>
                        <aspectLibrary>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-aspects</artifactId>
                        </aspectLibrary>
                        <aspectLibrary>
                            <groupId>org.springframework.data</groupId>
                            <artifactId>spring-data-neo4j</artifactId>
                        </aspectLibrary>
                    </aspectLibraries>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

        </plugins>

Software installed in eclipse


来源: stackexchange

问:
Is it possible to findout if someone used date option in git commit?
Trying to figure out strange structure of a git repository. The chronological order of commits doesn't make sense.

Is it possible to find out if someone used --date option during git commit?

答:
Is it possible to find out if someone used --date option during git commit?

No.  That is, commits do have date stamps, but there's no telling where the date stamp came from.

In fact, every commit has two date-and-time stamps:

```<code>$ git cat-file -p HEAD | sed 's/@/ /'
tree f8fa7543afb10d56e2138e2a7313aa8c2c93f3ba
parent bc7a3d4dc04dd719e7c8c35ebd7a6e6651c5c5b6
parent a0ba80001a42eeacae94e3503c3e7d4bf7f2f2e1
author Junio C Hamano <gitster pobox.com> 1580160367 -0800
committer Junio C Hamano <gitster pobox.com> 1580160367 -0800

Sync with maint

* maint:
  .mailmap: fix erroneous authorship for Johannes Schindelin
</code>```

The author line gives the name, email address, and date-and-time stamp for the author, and the committer line gives the name, email address, and date-and-time stamp for the committer.  They are often exactly the same, as here, but not always.  The date-and-time are in the form of the two numbers: the first is a Unix-like time value (count of seconds since 1970) and the second is the time zone offset.

By default, when copying a commit (as with git rebase or git cherry-pick), Git keeps the original author data, and writes new committer data.  When git log sorts commits,1 it uses the committer timestamp by default, although as John Szakmeister noted in a comment, it shows the author information, including author timestamp, by default.

can someone fake both author date and commit date?

Yes—plus, for a new commit, those default to reading the computer's clock, which could be wrong.  By "wrong" I don't just mean off a few nanoseconds, which is bad enough but doesn't affect Git (Git's resolution is whole seconds), but off by minutes, or hours, or even years.

Because the hash ID of any commit is the SHA-1 checksum of its (meta)data—its contents as shown above, with the tree and parent and author lines and so on—it is extremely difficult to tamper with any existing commit.  You not only have to break SHA-1 (not impossible any more) but also make the commit data "look right".  This means that if you have an existing repository that you trust, you don't have to worry about someone secretly replacing existing commits with new commits with the same hash ID: that's (a) way too hard and (b) profitless.  You can be mildly concerned with wrong or faked timestamps in new commits, but since your Git repository is yours, you can simply vet them before you allow them in.2

Note that the input data that result in the commit's hash ID include the hash IDs of the parent commits.  This means that the commits themselves form a Merkle tree.  Hence, the fact that some commit H passes some sort of cryptographic test implies that H's parent G also passes that test, which implies that G's parent F passes that test, and so on.  So you can GPG-sign particular commits using an annotated tag, which puts a pretty strong digital signature on the tag.  While SHA-1 itself is relatively weak, you can, if you're that worried, inspect each commit to make sure it has no "random junk" data area where someone can write bytes to construct a desired hash.  Then, if you trust the GPG signature, you can trust all the commits leading up to that signed commit—at least to the extent that you trust whoever made the GPG signature.

(It's possible to GPG-sign each commit, but in many work-flows, this is impractical.  When Git moves to SHA256, concerns over the relative weakness of SHA1 may abate, too.)

1Explaining just when git log actually sorts commits is a bit tricky.  In many or even most cases, git log is following a simple chain of commits, one commit at a time, so that there is no opportunity for sorting.  The command must be following more than one commit at the particular time.

The way git log works is this:

You start it with one or more starting point commits.  (It might be more appropriate to call these ending points because Git works backwards, but git log itself is going to start here.)

These commits go into a priority queue.  The priority is determined by the sort criteria.  So if you start Git with two or more commits, they get sorted here.

Then, as git log walk the graph, it pulls one commit out of the priority queue, examines it, determines whether to show it, and shows it or doesn't according to the show or don't show criteria you've specified.  Then it puts none, some, or all of that commit's parent commit hash IDs into the priority queue.  So if the commit has two or more parents, and git log puts them all into the priority queue, they get sorted here, at this point.

Different options to git log affect the sorting, the displaying criteria, and the set of parent hashes that get put into the queue.  For instance, the --first-parent option directs git log to insert only the first parent of any commit.

The most complicated of all of these is git log's history simplification mode, in which it may omit some parents entirely and/or "rewrite" the parent hashes attached to a commit (temporarily in memory only—the actual repository is not, and cannot be, altered).  History simplification is, for instance, how Git synthesizes a "file history" when you run git log --follow file: there is no such thing as file history, but by taking the commit history and dropping many commits and fiddling with the linkages in memory, Git can make a pretend file history, and show that instead of the actual history.

2This is easier said than done.  If your repository accepts git push requests, you can vet incoming commits in pre-receive and update hooks.  You have to write these hooks yourself, and they are nontrivial to write correctly.  If you git fetch to obtain new commits, you still have to write your own code to do this kind of screening, but this time, instead of having a pre-receive or update hook do it, you would probably create or update your own branch names after letting git fetch update remote-tracking names as usual.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to find out if someone used --date option during git commit?

No.  That is, commits do have date stamps, but there's no telling where the date stamp came from.

In fact, every commit has two date-and-time stamps:

$ git cat-file -p HEAD | sed 's/@/ /'
tree f8fa7543afb10d56e2138e2a7313aa8c2c93f3ba
parent bc7a3d4dc04dd719e7c8c35ebd7a6e6651c5c5b6
parent a0ba80001a42eeacae94e3503c3e7d4bf7f2f2e1
author Junio C Hamano <gitster pobox.com> 1580160367 -0800
committer Junio C Hamano <gitster pobox.com> 1580160367 -0800

Sync with maint

* maint:
  .mailmap: fix erroneous authorship for Johannes Schindelin

The author line gives the name, email address, and date-and-time stamp for the author, and the committer line gives the name, email address, and date-and-time stamp for the committer.  They are often exactly the same, as here, but not always.  The date-and-time are in the form of the two numbers: the first is a Unix-like time value (count of seconds since 1970) and the second is the time zone offset.

By default, when copying a commit (as with git rebase or git cherry-pick), Git keeps the original author data, and writes new committer data.  When git log sorts commits,1 it uses the committer timestamp by default, although as John Szakmeister noted in a comment, it shows the author information, including author timestamp, by default.

can someone fake both author date and commit date?

Yes—plus, for a new commit, those default to reading the computer's clock, which could be wrong.  By "wrong" I don't just mean off a few nanoseconds, which is bad enough but doesn't affect Git (Git's resolution is whole seconds), but off by minutes, or hours, or even years.

Because the hash ID of any commit is the SHA-1 checksum of its (meta)data—its contents as shown above, with the tree and parent and author lines and so on—it is extremely difficult to tamper with any existing commit.  You not only have to break SHA-1 (not impossible any more) but also make the commit data "look right".  This means that if you have an existing repository that you trust, you don't have to worry about someone secretly replacing existing commits with new commits with the same hash ID: that's (a) way too hard and (b) profitless.  You can be mildly concerned with wrong or faked timestamps in new commits, but since your Git repository is yours, you can simply vet them before you allow them in.2

Note that the input data that result in the commit's hash ID include the hash IDs of the parent commits.  This means that the commits themselves form a Merkle tree.  Hence, the fact that some commit H passes some sort of cryptographic test implies that H's parent G also passes that test, which implies that G's parent F passes that test, and so on.  So you can GPG-sign particular commits using an annotated tag, which puts a pretty strong digital signature on the tag.  While SHA-1 itself is relatively weak, you can, if you're that worried, inspect each commit to make sure it has no "random junk" data area where someone can write bytes to construct a desired hash.  Then, if you trust the GPG signature, you can trust all the commits leading up to that signed commit—at least to the extent that you trust whoever made the GPG signature.

(It's possible to GPG-sign each commit, but in many work-flows, this is impractical.  When Git moves to SHA256, concerns over the relative weakness of SHA1 may abate, too.)

1Explaining just when git log actually sorts commits is a bit tricky.  In many or even most cases, git log is following a simple chain of commits, one commit at a time, so that there is no opportunity for sorting.  The command must be following more than one commit at the particular time.

The way git log works is this:

You start it with one or more starting point commits.  (It might be more appropriate to call these ending points because Git works backwards, but git log itself is going to start here.)

These commits go into a priority queue.  The priority is determined by the sort criteria.  So if you start Git with two or more commits, they get sorted here.

Then, as git log walk the graph, it pulls one commit out of the priority queue, examines it, determines whether to show it, and shows it or doesn't according to the show or don't show criteria you've specified.  Then it puts none, some, or all of that commit's parent commit hash IDs into the priority queue.  So if the commit has two or more parents, and git log puts them all into the priority queue, they get sorted here, at this point.

Different options to git log affect the sorting, the displaying criteria, and the set of parent hashes that get put into the queue.  For instance, the --first-parent option directs git log to insert only the first parent of any commit.

The most complicated of all of these is git log's history simplification mode, in which it may omit some parents entirely and/or "rewrite" the parent hashes attached to a commit (temporarily in memory only—the actual repository is not, and cannot be, altered).  History simplification is, for instance, how Git synthesizes a "file history" when you run git log --follow file: there is no such thing as file history, but by taking the commit history and dropping many commits and fiddling with the linkages in memory, Git can make a pretend file history, and show that instead of the actual history.

2This is easier said than done.  If your repository accepts git push requests, you can vet incoming commits in pre-receive and update hooks.  You have to write these hooks yourself, and they are nontrivial to write correctly.  If you git fetch to obtain new commits, you still have to write your own code to do this kind of screening, but this time, instead of having a pre-receive or update hook do it, you would probably create or update your own branch names after letting git fetch update remote-tracking names as usual.


问:
Best way to move files between S3 buckets?
I'd like to copy some files from a production bucket to a development bucket daily.

For example:
Copy productionbucket/feed/feedname/date
to developmentbucket/feed/feedname/date

Because the files I want are so deep in the folder structure, it's too time consuming to go to each folder and copy/paste.

I've played around with mounting drives to each bucket and writing a windows batch script, but that is very slow and it unnecessarily downloads all the files/folders to the local server and back up again.

答:
For new version aws2.</p>

```<code>aws2 s3 sync s3://SOURCE_BUCKET_NAME s3://NEW_BUCKET_NAME
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For new version aws2.

aws2 s3 sync s3://SOURCE_BUCKET_NAME s3://NEW_BUCKET_NAME


问:
What is wrong with how I'm dynamically allocating space for this 2d array?
I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

How do I dynamically allocate space for it?

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

```<code>char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));
</code>```

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?

答:
The code you have posted is 'OK', so long as you remember to call free() on the allocated memory, later in your code, like this:

for (i=0;i<rownum2;i++) free(arr[i]);
```

<blockquote>
  <p>...and I've also been told some parts of this are unnecessary.</p>
</blockquote>

<p>The explicit cast is unnecessary, so, instead of:</p>

<pre class="lang-c prettyprint-override"><code>arr[i] =  (char *)malloc(colnum*sizeof(char));
</code>```

just use:

arr[i] =  malloc(colnum*sizeof(char));
```

The sizeof(char) is also, strictly speaking, unnecessary (char will always have a size of 1) but you can leave that, for clarity.

Body:
I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

How do I dynamically allocate space for it?

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?

Body:
The code you have posted is 'OK', so long as you remember to call free() on the allocated memory, later in your code, like this:

for (i=0;i<rownum2;i++) free(arr[i]);

...and I've also been told some parts of this are unnecessary.

The explicit cast is unnecessary, so, instead of:

arr[i] =  (char *)malloc(colnum*sizeof(char));

just use:

arr[i] =  malloc(colnum*sizeof(char));

The sizeof(char) is also, strictly speaking, unnecessary (char will always have a size of 1) but you can leave that, for clarity.


问:
Is "from ... import ..." sometimes required and plain "import ..." not always working? Why?
I always thought, doing from x import y and then directly use y, or doing import x and later use x.y was only a matter of style and avoiding naming conflicts. But it seems like this is not always the case. Sometimes from ... import ... seems to be required:

Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> PIL.__version__
'6.1.0'
>>> im = PIL.Image.open("test.png")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'PIL' has no attribute 'Image'
>>> from PIL import Image
>>> im = Image.open("test.png")
>>>
```

Am I doing something wrong here?

If not, can someone please explain me the mechanics behind this behavior? Thanks!

答:
For submodules, you have to explicitly import the submodule, whether or not you use from. The non-from import should look like

```<code>import PIL.Image
</code>```

Otherwise, Python won't load the submodule, and the submodule will only be accessible if the package itself imports the submodule for you or if some previous code has explicitly imported the submodule.

Body:
I always thought, doing from x import y and then directly use y, or doing import x and later use x.y was only a matter of style and avoiding naming conflicts. But it seems like this is not always the case. Sometimes from ... import ... seems to be required:

Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> PIL.__version__
'6.1.0'
>>> im = PIL.Image.open("test.png")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'PIL' has no attribute 'Image'
>>> from PIL import Image
>>> im = Image.open("test.png")
>>>

Am I doing something wrong here?

If not, can someone please explain me the mechanics behind this behavior? Thanks!

Body:
For submodules, you have to explicitly import the submodule, whether or not you use from. The non-from import should look like

import PIL.Image

Otherwise, Python won't load the submodule, and the submodule will only be accessible if the package itself imports the submodule for you or if some previous code has explicitly imported the submodule.


问:
Fastest way to deserialize multiple json strings using Json.NET
I will be retrieving multiple blocks of json data over time and deserializing them using Json.NET. I have objects created that mirror the structure of each different block of data, but when each block is received I will not be able to detect the type.

I would like to avoid attempting deserialization for each type, catching the failures (when exceptions are thrown) and moving on to the next type. Doing so would obviously be bad for performance.

Is there a fast and efficient way to determine the structure of a json message and deserialize it? Would the only way to use (JObject)JsonConvert.DeserializeObject(...) then drill into the structure to check if certain children exist, then using JsonConvert.DeserializeObject<T>(...)? It seems deserializing the object twice is inefficient.

答:
You stated that trial-and-error deserializing "would obviously be bad for performance." Have you measured this? Does the deserializer take very long to determine it's got the wrong type? It may be inelegant, but may not be that expensive.

Depending upon your measurements, you might be able to do a partial string comparison of the beginning of your JSON data and branch to the correct type, with a trial-and-error as a fallback.

However, you might find that if you try deserializing by the type most likely to occur, then you might find it fast enough without having to do extra comparisons.


问:
Hibernate .getResultStream() not streaming?
I am trying to stream a lot of data from MySQL with Hibernate via .getResultStream() and I am getting OutOfMemoryErrors.

On the first row load after a while I will get this exception where I can see:

```<code>    at com.mysql.jdbc.MysqlIO.nextRow(MysqlIO.java:1963) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.readSingleRowSet(MysqlIO.java:3308) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.getResultSet(MysqlIO.java:463) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:3032) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:2280) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673) ~[mysql-connector-java-5.1.37.jar:5.1.37]
</code>```

what surprises me here is the readAllResults - this would seem it is not a real streaming.

I also tried to use:

```<code>query.setHint("org.hibernate.fetchSize", 1000)
</code>```

With no effect.

I have then upgraded to MySQL Connector 8.0.19 and Hibernate 5.4.11.Final with the same effect.

答:
Following applies only for Hibernate versions without HHH-9340. Correct answer is the other one.

That is correct observation. Method getResultStream just views result list as a Stream. According API documentation:

By default this method delegates to getResultList().stream(), however
persistence provider may choose to override this method to provide
additional capabilities.

Hibernate has selected not to override this method, as can be seen from QueryImpl and classes it inherits from.

Body:
I am trying to stream a lot of data from MySQL with Hibernate via .getResultStream() and I am getting OutOfMemoryErrors.

On the first row load after a while I will get this exception where I can see:

    at com.mysql.jdbc.MysqlIO.nextRow(MysqlIO.java:1963) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.readSingleRowSet(MysqlIO.java:3308) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.getResultSet(MysqlIO.java:463) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:3032) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:2280) ~[mysql-connector-java-5.1.37.jar:5.1.37]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673) ~[mysql-connector-java-5.1.37.jar:5.1.37]

what surprises me here is the readAllResults - this would seem it is not a real streaming.

I also tried to use:

query.setHint("org.hibernate.fetchSize", 1000)

With no effect.

I have then upgraded to MySQL Connector 8.0.19 and Hibernate 5.4.11.Final with the same effect.


问:
Firebase function won't deleted child after certain time
I want to deleted a child after a certain time. I know that you need Firebase function to achief this. This is what I got so far:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const timeNow = Date.now();
    const Ref = admin.database().ref('/Feed');
    Ref.once('value', (snapshot) => {
        snapshot.forEach((child) => {
            if (1000*(Number(child.val()['timestamp']) + Number(child.val()['duration'])) >= timeNow) {
               child.ref.set(null);
            }
        });
    });
    return res.status(200).end();
});
</code>```

I want to deleted the child when the duration is over (the duration is in seconds). This is my structure:

Thanks!

答:
You're sending a response to the caller at the end of the function, which will be executed before the data from the database is returned. And Cloud Functions will stop executing your code straight after that res.status(200).end(), so the database cleanup never happens.

To prevent this, only send a response to the caller after all data has been deleted from the database:

```<code>exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const timeNow = Date.now();
    const Ref = admin.database().ref('/Feed');
    return Ref.once('value', (snapshot) => {
        let updates = [];
        snapshot.forEach((child) => {
            if (1000*(child.val().timestamp + child.val().duration) >= timeNow) {
               updates[child.key] = null;
            }
        });
        return Ref.update(updates).then(() => {
            return res.status(200).end();
        });
    });
});
</code>```

I highly recommend storing an additional property in your child nodes though, with the precalculated value of timestamp + duration. By having such a property, you can run a query on the nodes that have expired, instead of having to read all child nodes and then filtering in code.

For an example of this, see my answer to Delete firebase data older than 2 hours, and the Cloud Functions example that was based on that.

Body:
I want to deleted a child after a certain time. I know that you need Firebase function to achief this. This is what I got so far:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const timeNow = Date.now();
    const Ref = admin.database().ref('/Feed');
    Ref.once('value', (snapshot) => {
        snapshot.forEach((child) => {
            if (1000*(Number(child.val()['timestamp']) + Number(child.val()['duration'])) >= timeNow) {
               child.ref.set(null);
            }
        });
    });
    return res.status(200).end();
});

I want to deleted the child when the duration is over (the duration is in seconds). This is my structure:

Thanks!

Body:
You're sending a response to the caller at the end of the function, which will be executed before the data from the database is returned. And Cloud Functions will stop executing your code straight after that res.status(200).end(), so the database cleanup never happens.

To prevent this, only send a response to the caller after all data has been deleted from the database:

exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const timeNow = Date.now();
    const Ref = admin.database().ref('/Feed');
    return Ref.once('value', (snapshot) => {
        let updates = [];
        snapshot.forEach((child) => {
            if (1000*(child.val().timestamp + child.val().duration) >= timeNow) {
               updates[child.key] = null;
            }
        });
        return Ref.update(updates).then(() => {
            return res.status(200).end();
        });
    });
});

I highly recommend storing an additional property in your child nodes though, with the precalculated value of timestamp + duration. By having such a property, you can run a query on the nodes that have expired, instead of having to read all child nodes and then filtering in code.

For an example of this, see my answer to Delete firebase data older than 2 hours, and the Cloud Functions example that was based on that.


问:
Why both onkeyup and keyup is not working?
I want to display what the user is typing on the  Text from the input field. I already tried .onkeyup and addEventListener in javascript but they are not both working though it can detect the target input object but when it comes in .onkeyup and addEventListenerit does nothing.

Here's what I am trying to do:

While a user is typing in the input field First Name it should be displayed in the  Hyperlink Text (Even the backspace key stroke should be applied)

Here's my snippet code in my view/blade template:

```<code><ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#guestInfo0">User Information</a></li>
    @for($guest_no = 1; $guest_no<=$guest_quantity; $guest_no++)
        <li>
            <a data-toggle="tab"
                href="#guestInfo{{$guest_no}}"
                id = "linkText">Guest #{{$guest_no}} //Target ID = linkText (this is where the changes will be applied)
            </a>
        </li>
    @endfor
</ul>
.......
<input id="passenger_f_name" type="text"
class="form-control @error('passenger_f_name') is-invalid @enderror"
placeholder = "First Name for Passenger #{{$tab}}" name="passenger_f_name"
value="{{ old('passenger_f_name') }}" required autocomplete="passenger_f_name"
autofocus>
.......
<script type="application/javascript">

    var linkBox = document.getElementById('passenger_f_name');

    linkBox.onkeyup = function(){
        //alert("LOL"); //Used for checking if onkeyup is working properly = result: false
        document.getElementById('linkText').innerHTML = linkBox.value;
    }

</script>
</code>```

I don't know why it is not working But I suspect [DOM]'s warning in console log (Posted screenshot instead of copying and pasting here because it does not have options in google chrome console to copy the warning message):

It has three inputs because every tab has a form and input on it that has same name and IDs (depends on the for loop's condition on how many forms would be generated).

P.S. I am using:

Google Chrome Version 79.0.3945.130 (Official Build) (64-bit)

JQuery 3.4.1 & Bootstrap 3.4.1

Laravel 6.0

答:
You need unique IDs

Here is how to do it if there is ONE input field and 3 guests

$("#passenger_f_name").on("input",function() {
  $("li.active .linkText").text(this.value)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav nav-tabs">
  <li>User Information</li>
  <li>
    Guest #1
  </li>
  <li>User Information</li>
  <li>
    Guest #2
  </li>
  <li>User Information</li>
  <li class="active">
    Guest #3
  </li>
</ul>
<input id="passenger_f_name" type="text" class="form-control" placeholder="First Name for Passenger #{{$tab}}" name="passenger_f_name" value="" required autocomplete="passenger_f_name" autofocus></code>```

Body:
I want to display what the user is typing on the  Text from the input field. I already tried .onkeyup and addEventListener in javascript but they are not both working though it can detect the target input object but when it comes in .onkeyup and addEventListenerit does nothing.

Here's what I am trying to do:

While a user is typing in the input field First Name it should be displayed in the  Hyperlink Text (Even the backspace key stroke should be applied)

Here's my snippet code in my view/blade template:

User Information

    @for($guest_no = 1; $guest_no<=$guest_quantity; $guest_no++)

            Guest #{{$guest_no}} //Target ID = linkText (this is where the changes will be applied)

    @endfor

.......
<input id="passenger_f_name" type="text"
class="form-control @error('passenger_f_name') is-invalid @enderror"
placeholder = "First Name for Passenger #{{$tab}}" name="passenger_f_name"
value="{{ old('passenger_f_name') }}" required autocomplete="passenger_f_name"
autofocus>
.......

I don't know why it is not working But I suspect [DOM]'s warning in console log (Posted screenshot instead of copying and pasting here because it does not have options in google chrome console to copy the warning message):

It has three inputs because every tab has a form and input on it that has same name and IDs (depends on the for loop's condition on how many forms would be generated).

P.S. I am using:

Google Chrome Version 79.0.3945.130 (Official Build) (64-bit)

JQuery 3.4.1 & Bootstrap 3.4.1

Laravel 6.0

Body:
You need unique IDs

Here is how to do it if there is ONE input field and 3 guests

$("#passenger_f_name").on("input",function() {
  $("li.active .linkText").text(this.value)
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav nav-tabs">
  <li><a data-toggle="tab" href="#guestInfo0">User Information</a></li>
  <li>
    <a data-toggle="tab" href="#guestInfo{{$guest_no}}" class="linkText">Guest #1</a>
  </li>
  <li><a data-toggle="tab" href="#guestInfo0">User Information</a></li>
  <li>
    <a data-toggle="tab" href="#guestInfo{{$guest_no}}" class="linkText">Guest #2</a>
  </li>
  <li><a data-toggle="tab" href="#guestInfo0">User Information</a></li>
  <li class="active">
    <a data-toggle="tab" href="#guestInfo{{$guest_no}}" class="linkText">Guest #3</a>
  </li>
</ul>
<input id="passenger_f_name" type="text" class="form-control" placeholder="First Name for Passenger #{{$tab}}" name="passenger_f_name" value="" required autocomplete="passenger_f_name" autofocus>


问:
may COM server reallocate ([in, out] CACLSID * arg)?
With a COM interface method declared as this:

```<code>[ object,
  uuid(....),
]
interface IFoo : IUnknown
{
  HRESULT Foo([in, out] CACLSID * items);
}
</code>```

With regards to marshalling, is the server allowed to reallocate the counted array? (I think it is, but I am not sure anymore)

Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface.

[edit] please note that CACLSID is already an array, containing a count and a pointer.

答: I have not done COM for a very long time but is it even possible to allocate a new array?  In that case should it not be CACLSID ** items ?

OwnerDisplayName: peterchen

ContentLicense: CC BY-SA 2.5

Body:
With a COM interface method declared as this:

[ object,
  uuid(....),
]
interface IFoo : IUnknown
{
  HRESULT Foo([in, out] CACLSID * items);
}

With regards to marshalling, is the server allowed to reallocate the counted array? (I think it is, but I am not sure anymore)

Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface.

[edit] please note that CACLSID is already an array, containing a count and a pointer.

LastEditorDisplayName: peterchen


问:
Sharepoint-Designer 2010 "Remember-Mail-Workflow"
I got an pretty simple problem, but cant get over it.
I got a task in my Sharepoint 2010 and you have to confirm a transaction.. thats working alright.

Each task involves 3 people and they are sorted in a list with the headers :

Assigned to

Title

Status

Result

So I had the idea to make a workflow to remind ppl on the task, when the status in NOT "completed".
This also seem to work, but the problem is when I tell him to get the Description of the "Assigned to" part of the List he always takes the first one. So I have no chance to check the other ones in the list.

I would be really happy if you can help me.

答:
SharePoint Designer 2010 has no built-in capability for looping through multiple List Items that meet a criteria.  Most people will say you cannot achieve what you want to do with that version of SharePoint.

However, John Hipplito had a great post several years ago that shows how you can emulate it by creating a separate "Loop through Tasks" list, and you can use one workflow to add items to the second list as needed, and put your desired "for each" actions (in your case, your email reminder) in a separate workflow on the second list.  The process is much to long and detailed to list here, so I suggest you read his post at https://www.rbaconsulting.com/blog/tutorial-how-to-loop-through-multiple-list-items-without-code-using-a-sharepoint-2010-workflow/.

Since that blog post is already nearly five years old, and you never know when old blogs may be taken down, I will also post a link here to the wayback machine's archive of that blog post:  https://web.archive.org/web/20200215193135/https://www.rbaconsulting.com/blog/tutorial-how-to-loop-through-multiple-list-items-without-code-using-a-sharepoint-2010-workflow/


问:
DB transaction using R2BC Kotlin coroutine
I using R2bc in Spring Webflux project with Kotlin. It is working nicely. But I have this method

```<code>@Component
class UserRepository(private val client: DatabaseClient, private val operator: TransactionalOperator) {

    suspend fun updateUser(user: User, value: String): Int {

        client.execute("INSERT INTO log(user_id, activity) VALUES (:user_id, :activity)")
              .bind("activity", user.activity)
              .bind("user_id", user.id)
              .fetch()
              .awaitRowsUpdated()

        return client.execute("UPDATE users SET value = :value WHERE id = :id")
                     .bind("value", value)
                     .bind("id", user.id)
                     .fetch()
                     .awaitRowsUpdated()
}
</code>```

This method is working but I would like to use DB transaction. Is it supported in Kotlin.

答:
Ok I found the solution I am posting it here so that other can benefit from it. All I had to do was.</p>

```<code>@Component
class UserRepository(private val client: DatabaseClient, private val operator: TransactionalOperator) {

    suspend fun updateUser(user: User, value: String) =

        operator.executeAndAwait {

            client.execute("INSERT INTO log(user_id, activity) VALUES (:user_id, :activity)")
                  .bind("activity", user.activity)
                  .bind("user_id", user.id)
                  .await()

            client.execute("UPDATE users SET value = :value WHERE id = :id")
                  .bind("value", value)
                  .bind("id", user.id)
                  .await()
        }

}
</code>```

Body:
I using R2bc in Spring Webflux project with Kotlin. It is working nicely. But I have this method

@Component
class UserRepository(private val client: DatabaseClient, private val operator: TransactionalOperator) {

    suspend fun updateUser(user: User, value: String): Int {

        client.execute("INSERT INTO log(user_id, activity) VALUES (:user_id, :activity)")
              .bind("activity", user.activity)
              .bind("user_id", user.id)
              .fetch()
              .awaitRowsUpdated()

        return client.execute("UPDATE users SET value = :value WHERE id = :id")
                     .bind("value", value)
                     .bind("id", user.id)
                     .fetch()
                     .awaitRowsUpdated()
}

This method is working but I would like to use DB transaction. Is it supported in Kotlin.

Body:
Ok I found the solution I am posting it here so that other can benefit from it. All I had to do was.

@Component
class UserRepository(private val client: DatabaseClient, private val operator: TransactionalOperator) {

    suspend fun updateUser(user: User, value: String) =

        operator.executeAndAwait {

            client.execute("INSERT INTO log(user_id, activity) VALUES (:user_id, :activity)")
                  .bind("activity", user.activity)
                  .bind("user_id", user.id)
                  .await()

            client.execute("UPDATE users SET value = :value WHERE id = :id")
                  .bind("value", value)
                  .bind("id", user.id)
                  .await()
        }

}


问:
Handle multiple button views
My question is about how to control the background and text color of multiple buttons when you read a button click in MVVM. To make my question a bit clear please have a look at the UI I have attached.

I have already implemented this on code behind i.e on button click, I am handling all of the buttons separately. The original background and text color are white and black respectively and when you click on any other button except 1W that button will be highlighted.
In the next image, 3M is clicked

```<code>            lbl3M.BackgroundColor = Color.FromHex(defaultColor);
            lbl3M.TextColor = Color.White;
            if (lbl1M.BackgroundColor != Color.White)
            {
                lbl1M.BackgroundColor = Color.White;
                lbl1M.TextColor = Color.Black;
            }
            if (lbl1W.BackgroundColor != Color.White)
            {
                lbl1W.BackgroundColor = Color.White;
                lbl1W.TextColor = Color.Black;
            }
            if (lbl6M.BackgroundColor != Color.White)
            {
                lbl6M.BackgroundColor = Color.White;
                lbl6M.TextColor = Color.Black;
            }
            if (lbl1Y.BackgroundColor != Color.White)
            {
                lbl1Y.BackgroundColor = Color.White;
                lbl1Y.TextColor = Color.Black;
            }
</code>```

I have done this on each button clicked.

I know this approach is not cost-effective and I want to learn how to implement in MVVM way

EDIT:
I have created a function which reset all the buttons to Original UI and change the UI on button clicked

```<code> void ResetButtonUI()
    {
        lbl1W.BackgroundColor = Color.White;
        lbl1W.TextColor = Color.Black;
        lbl1M.BackgroundColor = Color.White;
        lbl1M.TextColor = Color.Black;
        lbl3M.BackgroundColor = Color.White;
        lbl3M.TextColor = Color.Black;
        lbl6M.BackgroundColor = Color.White;
        lbl6M.TextColor = Color.Black;
        lbl1Y.BackgroundColor = Color.White;
        lbl1Y.TextColor = Color.Black;
    }
</code>```

and on each button i have this logic

```<code>         ResetButtonUI();
         button.BackgroundColor = Color.FromHex(defaultColor);
         button.TextColor = Color.White;
</code>```

答:
So there are 5 options and the user have to choose one of them.

The ViewModel must contain 2 properties:

Collection of all options

Selected option

It should look like this

// ReactiveObject is from ReactiveUI => https://reactiveui.net/
public class MainViewModel : ReactiveObject
{
    private readonly ObservableCollection<TimeSpanItem> _options;
    private TimeSpanItem _selectedOption;

    public ReadOnlyObservableCollection<TimeSpanItem> Options { get; }

    public TimeSpanItem SelectedOption { get => _selectedOption; set => this.RaiseAndSetIfChanged( ref _selectedOption, value ); }

    public MainViewModel()
    {
        _options = new ObservableCollection<TimeSpanItem>();
        Options = new ReadOnlyObservableCollection<TimeSpanItem>( _options );

        _options.Add( new TimeSpanItem( 1, TimeSpanKind.Week ) );
        _options.Add( new TimeSpanItem( 1, TimeSpanKind.Month ) );
        _options.Add( new TimeSpanItem( 3, TimeSpanKind.Month ) );
        _options.Add( new TimeSpanItem( 6, TimeSpanKind.Month ) );
        _options.Add( new TimeSpanItem( 1, TimeSpanKind.Year ) );

        SelectedOption = _options.Last();
    }
}
```

<p>and some data types:</p>

<pre class="lang-cs prettyprint-override"><code>public enum TimeSpanKind
{
    M = 2,
    W = 1,
    Y = 3,

    Week = W,
    Month = M,
    Year = Y,
}

public class TimeSpanItem
{
    public TimeSpanItem( int value, TimeSpanKind kind )
    {
        Value = value;
        Kind = kind;
    }

    public int Value { get; }
    public TimeSpanKind Kind { get; }

    public override string ToString()
    {
        return $"{Value}{Kind}";
    }
}
</code>```

Now it is time for the presentation. The easiest way to present a selectable collection is a ListBox or ListView because everything can be wired up in XAML

<Window
      x:Class="WpfApp1.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:WpfApp1"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      Title="MainWindow"
      Width="800"
      Height="450"
      mc:Ignorable="d">
<Window.DataContext>
  <local:MainViewModel/>
</Window.DataContext>
    <Grid>

        <ListBox
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              ItemsSource="{Binding Items}"
              SelectedItem="{Binding SelectedItem}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel
                          Margin="5"
                          Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock
                          MinWidth="40"
                          Margin="5"
                          Text="{Binding}"
                          TextAlignment="Center" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>
</Window>
```

and that is the result

Title: Handle multiple button views

Body:
My question is about how to control the background and text color of multiple buttons when you read a button click in MVVM. To make my question a bit clear please have a look at the UI I have attached.

I have already implemented this on code behind i.e on button click, I am handling all of the buttons separately. The original background and text color are white and black respectively and when you click on any other button except 1W that button will be highlighted.
In the next image, 3M is clicked

            lbl3M.BackgroundColor = Color.FromHex(defaultColor);
            lbl3M.TextColor = Color.White;
            if (lbl1M.BackgroundColor != Color.White)
            {
                lbl1M.BackgroundColor = Color.White;
                lbl1M.TextColor = Color.Black;
            }
            if (lbl1W.BackgroundColor != Color.White)
            {
                lbl1W.BackgroundColor = Color.White;
                lbl1W.TextColor = Color.Black;
            }
            if (lbl6M.BackgroundColor != Color.White)
            {
                lbl6M.BackgroundColor = Color.White;
                lbl6M.TextColor = Color.Black;
            }
            if (lbl1Y.BackgroundColor != Color.White)
            {
                lbl1Y.BackgroundColor = Color.White;
                lbl1Y.TextColor = Color.Black;
            }

I have done this on each button clicked.

I know this approach is not cost-effective and I want to learn how to implement in MVVM way

EDIT:
I have created a function which reset all the buttons to Original UI and change the UI on button clicked

 void ResetButtonUI()
    {
        lbl1W.BackgroundColor = Color.White;
        lbl1W.TextColor = Color.Black;
        lbl1M.BackgroundColor = Color.White;
        lbl1M.TextColor = Color.Black;
        lbl3M.BackgroundColor = Color.White;
        lbl3M.TextColor = Color.Black;
        lbl6M.BackgroundColor = Color.White;
        lbl6M.TextColor = Color.Black;
        lbl1Y.BackgroundColor = Color.White;
        lbl1Y.TextColor = Color.Black;
    }

and on each button i have this logic

         ResetButtonUI();
         button.BackgroundColor = Color.FromHex(defaultColor);
         button.TextColor = Color.White;

Body:
So there are 5 options and the user have to choose one of them.

The ViewModel must contain 2 properties:

Collection of all options

Selected option

It should look like this

// ReactiveObject is from ReactiveUI => https://reactiveui.net/
public class MainViewModel : ReactiveObject
{
    private readonly ObservableCollection<TimeSpanItem> _options;
    private TimeSpanItem _selectedOption;

    public ReadOnlyObservableCollection<TimeSpanItem> Options { get; }

    public TimeSpanItem SelectedOption { get => _selectedOption; set => this.RaiseAndSetIfChanged( ref _selectedOption, value ); }

    public MainViewModel()
    {
        _options = new ObservableCollection<TimeSpanItem>();
        Options = new ReadOnlyObservableCollection<TimeSpanItem>( _options );

        _options.Add( new TimeSpanItem( 1, TimeSpanKind.Week ) );
        _options.Add( new TimeSpanItem( 1, TimeSpanKind.Month ) );
        _options.Add( new TimeSpanItem( 3, TimeSpanKind.Month ) );
        _options.Add( new TimeSpanItem( 6, TimeSpanKind.Month ) );
        _options.Add( new TimeSpanItem( 1, TimeSpanKind.Year ) );

        SelectedOption = _options.Last();
    }
}

and some data types:

public enum TimeSpanKind
{
    M = 2,
    W = 1,
    Y = 3,

    Week = W,
    Month = M,
    Year = Y,
}

public class TimeSpanItem
{
    public TimeSpanItem( int value, TimeSpanKind kind )
    {
        Value = value;
        Kind = kind;
    }

    public int Value { get; }
    public TimeSpanKind Kind { get; }

    public override string ToString()
    {
        return $"{Value}{Kind}";
    }
}

Now it is time for the presentation. The easiest way to present a selectable collection is a ListBox or ListView because everything can be wired up in XAML

<Window
      x:Class="WpfApp1.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:WpfApp1"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      Title="MainWindow"
      Width="800"
      Height="450"
      mc:Ignorable="d">
<Window.DataContext>
  <local:MainViewModel/>
</Window.DataContext>
    <Grid>

        <ListBox
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              ItemsSource="{Binding Items}"
              SelectedItem="{Binding SelectedItem}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel
                          Margin="5"
                          Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock
                          MinWidth="40"
                          Margin="5"
                          Text="{Binding}"
                          TextAlignment="Center" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>
</Window>

and that is the result


问:
How to remove white border around app in overview mode
As you can see in the image, while in "Overview" mode, my app has a very thin white border at the bottom of the screen. You can also slightly see the white border at the top two corners. I've already set the windowBackground of the AppTheme to the color of my liking.

How can I stop this from happening? Can I change that white to a different color at least?

*P.S. while scrolling between the apps in overview, you can see the white border slightly flickering.

Image of situation:

Example of Activity XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Home.HomeFragment">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerRelativeView">
        <include layout="@layout/layout_feed_viewpager"/>

    </RelativeLayout>

    <include layout="@layout/layout_navigation_view"/>

</RelativeLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>```
</div>
</div>
</p>

<p>Style.xml </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <!-- Change color of ripple effect on buttons -->
        <item name="colorControlHighlight">@color/label</item>

        <!-- Change color of EditText hint ex. Email, Password -->
        <item name="android:textColorHint">@color/white</item>

        <!-- Change color of navigation bar (this does not work for older phones) -->
        <item name="android:navigationBarColor">@color/windowBackground</item>

        <!-- Change background color of all activities -->
        <item name="android:windowBackground">@color/windowBackground</item>

        <!--<item name="android:background">@color/toolbar</item>-->
    </style>

    <!-- BottomNavigationTheme -->
    <style name="BottomNavigationTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/stylistic</item>
        <item name="android:textColorSecondary">@color/label</item>
        <!-- <item name="android:textSize">17sp</item> -->
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources></code>```

Colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#1A1E21</color>
    <color name="colorSecondary">#242A2E</color>
    <color name="colorAccent">#D81B60</color>
    <color name="colorStroke">#707070</color>

    <color name="white">#FFFFFF</color>

    <color name="windowBackground">#1A1E21</color>
    <color name="label">#9E9F9F</color>
    <color name="search">#9AA0A6</color>
    <color name="navigation">#272E32</color>
    <color name="navigation_text">#606369</color>

    <color name="stylistic">#E3E4DF</color>
    <color name="sub_label">#5F6366</color>

    <color name="translucentBlack">#10848D95</color>
</resources>```

答:
you use

Theme.AppCompat.Light

but your pallette seems dark for your window backgrounds. So why not try using a different inherited theme? Like:

Theme.AppCompat

Body:
As you can see in the image, while in "Overview" mode, my app has a very thin white border at the bottom of the screen. You can also slightly see the white border at the top two corners. I've already set the windowBackground of the AppTheme to the color of my liking.

How can I stop this from happening? Can I change that white to a different color at least?

*P.S. while scrolling between the apps in overview, you can see the white border slightly flickering.

Image of situation:

Example of Activity XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Home.HomeFragment">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerRelativeView">
        <include layout="@layout/layout_feed_viewpager"/>

    </RelativeLayout>

    <include layout="@layout/layout_navigation_view"/>

</RelativeLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Style.xml

<resources>


问:
Renaming labels of a factor in R
I have census data of Male and Female populations organizaed by age group:

```<code>library(tidyverse)

url <- "https://www2.census.gov/programs-surveys/popest/datasets/2010-2018/counties/asrh/cc-est2018-alldata-54.csv"

if (!file.exists("./datafiles/cc-est2018-alldata-54.csv"))
  download.file(url, destfile = "./datafiles/cc-est2018-alldata-54.csv", mode = "wb")

popSample <- read.csv("./datafiles/cc-est2018-alldata-54.csv") %>%
  filter(AGEGRP != 0 & YEAR == 1) %>%
  select("STNAME", "CTYNAME", "AGEGRP", "TOT_POP", "TOT_MALE", "TOT_FEMALE")

popSample$AGEGRP <- as.factor(popSample$AGEGRP)
</code>```

I then plot the Male and Female population relationships, faceted by age group (1-18, which is currently treated as a int

```<code>g <- ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
  geom_point(alpha = 0.5, colour="darkblue") +
  scale_x_log10() +
  scale_y_log10() +
  facet_wrap(~AGEGRP) +
  stat_smooth(method = "lm", col = "darkred", size=.75) +
  labs(title = "F vs. M Population across all Age Groups", x = "Total Male (log10)", y = "Total Female (log10)") +
  theme_light()

g
</code>```

Which results in this plot: https://share.getcloudapp.com/v1ur6O4e

The problem: I am trying to convert the column AGEGRP from ‘int’ to ‘factor’, and change the factors labels from “1”, “2”, “3”, … “18” to "AgeGroup1", "AgeGroup2", "AgeGroup3", … "AgeGroup18"

When I try this code, my AGEGRP column's observation values are all replaced with NAs:popSample$AGEGRP <- factor(popSample$AGEGRP, levels = c("0 to 4", "5 to 9", "10 to 14", "15 to 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+"))

https://share.getcloudapp.com/qGuo1O4y

Thank you for your help,

答:
Read in the csv again:

```<code>library(tidyverse)

url <- "https://www2.census.gov/programs-surveys/popest/datasets/2010-2018/counties/asrh/cc-est2018-alldata-54.csv"
popSample <- read.csv(url) %>%
filter(AGEGRP != 0 & YEAR == 1) %>%
select("STNAME", "CTYNAME", "AGEGRP", "TOT_POP", "TOT_MALE", "TOT_FEMALE")
</code>```

If you just want to add a prefix "AgeGroup" to your facet labels, you do:

```<code>ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
  geom_point(alpha = 0.5, colour="darkblue") +
  scale_x_log10() +
  scale_y_log10() +
  facet_wrap(~AGEGRP,labeller=labeller(AGEGRP = function(i)paste0("AgeGroup",i))) +
  stat_smooth(method = "lm", col = "darkred", size=.75) +
  labs(title = "F vs. M Population across all Age Groups",
  x = "Total Male (log10)", y = "Total Female (log10)") +
  theme_light()
</code>```

If there is a need for new factors, then you need to refactor (like @Annet's answer below):

```<code>lvls = c("0 to 4", "5 to 9", "10 to 14", "15 to 19",
"20 to 24", "25 to 29", "30 to 34", "35 to 39",
"40 to 44", "45 to 49", "50 to 54", "55 to 59",
 "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+")
#because you have factorize it
# if you can read the csv again, skip the factorization
popSample$AGEGRP = factor(lvls[popSample$AGEGRP],levels=lvls)
</code>```

Then plot:

```<code>ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
      geom_point(alpha = 0.5, colour="darkblue") +
      scale_x_log10() +
      scale_y_log10() +
      facet_wrap(~AGEGRP) +
      stat_smooth(method = "lm", col = "darkred", size=.75) +
      labs(title = "F vs. M Population across all Age Groups",
      x = "Total Male (log10)", y = "Total Female (log10)") +
      theme_light()
</code>```

Title: Renaming labels of a factor in R

Body:
I have census data of Male and Female populations organizaed by age group:

library(tidyverse)

url <- "https://www2.census.gov/programs-surveys/popest/datasets/2010-2018/counties/asrh/cc-est2018-alldata-54.csv"

if (!file.exists("./datafiles/cc-est2018-alldata-54.csv"))
  download.file(url, destfile = "./datafiles/cc-est2018-alldata-54.csv", mode = "wb")

popSample <- read.csv("./datafiles/cc-est2018-alldata-54.csv") %>%
  filter(AGEGRP != 0 & YEAR == 1) %>%
  select("STNAME", "CTYNAME", "AGEGRP", "TOT_POP", "TOT_MALE", "TOT_FEMALE")

popSample$AGEGRP <- as.factor(popSample$AGEGRP)

I then plot the Male and Female population relationships, faceted by age group (1-18, which is currently treated as a int

g <- ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
  geom_point(alpha = 0.5, colour="darkblue") +
  scale_x_log10() +
  scale_y_log10() +
  facet_wrap(~AGEGRP) +
  stat_smooth(method = "lm", col = "darkred", size=.75) +
  labs(title = "F vs. M Population across all Age Groups", x = "Total Male (log10)", y = "Total Female (log10)") +
  theme_light()

g

Which results in this plot: https://share.getcloudapp.com/v1ur6O4e

The problem: I am trying to convert the column AGEGRP from ‘int’ to ‘factor’, and change the factors labels from “1”, “2”, “3”, … “18” to "AgeGroup1", "AgeGroup2", "AgeGroup3", … "AgeGroup18"

When I try this code, my AGEGRP column's observation values are all replaced with NAs:popSample$AGEGRP <- factor(popSample$AGEGRP, levels = c("0 to 4", "5 to 9", "10 to 14", "15 to 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+"))

https://share.getcloudapp.com/qGuo1O4y

Thank you for your help,

Body:
Read in the csv again:

library(tidyverse)

url <- "https://www2.census.gov/programs-surveys/popest/datasets/2010-2018/counties/asrh/cc-est2018-alldata-54.csv"
popSample <- read.csv(url) %>%
filter(AGEGRP != 0 & YEAR == 1) %>%
select("STNAME", "CTYNAME", "AGEGRP", "TOT_POP", "TOT_MALE", "TOT_FEMALE")

If you just want to add a prefix "AgeGroup" to your facet labels, you do:

ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
  geom_point(alpha = 0.5, colour="darkblue") +
  scale_x_log10() +
  scale_y_log10() +
  facet_wrap(~AGEGRP,labeller=labeller(AGEGRP = function(i)paste0("AgeGroup",i))) +
  stat_smooth(method = "lm", col = "darkred", size=.75) +
  labs(title = "F vs. M Population across all Age Groups",
  x = "Total Male (log10)", y = "Total Female (log10)") +
  theme_light()

If there is a need for new factors, then you need to refactor (like @Annet's answer below):

lvls = c("0 to 4", "5 to 9", "10 to 14", "15 to 19",
"20 to 24", "25 to 29", "30 to 34", "35 to 39",
"40 to 44", "45 to 49", "50 to 54", "55 to 59",
 "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+")
#because you have factorize it
# if you can read the csv again, skip the factorization
popSample$AGEGRP = factor(lvls[popSample$AGEGRP],levels=lvls)

Then plot:

ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
      geom_point(alpha = 0.5, colour="darkblue") +
      scale_x_log10() +
      scale_y_log10() +
      facet_wrap(~AGEGRP) +
      stat_smooth(method = "lm", col = "darkred", size=.75) +
      labs(title = "F vs. M Population across all Age Groups",
      x = "Total Male (log10)", y = "Total Female (log10)") +
      theme_light()


问:
Django Filter timestamp data GROUP BY day, week, month, year
I have an django(DRF) app in which I storing periodic timeseries data based on API response. Here is my
model.py

```<code># Model to store the Alexa API Data
class Alexa(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    extra = jsonfield.JSONField(null=True)
    rank =  models.PositiveIntegerField(default=0, null=True)
</code>```

I am using django-filters to query data based on a range (__lte, __gte).
Like /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z return all the data created before 2020-02-14T09:15:52.329641Z

```<code>[
    {
        "id": 1,
        "created_at": "2020-02-03T19:30:57.868588Z",
        "extra": "{'load_time': 00, 'backlink': 0}",
        "rank": 0
    },
    ...
 ]
</code>```

Is there a way to build an endpoint to return aggregated data grouped by day, week, month and year based on the query params I pass. For example,
/api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z&group_by=month would return

```<code>[
    {
        "created_at": "2020-01-01T00:00:00.000000Z",
        "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data
        "rank": 0                                    <- Aggregated Data
    },
    {
        "created_at": "2020-02-01T00:00:00.000000Z",
        "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data
        "rank": 0                                    <- Aggregated Data
    },
 ]
</code>```

Here's my current views.py

```<code>class AlexaViewSet(viewsets.ModelViewSet):
    queryset = Alexa.objects.all()
    filter_fields = {'created_at' : ['iexact', 'lte', 'gte']}
    http_method_names = ['get', 'post', 'head']
</code>```

I have seen several snippets doing aggregation but none completely fulfilling my requirements nor giving me a complete idea about the topic.

I am new to Django and building analytics dashboards in general, if there are any other way of representing such timeseries data for consumption in front-end graphs, I would appreciate your suggestions to that as well.

EDIT :
Here is my serializer.py

```<code>class AlexaSerializer(serializers.ModelSerializer):
     class Meta:
         model = Alexa
         fields = '__all__'
</code>```

答:
First of all, the class AlexaViewSet is not a serializer but a ViewSet. You didn't specify the serializer class on that ViewSet so I you need to specify that.

On the other side, if you want to pass a custom query param on the URL then you should override the list method of this ViewSet and parse the query string passed in the request object to retrieve the value of group_by, validate it, and then perfom the aggregation youself.

Another problem that I see is that you also need to define what is to aggregate a JSON field, which is not supported in SQL and it's very relative, so you may want to consider redesigning how you store the information of this JSON field if you want to perfom aggregations on fields inside it. I would suggest extracting the fields you want to aggregate from the JSON (when storing them in the database) and put them in a SQL column separately so you could perform aggregations later.
The client could also pass the agregation operation as a query parameter, for example aggregation=sum or aggregation=avg.

In a simple case, where you just need the average of the ranks this should be useful as an example (you could add TruncQuarter, etc.):

class AlexaViewSet(viewsets.ModelViewSet):
    serializer_class = AlexaSerializer
    queryset = Alexa.objects.all()
    filter_fields = {'created_at': ['iexact', 'lte', 'gte']}
    http_method_names = ['get', 'post', 'head']

    GROUP_CASTING_MAP = {  # Used for outputing the reset datetime when grouping
        'day': Cast(TruncDate('created_at'), output_field=DateTimeField()),
        'month': Cast(TruncMonth('created_at'), output_field=DateTimeField()),
        'week': Cast(TruncWeek('created_at'), output_field=DateTimeField()),
        'year': Cast(TruncYear('created_at'), output_field=DateTimeField()),
    }

    GROUP_ANNOTATIONS_MAP = {  # Defines the fields used for grouping
        'day': {
            'day': TruncDay('created_at'),
            'month': TruncMonth('created_at'),
            'year': TruncYear('created_at'),
        },
        'week': {
            'week': TruncWeek('created_at')
        },
        'month': {
            'month': TruncMonth('created_at'),
            'year': TruncYear('created_at'),
        },
        'year': {
            'year': TruncYear('created_at'),
        },
    }

    def list(self, request, *args, **kwargs):
        group_by_field = request.GET.get('group_by', None)
        if group_by_field and group_by_field not in self.GROUP_CASTING_MAP.keys():  # validate possible values
            return Response(status=status.HTTP_400_BAD_REQUEST)

        queryset = self.filter_queryset(self.get_queryset())

        if group_by_field:
            queryset = queryset.annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \
                .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \
                .annotate(rank=Avg('rank'), created_at=self.GROUP_CASTING_MAP[group_by_field]) \
                .values('rank', 'created_at')

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
```

<p>For these values:</p>

<pre class="lang-py prettyprint-override"><code>GET /alexa
[
    {
        "id": 1,
        "created_at": "2020-03-16T12:04:59.096098Z",
        "extra": "{}",
        "rank": 2
    },
    {
        "id": 2,
        "created_at": "2020-02-15T12:05:01.907920Z",
        "extra": "{}",
        "rank": 64
    },
    {
        "id": 3,
        "created_at": "2020-02-15T12:05:03.890150Z",
        "extra": "{}",
        "rank": 232
    },
    {
        "id": 4,
        "created_at": "2020-02-15T12:05:06.357748Z",
        "extra": "{}",
        "rank": 12
    }
]
</code>```

GET /alexa/?group_by=day
[
    {
        "created_at": "2020-02-15T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-16T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]
```

<pre class="lang-py prettyprint-override"><code>GET /alexa/?group_by=week
[
    {
        "created_at": "2020-02-10T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-16T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

</code>```

GET /alexa/?group_by=month
[
    {
        "created_at": "2020-02-01T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-01T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]
```

<pre class="lang-py prettyprint-override"><code>GET /alexa/?group_by=year
[
    {
        "created_at": "2020-01-01T00:00:00Z",
        "extra": null,
        "rank": 77
    }
]
</code>```

Body:
I have an django(DRF) app in which I storing periodic timeseries data based on API response. Here is my
model.py

# Model to store the Alexa API Data
class Alexa(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    extra = jsonfield.JSONField(null=True)
    rank =  models.PositiveIntegerField(default=0, null=True)

I am using django-filters to query data based on a range (__lte, __gte).
Like /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z return all the data created before 2020-02-14T09:15:52.329641Z

[
    {
        "id": 1,
        "created_at": "2020-02-03T19:30:57.868588Z",
        "extra": "{'load_time': 00, 'backlink': 0}",
        "rank": 0
    },
    ...
 ]

Is there a way to build an endpoint to return aggregated data grouped by day, week, month and year based on the query params I pass. For example,
/api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z&group_by=month would return

[
    {
        "created_at": "2020-01-01T00:00:00.000000Z",
        "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data
        "rank": 0                                    <- Aggregated Data
    },
    {
        "created_at": "2020-02-01T00:00:00.000000Z",
        "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data
        "rank": 0                                    <- Aggregated Data
    },
 ]

Here's my current views.py

class AlexaViewSet(viewsets.ModelViewSet):
    queryset = Alexa.objects.all()
    filter_fields = {'created_at' : ['iexact', 'lte', 'gte']}
    http_method_names = ['get', 'post', 'head']

I have seen several snippets doing aggregation but none completely fulfilling my requirements nor giving me a complete idea about the topic.

I am new to Django and building analytics dashboards in general, if there are any other way of representing such timeseries data for consumption in front-end graphs, I would appreciate your suggestions to that as well.

EDIT :
Here is my serializer.py

class AlexaSerializer(serializers.ModelSerializer):
     class Meta:
         model = Alexa
         fields = '__all__'

Body:
First of all, the class AlexaViewSet is not a serializer but a ViewSet. You didn't specify the serializer class on that ViewSet so I you need to specify that.

On the other side, if you want to pass a custom query param on the URL then you should override the list method of this ViewSet and parse the query string passed in the request object to retrieve the value of group_by, validate it, and then perfom the aggregation youself.

Another problem that I see is that you also need to define what is to aggregate a JSON field, which is not supported in SQL and it's very relative, so you may want to consider redesigning how you store the information of this JSON field if you want to perfom aggregations on fields inside it. I would suggest extracting the fields you want to aggregate from the JSON (when storing them in the database) and put them in a SQL column separately so you could perform aggregations later.
The client could also pass the agregation operation as a query parameter, for example aggregation=sum or aggregation=avg.

In a simple case, where you just need the average of the ranks this should be useful as an example (you could add TruncQuarter, etc.):

class AlexaViewSet(viewsets.ModelViewSet):
    serializer_class = AlexaSerializer
    queryset = Alexa.objects.all()
    filter_fields = {'created_at': ['iexact', 'lte', 'gte']}
    http_method_names = ['get', 'post', 'head']

    GROUP_CASTING_MAP = {  # Used for outputing the reset datetime when grouping
        'day': Cast(TruncDate('created_at'), output_field=DateTimeField()),
        'month': Cast(TruncMonth('created_at'), output_field=DateTimeField()),
        'week': Cast(TruncWeek('created_at'), output_field=DateTimeField()),
        'year': Cast(TruncYear('created_at'), output_field=DateTimeField()),
    }

    GROUP_ANNOTATIONS_MAP = {  # Defines the fields used for grouping
        'day': {
            'day': TruncDay('created_at'),
            'month': TruncMonth('created_at'),
            'year': TruncYear('created_at'),
        },
        'week': {
            'week': TruncWeek('created_at')
        },
        'month': {
            'month': TruncMonth('created_at'),
            'year': TruncYear('created_at'),
        },
        'year': {
            'year': TruncYear('created_at'),
        },
    }

    def list(self, request, *args, **kwargs):
        group_by_field = request.GET.get('group_by', None)
        if group_by_field and group_by_field not in self.GROUP_CASTING_MAP.keys():  # validate possible values
            return Response(status=status.HTTP_400_BAD_REQUEST)

        queryset = self.filter_queryset(self.get_queryset())

        if group_by_field:
            queryset = queryset.annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \
                .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \
                .annotate(rank=Avg('rank'), created_at=self.GROUP_CASTING_MAP[group_by_field]) \
                .values('rank', 'created_at')

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

For these values:

GET /alexa
[
    {
        "id": 1,
        "created_at": "2020-03-16T12:04:59.096098Z",
        "extra": "{}",
        "rank": 2
    },
    {
        "id": 2,
        "created_at": "2020-02-15T12:05:01.907920Z",
        "extra": "{}",
        "rank": 64
    },
    {
        "id": 3,
        "created_at": "2020-02-15T12:05:03.890150Z",
        "extra": "{}",
        "rank": 232
    },
    {
        "id": 4,
        "created_at": "2020-02-15T12:05:06.357748Z",
        "extra": "{}",
        "rank": 12
    }
]

GET /alexa/?group_by=day
[
    {
        "created_at": "2020-02-15T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-16T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

GET /alexa/?group_by=week
[
    {
        "created_at": "2020-02-10T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-16T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

GET /alexa/?group_by=month
[
    {
        "created_at": "2020-02-01T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-01T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

GET /alexa/?group_by=year
[
    {
        "created_at": "2020-01-01T00:00:00Z",
        "extra": null,
        "rank": 77
    }
]