问:
Heterogeneous Binary Search Tree
I need to build a heterogeneous(Elements with different types) BST and be able to sort the elements but I do not know how to approach the problem.

I've got the binary tree code right here.

```<code>This is the node class

public class Node<T> {
  T data;
  Node<T> left;
  Node<T> right;

  Node(T data) {
    this.data = data;
    left = null;
    right = null;
  }
}
</code>```

And this is the tree class.

```<code>public class Tree<T extends Comparable<T>> {
  private Node<T> root;
  StringBuilder result = new StringBuilder();

  public Tree() {
    root = null;
  }

  public Node<T> getRoot() {
    return root;
  }

  /**
   * Method that inserts nodes into the binary tree. If the tree is empty , a new root node is
   * initialized.
   *
   * @param root A node object.
   * @param dataBeingInserted The object to be inserted on the tree.
   * @return The root node object
   */
  private Node<T> insertNode(Node<T> root, T dataBeingInserted) {
    if (root == null) {
      root = new Node<>(dataBeingInserted);
      return root;
    }

    if (dataBeingInserted.compareTo(root.data) < 0) {
      root.left = insertNode(root.left, dataBeingInserted);
    } else if (dataBeingInserted.compareTo(root.data) > 0) {
      root.right = insertNode(root.right, dataBeingInserted);
    }
    return root;
  }

  public void insertNode(T dataBeingInserted) {
    root = insertNode(root, dataBeingInserted);
  }

  /**
   * Method that recursively searches for our element through the tree. If the value is present in
   * the root node , or there aren't any nodes in the tree , the method returns the root node. If
   * the value we're looking for is smaller than the root node's value , we search for our value in
   * the left subtree , otherwise we search for it in the right subtree.
   *
   * @param root A node object.
   * @param dataBeingSearched User's value.
   * @return Recursive call of the method.
   */
  private Node<T> searchTree(Node<T> root, T dataBeingSearched) {
    if (root == null || dataBeingSearched.compareTo(root.data) == 0) {
      return root;
    }
    if ((dataBeingSearched.compareTo(root.data) > 0)) {
      return searchTree(root.left, dataBeingSearched);
    }
    return searchTree(root.right, dataBeingSearched);
  }

  public Node searchTree(T dataBeingSearched) {
    return searchTree(root, dataBeingSearched);
  }

  /**
   * An implementation of the In-order traversal. First the left subtree is visited and printed
   * accordingly, then we visit and print the root and after that we visit and print the right
   * subtree.
   *
   * @param root The root node object.
   */
  private String inorderTraversal(Node root) {
    if (root == null) {
      return "";
    }
    inorderTraversal(root.left);
    result.append(root.data).append(" ");
    inorderTraversal(root.right);

    return result.toString();
  }

  public void inorderTraversal() {
    inorderTraversal(root);
  }

}
</code>```

The problem with my tree right now is that I'm getting ClassCastException whenever any element is different than the root , because there what happens is the root defines the type of the tree and I can't fix that.

P.S
Here is the snippet that gives me the error (I will post the whole main method for convenience.)

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

public class Main {
  private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
  private static final Scanner SCANNER = new Scanner(System.in);

  public static void main(String[] args) {
    Tree tree = new Tree<>();
    tree.insertNode(50);
    tree.insertNode("30");
    tree.insertNode('b');
    tree.insertNode(69.3);
    tree.inorderTraversal();
    LOGGER.info("{}", tree.result);
  }
}
</code>```

For example there the first insert is an Integer , after which I try to insert a String and right there it's giving me the ClassCastException , saying that String is incomparable with Integer.

答:
I had a similar task in my java course. I used generics to define the tree. Then I created a tree of an interface, which is implemented by every node. The methods of the interface are then implemented in every node and this allowed me to compare and sort the objects. There is a simple example in this topic: simple heterogeneous k-ary tree in java (for creating network simulator)

I thought of the problem as of the products in a grocery store. Every product has id, brand, name, price but depending of the type of product they have to be cooled or have "best before" or need to be frozen or are not edible.

Title: Heterogeneous Binary Search Tree

Body:
I need to build a heterogeneous(Elements with different types) BST and be able to sort the elements but I do not know how to approach the problem.

I've got the binary tree code right here.

This is the node class

public class Node<T> {
  T data;
  Node<T> left;
  Node<T> right;

  Node(T data) {
    this.data = data;
    left = null;
    right = null;
  }
}

And this is the tree class.

public class Tree<T extends Comparable<T>> {
  private Node<T> root;
  StringBuilder result = new StringBuilder();

  public Tree() {
    root = null;
  }

  public Node<T> getRoot() {
    return root;
  }

  /**
   * Method that inserts nodes into the binary tree. If the tree is empty , a new root node is
   * initialized.
   *
   * @param root A node object.
   * @param dataBeingInserted The object to be inserted on the tree.
   * @return The root node object
   */
  private Node<T> insertNode(Node<T> root, T dataBeingInserted) {
    if (root == null) {
      root = new Node<>(dataBeingInserted);
      return root;
    }

    if (dataBeingInserted.compareTo(root.data) < 0) {
      root.left = insertNode(root.left, dataBeingInserted);
    } else if (dataBeingInserted.compareTo(root.data) > 0) {
      root.right = insertNode(root.right, dataBeingInserted);
    }
    return root;
  }

  public void insertNode(T dataBeingInserted) {
    root = insertNode(root, dataBeingInserted);
  }

  /**
   * Method that recursively searches for our element through the tree. If the value is present in
   * the root node , or there aren't any nodes in the tree , the method returns the root node. If
   * the value we're looking for is smaller than the root node's value , we search for our value in
   * the left subtree , otherwise we search for it in the right subtree.
   *
   * @param root A node object.
   * @param dataBeingSearched User's value.
   * @return Recursive call of the method.
   */
  private Node<T> searchTree(Node<T> root, T dataBeingSearched) {
    if (root == null || dataBeingSearched.compareTo(root.data) == 0) {
      return root;
    }
    if ((dataBeingSearched.compareTo(root.data) > 0)) {
      return searchTree(root.left, dataBeingSearched);
    }
    return searchTree(root.right, dataBeingSearched);
  }

  public Node searchTree(T dataBeingSearched) {
    return searchTree(root, dataBeingSearched);
  }

  /**
   * An implementation of the In-order traversal. First the left subtree is visited and printed
   * accordingly, then we visit and print the root and after that we visit and print the right
   * subtree.
   *
   * @param root The root node object.
   */
  private String inorderTraversal(Node root) {
    if (root == null) {
      return "";
    }
    inorderTraversal(root.left);
    result.append(root.data).append(" ");
    inorderTraversal(root.right);

    return result.toString();
  }

  public void inorderTraversal() {
    inorderTraversal(root);
  }

}

The problem with my tree right now is that I'm getting ClassCastException whenever any element is different than the root , because there what happens is the root defines the type of the tree and I can't fix that.

P.S
Here is the snippet that gives me the error (I will post the whole main method for convenience.)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

public class Main {
  private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
  private static final Scanner SCANNER = new Scanner(System.in);

  public static void main(String[] args) {
    Tree tree = new Tree<>();
    tree.insertNode(50);
    tree.insertNode("30");
    tree.insertNode('b');
    tree.insertNode(69.3);
    tree.inorderTraversal();
    LOGGER.info("{}", tree.result);
  }
}

For example there the first insert is an Integer , after which I try to insert a String and right there it's giving me the ClassCastException , saying that String is incomparable with Integer.


来源: stackexchange

问:
Is django prefetch_related supposed to work with GenericRelation
UPDATE 2022: The original ticked #24272 which I opened 8 years ago about this issue is now closed in favor of #33651, which once implemented will give us a new syntax to do this type of prefetches.

============== END OF UPDATE ==============

What's all about?

Django has a GenericRelation class, which adds a “reverse” generic relationship to enable an additional API.

It turns out we can use this reverse-generic-relation for filtering or ordering, but we can't use it inside prefetch_related.

I was wondering if this is a bug, or its not supposed to work, or its something that can be implemented in the feature.

Let me show you with some examples what I mean.

Lets say we have two main models: Movies and Books.

Movies have a Director

Books have an Author

And we want to assign tags to our Movies and Books, but instead of using MovieTag and BookTag models, we want to use a single TaggedItem class with a GFK to Movie or Book.

Here is the model structure:

```<code>from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.tag

class Director(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class Movie(models.Model):
    name = models.CharField(max_length=100)
    director = models.ForeignKey(Director)
    tags = GenericRelation(TaggedItem, related_query_name='movies')

    def __unicode__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Author)
    tags = GenericRelation(TaggedItem, related_query_name='books')

    def __unicode__(self):
        return self.name
</code>```

And some initial data:

```<code>>>> from tags.models import Book, Movie, Author, Director, TaggedItem
>>> a = Author.objects.create(name='E L James')
>>> b1 = Book.objects.create(name='Fifty Shades of Grey', author=a)
>>> b2 = Book.objects.create(name='Fifty Shades Darker', author=a)
>>> b3 = Book.objects.create(name='Fifty Shades Freed', author=a)
>>> d = Director.objects.create(name='James Gunn')
>>> m1 = Movie.objects.create(name='Guardians of the Galaxy', director=d)
>>> t1 = TaggedItem.objects.create(content_object=b1, tag='roman')
>>> t2 = TaggedItem.objects.create(content_object=b2, tag='roman')
>>> t3 = TaggedItem.objects.create(content_object=b3, tag='roman')
>>> t4 = TaggedItem.objects.create(content_object=m1, tag='action movie')
</code>```

So as the docs show we can do stuff like this.

```<code>>>> b1.tags.all()
[<TaggedItem: roman>]
>>> m1.tags.all()
[<TaggedItem: action movie>]
>>> TaggedItem.objects.filter(books__author__name='E L James')
[<TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: roman>]
>>> TaggedItem.objects.filter(movies__director__name='James Gunn')
[<TaggedItem: action movie>]
>>> Book.objects.all().prefetch_related('tags')
[<Book: Fifty Shades of Grey>, <Book: Fifty Shades Darker>, <Book: Fifty Shades Freed>]
>>> Book.objects.filter(tags__tag='roman')
[<Book: Fifty Shades of Grey>, <Book: Fifty Shades Darker>, <Book: Fifty Shades Freed>]
</code>```

But, if we try to prefetch some related data of TaggedItem via this reverse generic relation, we are going to get an AttributeError.

```<code>>>> TaggedItem.objects.all().prefetch_related('books')
Traceback (most recent call last):
  ...
AttributeError: 'Book' object has no attribute 'object_id'
</code>```

Some of you may ask, why I just don't use content_object instead of books here? The reason is, because this only work when we want to:

prefetch only one level deep from querysets containing different type of content_object.

```<code>>>> TaggedItem.objects.all().prefetch_related('content_object')
[<TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: action movie>]
</code>```

prefetch many levels but from querysets containing only one type of content_object.

```<code>>>> TaggedItem.objects.filter(books__author__name='E L James').prefetch_related('content_object__author')
[<TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: roman>]
</code>```

But, if we want both 1) and 2) (to prefetch many levels from queryset containing different types of content_objects, we can't use content_object.

```<code>>>> TaggedItem.objects.all().prefetch_related('content_object__author')
Traceback (most recent call last):
  ...
AttributeError: 'Movie' object has no attribute 'author_id'
</code>```

Django thinks that all content_objects are Books, and thus they have an Author.

Now imagine the situation where we want to prefetch not only the books with their author, but also the movies with their director. Here are few attempts.

The silly way:

```<code>>>> TaggedItem.objects.all().prefetch_related(
...     'content_object__author',
...     'content_object__director',
... )
Traceback (most recent call last):
  ...
AttributeError: 'Movie' object has no attribute 'author_id'
</code>```

Maybe with custom Prefetch object?

```<code>>>> TaggedItem.objects.all().prefetch_related(
...     Prefetch('content_object', queryset=Book.objects.all().select_related('author')),
...     Prefetch('content_object', queryset=Movie.objects.all().select_related('director')),
... )
Traceback (most recent call last):
  ...
ValueError: Custom queryset can't be used for this lookup.
</code>```

Some solutions of this problem are shown here. But that's a lot of massage over the data which I want to avoid.
I really like the API coming from the reversed generic relations, it would be very nice to be able to do prefetchs like that:

```<code>>>> TaggedItem.objects.all().prefetch_related(
...     'books__author',
...     'movies__director',
... )
Traceback (most recent call last):
  ...
AttributeError: 'Book' object has no attribute 'object_id'
</code>```

Or like that:

```<code>>>> from tags.models import Book, Movie, Author, Director, TaggedItem
>>> a = Author.objects.create(name='E L James')
>>> b1 = Book.objects.create(name='Fifty Shades of Grey', author=a)
>>> b2 = Book.objects.create(name='Fifty Shades Darker', author=a)
>>> b3 = Book.objects.create(name='Fifty Shades Freed', author=a)
>>> d = Director.objects.create(name='James Gunn')
>>> m1 = Movie.objects.create(name='Guardians of the Galaxy', director=d)
>>> t1 = TaggedItem.objects.create(content_object=b1, tag='roman')
>>> t2 = TaggedItem.objects.create(content_object=b2, tag='roman')
>>> t3 = TaggedItem.objects.create(content_object=b3, tag='roman')
>>> t4 = TaggedItem.objects.create(content_object=m1, tag='action movie')
</code>```0

But as you can see, we aways get that AttributeError.
I'm using Django 1.7.3 and Python 2.7.6. And i'm curious why Django is throwing that error? Why is Django searching for an object_id in the Book model?
Why I think this may be a bug?
Usually when we ask prefetch_related to resolve something it can't, we see:

```<code>>>> from tags.models import Book, Movie, Author, Director, TaggedItem
>>> a = Author.objects.create(name='E L James')
>>> b1 = Book.objects.create(name='Fifty Shades of Grey', author=a)
>>> b2 = Book.objects.create(name='Fifty Shades Darker', author=a)
>>> b3 = Book.objects.create(name='Fifty Shades Freed', author=a)
>>> d = Director.objects.create(name='James Gunn')
>>> m1 = Movie.objects.create(name='Guardians of the Galaxy', director=d)
>>> t1 = TaggedItem.objects.create(content_object=b1, tag='roman')
>>> t2 = TaggedItem.objects.create(content_object=b2, tag='roman')
>>> t3 = TaggedItem.objects.create(content_object=b3, tag='roman')
>>> t4 = TaggedItem.objects.create(content_object=m1, tag='action movie')
</code>```1

But here, it is different. Django actually tries to resolve the relation... and fails. Is this a bug which should be reported? I have never reported anything to Django so that's why I'm asking here first. I'm unable to trace the error and decide for myself if this is a bug, or a feature which could be implemented.

答:
Building on Bernhard's answer, which has a code-snippet at the end that throws the below error in reality:

```<code>ValueError: Custom queryset can't be used for this lookup.
</code>```

I've overridden the GenericForeignKey to actually allow the behavior, how bulletproof this implementation is, is unknown to me at this time but it seems to get what I need done, so I'm posting it here, hopefully it'll help out others. Please lookout for START CHANGES and END CHANGES tags to see my changes to the original django code.

```<code>from django.contrib.contenttypes.fields import GenericForeignKey as BaseGenericForeignKey

class CustomGenericForeignKey(BaseGenericForeignKey):
    def get_prefetch_queryset(self, instances, queryset=None):
        """
        Enable passing queryset to get_prefetch_queryset when using GenericForeignKeys but only works when a single
        content type is being queried
        """
        # START CHANGES
        # if queryset is not None:
        #     raise ValueError("Custom queryset can't be used for this lookup.")
        # END CHANGES

        # For efficiency, group the instances by content type and then do one
        # query per model
        fk_dict = defaultdict(set)
        # We need one instance for each group in order to get the right db:
        instance_dict = {}
        ct_attname = self.model._meta.get_field(self.ct_field).get_attname()
        for instance in instances:
            # We avoid looking for values if either ct_id or fkey value is None
            ct_id = getattr(instance, ct_attname)
            if ct_id is not None:
                fk_val = getattr(instance, self.fk_field)
                if fk_val is not None:
                    fk_dict[ct_id].add(fk_val)
                    instance_dict[ct_id] = instance

        ret_val = []
        for ct_id, fkeys in fk_dict.items():
            instance = instance_dict[ct_id]
            # START CHANGES
            if queryset is not None:
                assert len(fk_dict) == 1  # only a single content type is allowed, else undefined behavior
                ret_val.extend(queryset.filter(pk__in=fkeys))
            else:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys))
            # END CHANGES

        # For doing the join in Python, we have to match both the FK val and the
        # content type, so we use a callable that returns a (fk, class) pair.
        def gfk_key(obj):
            ct_id = getattr(obj, ct_attname)
            if ct_id is None:
                return None
            else:
                model = self.get_content_type(id=ct_id,
                                              using=obj._state.db).model_class()
                return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),
                        model)

        return (
            ret_val,
            lambda obj: (obj.pk, obj.__class__),
            gfk_key,
            True,
            self.name,
            True,
        )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
UPDATE 2022: The original ticked #24272 which I opened 8 years ago about this issue is now closed in favor of #33651, which once implemented will give us a new syntax to do this type of prefetches.

============== END OF UPDATE ==============

What's all about?

Django has a GenericRelation class, which adds a “reverse” generic relationship to enable an additional API.

It turns out we can use this reverse-generic-relation for filtering or ordering, but we can't use it inside prefetch_related.

I was wondering if this is a bug, or its not supposed to work, or its something that can be implemented in the feature.

Let me show you with some examples what I mean.

Lets say we have two main models: Movies and Books.

Movies have a Director

Books have an Author

And we want to assign tags to our Movies and Books, but instead of using MovieTag and BookTag models, we want to use a single TaggedItem class with a GFK to Movie or Book.

Here is the model structure:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.tag

class Director(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class Movie(models.Model):
    name = models.CharField(max_length=100)
    director = models.ForeignKey(Director)
    tags = GenericRelation(TaggedItem, related_query_name='movies')

    def __unicode__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Author)
    tags = GenericRelation(TaggedItem, related_query_name='books')

    def __unicode__(self):
        return self.name

And some initial data:

>>> from tags.models import Book, Movie, Author, Director, TaggedItem
>>> a = Author.objects.create(name='E L James')
>>> b1 = Book.objects.create(name='Fifty Shades of Grey', author=a)
>>> b2 = Book.objects.create(name='Fifty Shades Darker', author=a)
>>> b3 = Book.objects.create(name='Fifty Shades Freed', author=a)
>>> d = Director.objects.create(name='James Gunn')
>>> m1 = Movie.objects.create(name='Guardians of the Galaxy', director=d)
>>> t1 = TaggedItem.objects.create(content_object=b1, tag='roman')
>>> t2 = TaggedItem.objects.create(content_object=b2, tag='roman')
>>> t3 = TaggedItem.objects.create(content_object=b3, tag='roman')
>>> t4 = TaggedItem.objects.create(content_object=m1, tag='action movie')

So as the docs show we can do stuff like this.

>>> b1.tags.all()
[<TaggedItem: roman>]
>>> m1.tags.all()
[<TaggedItem: action movie>]
>>> TaggedItem.objects.filter(books__author__name='E L James')
[<TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: roman>]
>>> TaggedItem.objects.filter(movies__director__name='James Gunn')
[<TaggedItem: action movie>]
>>> Book.objects.all().prefetch_related('tags')
[<Book: Fifty Shades of Grey>, <Book: Fifty Shades Darker>, <Book: Fifty Shades Freed>]
>>> Book.objects.filter(tags__tag='roman')
[<Book: Fifty Shades of Grey>, <Book: Fifty Shades Darker>, <Book: Fifty Shades Freed>]

But, if we try to prefetch some related data of TaggedItem via this reverse generic relation, we are going to get an AttributeError.

>>> TaggedItem.objects.all().prefetch_related('books')
Traceback (most recent call last):
  ...
AttributeError: 'Book' object has no attribute 'object_id'

Some of you may ask, why I just don't use content_object instead of books here? The reason is, because this only work when we want to:

prefetch only one level deep from querysets containing different type of content_object.

>>> TaggedItem.objects.all().prefetch_related('content_object')
[<TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: action movie>]

prefetch many levels but from querysets containing only one type of content_object.

>>> TaggedItem.objects.filter(books__author__name='E L James').prefetch_related('content_object__author')
[<TaggedItem: roman>, <TaggedItem: roman>, <TaggedItem: roman>]

But, if we want both 1) and 2) (to prefetch many levels from queryset containing different types of content_objects, we can't use content_object.

>>> TaggedItem.objects.all().prefetch_related('content_object__author')
Traceback (most recent call last):
  ...
AttributeError: 'Movie' object has no attribute 'author_id'

Django thinks that all content_objects are Books, and thus they have an Author.

Now imagine the situation where we want to prefetch not only the books with their author, but also the movies with their director. Here are few attempts.

The silly way:

>>> TaggedItem.objects.all().prefetch_related(
...     'content_object__author',
...     'content_object__director',
... )
Traceback (most recent call last):
  ...
AttributeError: 'Movie' object has no attribute 'author_id'

Maybe with custom Prefetch object?

>>> TaggedItem.objects.all().prefetch_related(
...     Prefetch('content_object', queryset=Book.objects.all().select_related('author')),
...     Prefetch('content_object', queryset=Movie.objects.all().select_related('director')),
... )
Traceback (most recent call last):
  ...
ValueError: Custom queryset can't be used for this lookup.

Some solutions of this problem are shown here. But that's a lot of massage over the data which I want to avoid.
I really like the API coming from the reversed generic relations, it would be very nice to be able to do prefetchs like that:

>>> TaggedItem.objects.all().prefetch_related(
...     'books__author',
...     'movies__director',
... )
Traceback (most recent call last):
  ...
AttributeError: 'Book' object has no attribute 'object_id'

Or like that:

>>> TaggedItem.objects.all().prefetch_related(
...     Prefetch('books', queryset=Book.objects.all().select_related('author')),
...     Prefetch('movies', queryset=Movie.objects.all().select_related('director')),
... )
Traceback (most recent call last):
  ...
AttributeError: 'Book' object has no attribute 'object_id'

But as you can see, we aways get that AttributeError.
I'm using Django 1.7.3 and Python 2.7.6. And i'm curious why Django is throwing that error? Why is Django searching for an object_id in the Book model?
Why I think this may be a bug?
Usually when we ask prefetch_related to resolve something it can't, we see:

>>> TaggedItem.objects.all().prefetch_related('some_field')
Traceback (most recent call last):
  ...
AttributeError: Cannot find 'some_field' on TaggedItem object, 'some_field' is an invalid parameter to prefetch_related()

But here, it is different. Django actually tries to resolve the relation... and fails. Is this a bug which should be reported? I have never reported anything to Django so that's why I'm asking here first. I'm unable to trace the error and decide for myself if this is a bug, or a feature which could be implemented.

Body:
Building on Bernhard's answer, which has a code-snippet at the end that throws the below error in reality:

ValueError: Custom queryset can't be used for this lookup.

I've overridden the GenericForeignKey to actually allow the behavior, how bulletproof this implementation is, is unknown to me at this time but it seems to get what I need done, so I'm posting it here, hopefully it'll help out others. Please lookout for START CHANGES and END CHANGES tags to see my changes to the original django code.

from django.contrib.contenttypes.fields import GenericForeignKey as BaseGenericForeignKey

class CustomGenericForeignKey(BaseGenericForeignKey):
    def get_prefetch_queryset(self, instances, queryset=None):
        """
        Enable passing queryset to get_prefetch_queryset when using GenericForeignKeys but only works when a single
        content type is being queried
        """
        # START CHANGES
        # if queryset is not None:
        #     raise ValueError("Custom queryset can't be used for this lookup.")
        # END CHANGES

        # For efficiency, group the instances by content type and then do one
        # query per model
        fk_dict = defaultdict(set)
        # We need one instance for each group in order to get the right db:
        instance_dict = {}
        ct_attname = self.model._meta.get_field(self.ct_field).get_attname()
        for instance in instances:
            # We avoid looking for values if either ct_id or fkey value is None
            ct_id = getattr(instance, ct_attname)
            if ct_id is not None:
                fk_val = getattr(instance, self.fk_field)
                if fk_val is not None:
                    fk_dict[ct_id].add(fk_val)
                    instance_dict[ct_id] = instance

        ret_val = []
        for ct_id, fkeys in fk_dict.items():
            instance = instance_dict[ct_id]
            # START CHANGES
            if queryset is not None:
                assert len(fk_dict) == 1  # only a single content type is allowed, else undefined behavior
                ret_val.extend(queryset.filter(pk__in=fkeys))
            else:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                ret_val.extend(ct.get_all_objects_for_this_type(pk__in=fkeys))
            # END CHANGES

        # For doing the join in Python, we have to match both the FK val and the
        # content type, so we use a callable that returns a (fk, class) pair.
        def gfk_key(obj):
            ct_id = getattr(obj, ct_attname)
            if ct_id is None:
                return None
            else:
                model = self.get_content_type(id=ct_id,
                                              using=obj._state.db).model_class()
                return (model._meta.pk.get_prep_value(getattr(obj, self.fk_field)),
                        model)

        return (
            ret_val,
            lambda obj: (obj.pk, obj.__class__),
            gfk_key,
            True,
            self.name,
            True,
        )


问:
XSLT value-of returns text only
I'm using XSLT to show a node from XML. This node contains a HTML unordered list like this:

one

two

but <xsl:value-of select="root/node1" disable-output-escaping="yes" /> returns only onetwo

I know i need to use disable-output-escaping="yes" But this does nothing.

I want the output to be the same as in the node, like this:

one

two

答:
xsl:value-of is used to create text nodes by evaluating the string-value of the selected node.

You need to use xsl:copy-of.

http://www.w3.org/TR/xslt#value-of

The xsl:value-of element is instantiated to create a text node
  in the result tree. The required select attribute is an expression;
  this expression is evaluated and the resulting object is converted
  to a string as if by a call to the string function. The string
  specifies the string-value of the created text node. If the string is
  empty, no text node will be created. The created text node will be
  merged with any adjacent text nodes.

The xsl:copy-of element can be used to copy a node-set over to the
  result tree without converting it to a string. See [11.3 Using Values
  of Variables and Parameters with xsl:copy-of].

ContentLicense: CC BY-SA 3.0

Title: XSLT value-of returns text only


问:
Is there a possibility to add OMR codes to Oracle Reports
Is there any way to add OMR codes for letter inserters onto an Oracle Report?

Dirty tricks or not, any ideas are welcome. So far I was thinking of either drawing the lines and hiding/showing them depending on the page. Either that or creating 16 different images (8 combinations for start and end) -> Explanation: The top 2 represent start and stop, the bottom represents a binary sequence going from bottom to top.

Here is the desired result:

答:
When I was developing such a report (boy, it was ... 15 years ago, I don't remember details any more), I created separate lines. Each of them had its own Format trigger which returned TRUE (if that line had to be displayed) or FALSE (if not), based on a function result.

If I remember well,

the 1st line was always displayed

the 2nd line represented beginning of "data set" (e.g. 3 papers had to be put into the same envelope, so the 1st of these 3 pages had that line displayed)

the 3rd line represented end of "data set" (as above; that line was displayed on the 3rd page of that set, which means that these 3 papers were put into the same envelope)

the next 3 lines were "counters" (binary, of course):

no lines = 0

only the 1st line = 1

only the 2nd line = 2

the 1st and the 2nd line = 3
etc.

You're having more "counter" lines than I did, but it doesn't matter, the principle is the same.

It worked on both Neopost and Pitney-Bowes machines.

P.S. Did you hug your backup today? I just did - found the report that dates back in August 2007. Here's a screenshot which illustrates what I was trying to describe:


问:
Xamarin Android Accessibility - how can we set accessibility focus to a UI element like a button programatically
In my Xamarin Android application user needs to select an item from a spinner (dropdown menu). After selecting any item from the spinner the accessibility focus shifts to the start of the screen instead of the next focusable element, which is not the expected behavior.
So trying to find a way to set focus to the button programmatically but it seems there is no way in Xamarin Android.

I have tried

```<code>Button1.RequestFocus();

Button1.RequestFocusFromTouch();

Button1.SendAccessibilityEvent(EventTypes.ViewAccessibilityFocused);
</code>```

But nothing works!!

The below code example is related to Xamarin iOS:

```<code>    UIAccessibility.PostNotification(UIAccessibilityPostNotification.ScreenChanged, myFirstElement);
</code>```

This method which is available in Xamarin iOS works fine so need a similar way for Xamarin Android to focus programmatically.

Here, I am posting sample code.

My .axml file code:

```<code><?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"   android:focusable="true"    android:focusableInTouchMode="true"/>
    <Button
        android:text="Add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnAdd"
        android:focusable="true"
        android:focusableInTouchMode="true"/>
</LinearLayout> </LinearLayout>
</code>```

My Activity file

```<code>protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        this.SetContentView (Resource.Layout.Main);
Spinner spinner = this.FindViewById<Spinner>(Resource.Id.spinner);
        Button btnAdd = this.FindViewById<Button>(Resource.Id.btnAdd);
var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.planets_array, Android.Resource.Layout.SimpleSpinnerItem);

            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;
            btnAdd.Click += (s, e) =>
              {
                  string toasts = string.Format("Add button got focus");
                  Toast.MakeText(this, toasts, ToastLength.Long).Show();
              };

        }

        private void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;

            string toast = string.Format("The planet is {0}", spinner.GetItemAtPosition(e.Position));
            Toast.MakeText(this, toast, ToastLength.Long).Show();
            //btnAdd.RequestFocus();
            btnAdd.RequestFocusFromTouch();
            btnAdd.RequestFocus();
            if (btnAdd.IsFocused)
            {
                string toasts = string.Format("Add button got focus");
                Toast.MakeText(this, toasts, ToastLength.Long).Show();
            }
            skillSeleted = "selected";
        }

        protected override void OnResume()
        {
            base.OnResume();
            if (skillSeleted == "selected")
            {
                btnAdd.RequestFocusFromTouch();
                btnAdd.RequestFocus();
            }
        }

//Add this to String file under values folder:
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</code>```

Please check this scenario in Samsung Mobile with Marshmallow android version.

Thanks in advance.

答:
```<code>public class MainPage : ContentPage {
    public MainPage() => Content = BuildView().CreateView();

    void SetState() => BuildView().Apply(Content);

    int _counter;

    Command _push => new Command(() => {
        _counter++;
        SetState();
    });

    ViewModel BuildView() =>
        new StackLayoutModel(
            children: new ViewModel[] {
                new LabelModel(text: _counter.ToString(), fontSize: 42),
                new ButtonModel(text: "Increment", command: _push),
            },
            padding: new Thickness(42));
}
</code>```

Body:
In my Xamarin Android application user needs to select an item from a spinner (dropdown menu). After selecting any item from the spinner the accessibility focus shifts to the start of the screen instead of the next focusable element, which is not the expected behavior.
So trying to find a way to set focus to the button programmatically but it seems there is no way in Xamarin Android.

I have tried

Button1.RequestFocus();

Button1.RequestFocusFromTouch();

Button1.SendAccessibilityEvent(EventTypes.ViewAccessibilityFocused);

But nothing works!!

The below code example is related to Xamarin iOS:

    UIAccessibility.PostNotification(UIAccessibilityPostNotification.ScreenChanged, myFirstElement);

This method which is available in Xamarin iOS works fine so need a similar way for Xamarin Android to focus programmatically.

Here, I am posting sample code.

My .axml file code:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"   android:focusable="true"    android:focusableInTouchMode="true"/>
    <Button
        android:text="Add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnAdd"
        android:focusable="true"
        android:focusableInTouchMode="true"/>
</LinearLayout> </LinearLayout>

My Activity file

protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        this.SetContentView (Resource.Layout.Main);
Spinner spinner = this.FindViewById<Spinner>(Resource.Id.spinner);
        Button btnAdd = this.FindViewById<Button>(Resource.Id.btnAdd);
var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.planets_array, Android.Resource.Layout.SimpleSpinnerItem);

            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;
            btnAdd.Click += (s, e) =>
              {
                  string toasts = string.Format("Add button got focus");
                  Toast.MakeText(this, toasts, ToastLength.Long).Show();
              };

        }

        private void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;

            string toast = string.Format("The planet is {0}", spinner.GetItemAtPosition(e.Position));
            Toast.MakeText(this, toast, ToastLength.Long).Show();
            //btnAdd.RequestFocus();
            btnAdd.RequestFocusFromTouch();
            btnAdd.RequestFocus();
            if (btnAdd.IsFocused)
            {
                string toasts = string.Format("Add button got focus");
                Toast.MakeText(this, toasts, ToastLength.Long).Show();
            }
            skillSeleted = "selected";
        }

        protected override void OnResume()
        {
            base.OnResume();
            if (skillSeleted == "selected")
            {
                btnAdd.RequestFocusFromTouch();
                btnAdd.RequestFocus();
            }
        }

//Add this to String file under values folder:
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>

Please check this scenario in Samsung Mobile with Marshmallow android version.

Thanks in advance.


问:
Monitoring Multiple Directories For Adding / Removing Files in Node.js
I need to monitor cross-platform if some files are created/removed from certain directories.

I've tried to use fs.watch:

```<code>let dirs = ['/tmp', '/home/user', './some-dir']

dirs.forEach(function(dir) {
   fs.watch(dir, (evt, filename) => {
      if (filename && evt === "rename") {
        console.log(evt, dir, filename)
      }
   })
})
</code>```

Above code will keep returning latest directory in the array. In the same time, the file was added/removed from the random directory. The behavior of returning latest directory name in forEach cycle is logical. So the question is how can I get correct directory name?

There are some nice third-party modules around such as https://www.npmjs.com/package/chokidar But it has lots of dependencies, so I'm trying to keep up with native Node solution for now.

答: There is a package Chokidar for the NodeJS, which is actually a business standard. Chokidar is a cross-platform solution that works well not only under Linux.</p>

Body:
I need to monitor cross-platform if some files are created/removed from certain directories.

I've tried to use fs.watch:

let dirs = ['/tmp', '/home/user', './some-dir']

dirs.forEach(function(dir) {
   fs.watch(dir, (evt, filename) => {
      if (filename && evt === "rename") {
        console.log(evt, dir, filename)
      }
   })
})

Above code will keep returning latest directory in the array. In the same time, the file was added/removed from the random directory. The behavior of returning latest directory name in forEach cycle is logical. So the question is how can I get correct directory name?

There are some nice third-party modules around such as https://www.npmjs.com/package/chokidar But it has lots of dependencies, so I'm trying to keep up with native Node solution for now.


问:
Android-12 - BLE only returns status 0 in onConnectionStateChange Callback
I am facing one issue related to BLE’s behavior in our application. In Android 11 and below, On Ble disconnection, we used to get different status codes in onConnectionStateChange callback like status 8 is for out range, 19 is peripheral disconnection etc and For programmatic disconnection, it was returning 0.

However starting from Android 12 the BLE API is always returning 0 regardless of it is programmatic disconnection or due to any other reason.

In our application, we are performing some operations based on if the disconnection was unexpected(Out of range, peripheral initiated, etc) or it was programmatic. Now there is no way to distinguish the difference for BLE disconnection reason on Android 12 devices. And this creates issues in our application.

Has anyone faced this issue with BLE’s behavior in your application running on an android 12 devices and found any solution for it?

Also, This change in android 12 is not mentioned anywhere in the android developer’s documentation.

Here is the callback which i am using to get connection status change : https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt,%20int,%20int)

答:
I also find it very annoying.
The question is also asked here (Android 12 BLE always returning status 0 on disconnect) and gives a little more context.</p>


问:
OpenHTMLToPDF: Embed a custom font into PDF created out of HTML
I create a PDF from HTML with Jsoup and OpenHTMLToPDF. I have to use a different font in my PDF to have non-latin glyphcs covered (see here). How can I embed my font correctly?

Simplified program reproducing the issue:

src/main/resources/test.html

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Font Test</title>
        <style>
            @font-face {
                font-family: 'source-sans';
                font-style: normal;
                font-weight: 400;
                src: url(fonts/SourceSansPro-Regular.ttf);
            }
        </style>
    </head>
    <body>
        <p style="font-family: 'source-sans',serif">Latin Script</p>
        <p style="font-family: 'source-sans',serif">Είμαι ελληνικό κείμενο.</p>
    </body>
</html>
</code>```

this file shall be written as PDF

In a browser it looks correctly and uses the Source Sans font.

src/main/java/main.java:

```<code>import com.openhtmltopdf.extend.FSSupplier;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.w3c.dom.Document;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class main {
    public static void main(String[] args) {
        System.out.println("Starting");

        try {

            final W3CDom w3cDom = new W3CDom();
            final Document w3cDoc = w3cDom.fromJsoup(Jsoup.parse(readFile()));
            final OutputStream outStream = new FileOutputStream("test.pdf");

            final PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();
            pdfBuilder.useFastMode();
            pdfBuilder.withW3cDocument(w3cDoc, "/");
            pdfBuilder.useFont(new File(main.class.getClassLoader().getResource("fonts/SourceSansPro-Regular.ttf").getFile()), "source-sans");
            pdfBuilder.toStream(outStream);

            pdfBuilder.run();
            outStream.close();

        } catch (Exception e) {
            System.out.println("PDF could not be created: " + e.getMessage());
        }

        System.out.println("Finish.");
    }

    private static String readFile() throws IOException {
        final ClassLoader classLoader = main.class.getClassLoader();
        final InputStream inputStream = classLoader.getResourceAsStream("test.html");
        final StringBuilder sb = new StringBuilder();
        final Reader r = new InputStreamReader(Objects.requireNonNull(inputStream), StandardCharsets.UTF_8);
        char[] buf = new char[1024];
        int amt = r.read(buf);
        while(amt > 0) {
            sb.append(buf, 0, amt);
            amt = r.read(buf);
        }
        return sb.toString();
    }
}
</code>```

Don't bother about the second function, it just reads the HTML file and is only included here, to have a complete program.

src/main/resources/fonts/SourceSansPro-regular.ttf

Download here: https://www.fontsquirrel.com/fonts/source-sans-pro

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>paf</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.openhtmltopdf</groupId>
            <artifactId>openhtmltopdf-pdfbox</artifactId>
            <version>0.0.1-RC18</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.2</version>
        </dependency>
    </dependencies>
</project>
</code>```

Program output:

```<code>Starting
com.openhtmltopdf.load INFO:: TIME: parse stylesheets  148ms
com.openhtmltopdf.match INFO:: media = print
com.openhtmltopdf.match INFO:: Matcher created with 147 selectors
com.openhtmltopdf.load INFO:: Loading font(source-sans) from InputStream supplier now.
com.openhtmltopdf.exception WARNING:: bad URL given: /fonts/SourceSansPro-Regular.ttf
com.openhtmltopdf.exception WARNING:: Could not load @font-face font: /fonts/SourceSansPro-Regular.ttf
com.openhtmltopdf.exception WARNING:: Font metrics not available. Probably a bug.
com.openhtmltopdf.exception WARNING:: Font metrics not available. Probably a bug.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
Finish.
</code>```

Resulting PDF

```<code>Latin Script
##### ######## #######.
</code>```

In Serif-Font.

Edit 1: Various changes according to the pages linked in the comments and updated to RC18. new output now, but font in PDF still not right.

Edit 2: Tried fast Renderer

答:
Tried all the above solutions, but it did not worked from me.

However using  tag inplace of @font-face worked for me.

Here is the example of html:

```<code><html
        xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+Ethiopic&display=swap" rel="stylesheet">
</head>
<body class="c9" style="font-family: 'Noto Serif Ethiopic', serif;">
<p> {my content here} </p>
</code>```

so using the link and using the google fonts specific for the language which i needed resolved the issue for me.

I hope this helps others.

Body:
I create a PDF from HTML with Jsoup and OpenHTMLToPDF. I have to use a different font in my PDF to have non-latin glyphcs covered (see here). How can I embed my font correctly?

Simplified program reproducing the issue:

src/main/resources/test.html

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <title>Font Test</title>

Latin Script

Είμαι ελληνικό κείμενο.

this file shall be written as PDF

In a browser it looks correctly and uses the Source Sans font.

src/main/java/main.java:

import com.openhtmltopdf.extend.FSSupplier;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.w3c.dom.Document;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class main {
    public static void main(String[] args) {
        System.out.println("Starting");

        try {

            final W3CDom w3cDom = new W3CDom();
            final Document w3cDoc = w3cDom.fromJsoup(Jsoup.parse(readFile()));
            final OutputStream outStream = new FileOutputStream("test.pdf");

            final PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();
            pdfBuilder.useFastMode();
            pdfBuilder.withW3cDocument(w3cDoc, "/");
            pdfBuilder.useFont(new File(main.class.getClassLoader().getResource("fonts/SourceSansPro-Regular.ttf").getFile()), "source-sans");
            pdfBuilder.toStream(outStream);

            pdfBuilder.run();
            outStream.close();

        } catch (Exception e) {
            System.out.println("PDF could not be created: " + e.getMessage());
        }

        System.out.println("Finish.");
    }

    private static String readFile() throws IOException {
        final ClassLoader classLoader = main.class.getClassLoader();
        final InputStream inputStream = classLoader.getResourceAsStream("test.html");
        final StringBuilder sb = new StringBuilder();
        final Reader r = new InputStreamReader(Objects.requireNonNull(inputStream), StandardCharsets.UTF_8);
        char[] buf = new char[1024];
        int amt = r.read(buf);
        while(amt > 0) {
            sb.append(buf, 0, amt);
            amt = r.read(buf);
        }
        return sb.toString();
    }
}

Don't bother about the second function, it just reads the HTML file and is only included here, to have a complete program.

src/main/resources/fonts/SourceSansPro-regular.ttf

Download here: https://www.fontsquirrel.com/fonts/source-sans-pro

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>paf</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.openhtmltopdf</groupId>
            <artifactId>openhtmltopdf-pdfbox</artifactId>
            <version>0.0.1-RC18</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.2</version>
        </dependency>
    </dependencies>
</project>

Program output:

Starting
com.openhtmltopdf.load INFO:: TIME: parse stylesheets  148ms
com.openhtmltopdf.match INFO:: media = print
com.openhtmltopdf.match INFO:: Matcher created with 147 selectors
com.openhtmltopdf.load INFO:: Loading font(source-sans) from InputStream supplier now.
com.openhtmltopdf.exception WARNING:: bad URL given: /fonts/SourceSansPro-Regular.ttf
com.openhtmltopdf.exception WARNING:: Could not load @font-face font: /fonts/SourceSansPro-Regular.ttf
com.openhtmltopdf.exception WARNING:: Font metrics not available. Probably a bug.
com.openhtmltopdf.exception WARNING:: Font metrics not available. Probably a bug.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
com.openhtmltopdf.render WARNING:: Font is null.
Finish.

Resulting PDF

Latin Script
##### ######## #######.

In Serif-Font.

Edit 1: Various changes according to the pages linked in the comments and updated to RC18. new output now, but font in PDF still not right.

Edit 2: Tried fast Renderer

Body:
Tried all the above solutions, but it did not worked from me.

However using  tag inplace of @font-face worked for me.

Here is the example of html:

<html
        xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+Ethiopic&display=swap" rel="stylesheet">
</head>
<body class="c9" style="font-family: 'Noto Serif Ethiopic', serif;">
<p> {my content here} </p>

so using the link and using the google fonts specific for the language which i needed resolved the issue for me.

I hope this helps others.


问:
How to do mongodb $lookup, but keep other fields
Each document in my collection has a list of people and their status:

```<code>[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      { id: 61c005b939d7239960dceca5, status: 'pending' },
      { id: 6204232e0aa660002e2e2617, status: 'active' }
    ]
  },
  // ...
]
</code>```

I do a lookup to replace the person ID with the actual data from another collection, with this lookup stage:

```<code>{
  $lookup: {
    from: 'user',
    let: { people: '$people' },
    pipeline: [
      { $match: { $expr: { $in: [ '$_id', '$$people.id' ] } } }
    ],
    as: 'people'
  }
}
</code>```

The result of this is something like this:

```<code>[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      {
        _id: 61c005b939d7239960dceca5,
        lastName: 'Joe',
        firstName: 'Shmo',
      },
      {
        _id: 6204232e0aa660002e2e2617,
        firstName: 'John',
        lastName: 'Appleseed',
      }
    ]
  },
  // ...
]
</code>```

That's great, but I've lost the "status" field from the original documents.
Is there a way to keep the status field in the result? Or copy it in afterward?

答:
Try this: https://mongoplayground.net/p/gRLzpJ3i6Ir

Not very efficient...

```<code>db.coll.aggregate([
  {
    $lookup: {
      from: "user",
      let: {
        people: "$people"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$_id",
                "$$people.id"
              ]
            }
          }
        }
      ],
      as: "people2"
    }
  },
  {
    "$addFields": {
      "people": {
        $map: {
          input: "$people2",
          in: {
            "$mergeObjects": [
              "$$this",
              {
                "$arrayElemAt": [
                  {
                    "$filter": {
                      "input": "$people",
                      "as": "pstatus",
                      "cond": {
                        $eq: [
                          "$$pstatus.id",
                          "$$this._id"
                        ]
                      }
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  }
])
</code>```

Body:
Each document in my collection has a list of people and their status:

[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      { id: 61c005b939d7239960dceca5, status: 'pending' },
      { id: 6204232e0aa660002e2e2617, status: 'active' }
    ]
  },
  // ...
]

I do a lookup to replace the person ID with the actual data from another collection, with this lookup stage:

{
  $lookup: {
    from: 'user',
    let: { people: '$people' },
    pipeline: [
      { $match: { $expr: { $in: [ '$_id', '$$people.id' ] } } }
    ],
    as: 'people'
  }
}

The result of this is something like this:

[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      {
        _id: 61c005b939d7239960dceca5,
        lastName: 'Joe',
        firstName: 'Shmo',
      },
      {
        _id: 6204232e0aa660002e2e2617,
        firstName: 'John',
        lastName: 'Appleseed',
      }
    ]
  },
  // ...
]

That's great, but I've lost the "status" field from the original documents.
Is there a way to keep the status field in the result? Or copy it in afterward?

Body:
Try this: https://mongoplayground.net/p/gRLzpJ3i6Ir

Not very efficient...

db.coll.aggregate([
  {
    $lookup: {
      from: "user",
      let: {
        people: "$people"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$_id",
                "$$people.id"
              ]
            }
          }
        }
      ],
      as: "people2"
    }
  },
  {
    "$addFields": {
      "people": {
        $map: {
          input: "$people2",
          in: {
            "$mergeObjects": [
              "$$this",
              {
                "$arrayElemAt": [
                  {
                    "$filter": {
                      "input": "$people",
                      "as": "pstatus",
                      "cond": {
                        $eq: [
                          "$$pstatus.id",
                          "$$this._id"
                        ]
                      }
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  }
])


问:
Autosummary with toctree not creating documentation for methods
I'm using sphinx with the numpydoc extension and autosummary.  After some experimentation, I added the following options to my conf.py file.

```<code>autosummary_generate = True
numpydoc_show_class_members = False
</code>```

This is giving me a new file for each class referenced like below, and it also creates a summary table of all of the attributes and methods.

```<code>.. autosummary::
   :toctree: generated/
   :nosignatures:

   MyClass
</code>```

The problem is that while there is a summary table of the methods with the first line of the doc string, the names of the methods don't link to anything.  How do I get the doc strings of the methods to also create files of their own (or at least generate the documentation in the same file as the class)?

答: It appears that a template is needed to have sphinx generate rst files for the methods. Under _templates/autosummary I added a file named class.rst which looks like this and everything works.

Body:
I'm using sphinx with the numpydoc extension and autosummary.  After some experimentation, I added the following options to my conf.py file.

autosummary_generate = True
numpydoc_show_class_members = False

This is giving me a new file for each class referenced like below, and it also creates a summary table of all of the attributes and methods.

.. autosummary::
   :toctree: generated/
   :nosignatures:

   MyClass

The problem is that while there is a summary table of the methods with the first line of the doc string, the names of the methods don't link to anything.  How do I get the doc strings of the methods to also create files of their own (or at least generate the documentation in the same file as the class)?


问:
Excel formula to enhance depreciation pro-rated formula
I am building a file to calculate the depreciation amount of several items with various capitalization dates and depreciation rates. I currently have worked something out but it seems too basic, I am trying to fit as many of the already created formulas from column I to N into one to make it nice and clean. I am struggling to mix & match formuals to get there. Any suggestions on which formuals I should use is most welcomed.

From column A to G, it is data generated by a system. From Column I to N is the couple of basic formulas I have added.

Cell I13 has: =YEAR($C$10)-YEAR(B13)
Cell J13 has: =MONTH($C$10)-MONTH(B13)+1
Cell K13 has: =(I13*12)+J13
Cell L13 has: =VLOOKUP(A13,$B$4:$D$8,3,FALSE)
Cell M13 has: =VLOOKUP(A13,$B$4:$E$8,4,FALSE)
Cell N13 has: =IF(K13<M13,-C13*K13/M13,-C13)

The depreciation is calculated from the month of purchase of the asset (capitalisation date) and not by day.

答:
You could make your life easier using Excel 'hidden' DATEDIF() function.

=DATEDIF(startDate, endDate, "M") will return the difference in months.

There is a good explanation  about it here and from Microsoft here.
You will have to type it manually, strangely it is not available in the list of functions.


问:
File transfer from android mobile to android tv
Wanna create an app for file transfer from android mobile to android tv like this Send files to tv.Using wifi p2p file transfer or any other technic should i use to achieve this? If i use wifi p2p i should enable location permission.But Send files to tv not asking location permission. Any idea?</p>

答:
Since you are already using Wifi p2p you can combine it with NanoHttpD server to serve your file to the TV Device over wifi. NanoHttpD is a very small web server which can be used to serve both Rest API's which can then be called by the application embedded on the TV or you can stream files using it.

Checkout this answer on how to use it on Android.


问:
Dropdown Search fuzzy but require Begins with
Semantic-UI-React search pattern appears to be fuzzy however, I need "starts with".
Reviewing Semantic-UI this is supported, but I can't find the options in Semantic-UI-React.

Is this possible? if not can someone directly how I can extend/Override the search module?

What is expected?
When typing "B" into the search input, I expect countries beginning with 'B' to be displayed.
What I get
When typing "B" into the search input, I get any countries with 'B' or 'b' in the name.

https://codesandbox.io/s/semantic-ui-select-search-9l7nu?file=/example.js:1297-1311

References Researched
https://github.com/Semantic-Org/Semantic-UI-React/issues/3690
https://semantic-ui.com/modules/dropdown.html#additional-settings

https://github.com/Semantic-Org/Semantic-UI-React/blob/master/src/modules/Search/Search.d.ts
https://github.com/Semantic-Org/Semantic-UI-React/blob/master/test/specs/modules/Search/Search-test.js

答:
The Framework is not going to be up-dated to match Semantic but there is a work-around.

https://github.com/Semantic-Org/Semantic-UI-React/issues/4333

```<code>function customSearch(options, searchQuery) {
  return options.filter((option) =>
    option.text.toLowerCase().startsWith(searchQuery.toLowerCase())
  );
}

const DropdownExampleSearchSelection = () => (
  <Dropdown
    placeholder="Select Country"
    search={customSearch}
    fluid
    selection
    options={countryOptions}
  />
);
</code>```

Body:
The Framework is not going to be up-dated to match Semantic but there is a work-around.

https://github.com/Semantic-Org/Semantic-UI-React/issues/4333

function customSearch(options, searchQuery) {
  return options.filter((option) =>
    option.text.toLowerCase().startsWith(searchQuery.toLowerCase())
  );
}

const DropdownExampleSearchSelection = () => (
  <Dropdown
    placeholder="Select Country"
    search={customSearch}
    fluid
    selection
    options={countryOptions}
  />
);


问:
Command times out when executing
```<code>Laravel version:
8.x

PHP version:
8.0

MySQL version:
8.0

Server:
Larave Forge
</code>```

I'm running a command on one of my websites

php artisan command:here

after a few minutes I get this status "Timed Out", is there anything that can be optimized here to prevent the time out?

subscriptions table has 40,000 records and incomes table has 8,000,000. Every subscription has a maximum of 200 records in the incomes table.

To explain what this command does, this is fixing (by inserting) the lacking of income of every ACTIVE subscription, which will be identified based on the hour difference from the last income that has been inserted. Every subscription has a max of 200 records in the incomes table, so if the script detected that a subscription has already reached the 200 income records, it will update the status to
COMPLETED.

Subscription.php (model)

```<code>public function latestIncome()
{
    return $this->hasOne(Income::class)->latestOfMany();
}
</code>```

Income.php (model)

```<code>public function subscription()
{
    return $this->belongsTo(Subscription::class);
}
</code>```
```<code>namespace App\Console\Commands;

class SomeCommand extends Command
{
    protected $signature = 'command:here';

    public function handle()
    {
        ini_set('max_execution_time', 0);

        foreach (Subscription::with('latestIncome')->withCount('income')->where('status', 'ACTIVE')->lazy() as $subscription) {
            $count_earnings = $subscription->income_count;
            $recent_bonus = $subscription->latestIncome;

            if ($recent_bonus) {
                if ($count_earnings < 200) {
                    $hour_difference = now()->diffInHours($recent_bonus->created_at);

                    if ($hour_difference > 1) {
                        $to_insert = 200 - $count_earnings;
                        $max = $hour_difference;

                        if ($hour_difference > $to_insert) {
                            $max = $to_insert;
                        }

                        for ($i = 0; $i < $max; $i++) {
                            $income = new Income;
                            $income->user_id = $subscription->user_id;
                            $income->subscription_id = $subscription->id;
                            $income->amount = (100 * 0.002) * 100;
                            $income->save();
                        }

                        if (($count_earnings + $max) >= 200) {
                            $subscription->update(['status' => 'COMPLETED']);
                        }

                        Log::info('Fix for:'.$subscription->id.' | User:'.$subscription->user_id.' | Total:'.$max);
                    }
                } else {
                    $subscription->update(['status' => 'COMPLETED']);
                }
            }
        }
    }
}
</code>```

答:
You can define a time limit in the __construct function or in your index controller if you want a large time restriction.</p>
```<code>    public function __construct()
    {
        set_time_limit(8000000);
    }
</code>```

Title: Command times out when executing

Body:
Laravel version:
8.x

PHP version:
8.0

MySQL version:
8.0

Server:
Larave Forge

I'm running a command on one of my websites

php artisan command:here

after a few minutes I get this status "Timed Out", is there anything that can be optimized here to prevent the time out?

subscriptions table has 40,000 records and incomes table has 8,000,000. Every subscription has a maximum of 200 records in the incomes table.

To explain what this command does, this is fixing (by inserting) the lacking of income of every ACTIVE subscription, which will be identified based on the hour difference from the last income that has been inserted. Every subscription has a max of 200 records in the incomes table, so if the script detected that a subscription has already reached the 200 income records, it will update the status to
COMPLETED.

Subscription.php (model)

public function latestIncome()
{
    return $this->hasOne(Income::class)->latestOfMany();
}

Income.php (model)

public function subscription()
{
    return $this->belongsTo(Subscription::class);
}

namespace App\Console\Commands;

class SomeCommand extends Command
{
    protected $signature = 'command:here';

    public function handle()
    {
        ini_set('max_execution_time', 0);

        foreach (Subscription::with('latestIncome')->withCount('income')->where('status', 'ACTIVE')->lazy() as $subscription) {
            $count_earnings = $subscription->income_count;
            $recent_bonus = $subscription->latestIncome;

            if ($recent_bonus) {
                if ($count_earnings < 200) {
                    $hour_difference = now()->diffInHours($recent_bonus->created_at);

                    if ($hour_difference > 1) {
                        $to_insert = 200 - $count_earnings;
                        $max = $hour_difference;

                        if ($hour_difference > $to_insert) {
                            $max = $to_insert;
                        }

                        for ($i = 0; $i < $max; $i++) {
                            $income = new Income;
                            $income->user_id = $subscription->user_id;
                            $income->subscription_id = $subscription->id;
                            $income->amount = (100 * 0.002) * 100;
                            $income->save();
                        }

                        if (($count_earnings + $max) >= 200) {
                            $subscription->update(['status' => 'COMPLETED']);
                        }

                        Log::info('Fix for:'.$subscription->id.' | User:'.$subscription->user_id.' | Total:'.$max);
                    }
                } else {
                    $subscription->update(['status' => 'COMPLETED']);
                }
            }
        }
    }
}

Body:
You can define a time limit in the __construct function or in your index controller if you want a large time restriction.

    public function __construct()
    {
        set_time_limit(8000000);
    }


问:
ESLint Definition for rule 'import/extensions' was not found
I'm getting the following two errors on all TypeScript files using ESLint in VS Code:

```<code>Definition for rule 'import/extensions' was not found.eslint(import/extensions)
Definition for rule 'import/no-extraneous-dependencies' was not found.eslint(import/no-extraneous-dependencies)
</code>```

A screenshot from VSC Problems pane:

Note on possible duplicates

There are many similar questions about different modules and even some about the import/extensions, but none of the suggested solutions help. I've tried them all. I also tried every single solution posted in every single thread suggested by Stack Overflow while typing this question.

Here is my .eslintrc.json:

```<code>{
  "env": {
      "es2021": true,
      "node": true
  },
  "extends": [
      "airbnb-typescript/base",
      "plugin:@typescript-eslint/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaVersion": 12,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "@typescript-eslint"
  ],
  "rules": {
      "@typescript-eslint/no-use-before-define": "off"
  }
}
</code>```

package.json:

```<code>{
  "name": "graph-userdata-gateway",
  "version": "1.0.0",
  "description": "Gateway for PowerApps Microsoft Graph API custom connector to query user data with application permissions.",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git@gitlab.yobitti.fi:powerapps/graph-userdata-gateway.git"
  },
  "author": "Benjamin Pettinen / YO-bitti Oy",
  "license": "UNLICENSED",
  "dependencies": {
    "@microsoft/microsoft-graph-client": "^3.0.0",
    "dedent": "^0.7.0",
    "express": "^4.17.1",
    "isomorphic-fetch": "^3.0.0",
    "md5": "^2.3.0",
    "node-fetch": "^2.6.1"
  },
  "devDependencies": {
    "@types/dedent": "^0.7.0",
    "@types/express": "^4.17.13",
    "@types/isomorphic-fetch": "0.0.35",
    "@types/md5": "^2.3.1",
    "@types/node-fetch": "^2.5.12",
    "@typescript-eslint/eslint-plugin": "^4.29.2",
    "@typescript-eslint/parser": "^4.29.2",
    "eslint": "^7.32.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-airbnb-typescript": "^13.0.0",
    "eslint-plugin-import": "^2.24.1",
    "typescript": "^4.3.5"
  }
}
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "esModuleInterop": true,
    "noImplicitAny": true,
    "moduleResolution": "Node",
    "outDir": "dist",
    "sourceMap": true
  }
}
</code>```

I've tried deleting the whole node_mobules and re-running npm install as well as played with the extends in the .eslintrc.json. If I remove airbnb-typescript/base the error disappears, but I lose the Airbnb style from ESLint. Using airbnb-base instead works, but then ESLint complains about Missing file extension for abc.ts and Unable to resolve path to module abc. I have also multiple time restarted VSC and the ESLint server.

答:
In my case, I was able to fix it by adding the "allowSyntheticDefaultImports" setting to "compilerOptions" in "tsconfig.json".</p>
```<code>{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
  }
}
</code>```

Body:
I'm getting the following two errors on all TypeScript files using ESLint in VS Code:

Definition for rule 'import/extensions' was not found.eslint(import/extensions)
Definition for rule 'import/no-extraneous-dependencies' was not found.eslint(import/no-extraneous-dependencies)

A screenshot from VSC Problems pane:

Note on possible duplicates

There are many similar questions about different modules and even some about the import/extensions, but none of the suggested solutions help. I've tried them all. I also tried every single solution posted in every single thread suggested by Stack Overflow while typing this question.

Here is my .eslintrc.json:

{
  "env": {
      "es2021": true,
      "node": true
  },
  "extends": [
      "airbnb-typescript/base",
      "plugin:@typescript-eslint/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaVersion": 12,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "@typescript-eslint"
  ],
  "rules": {
      "@typescript-eslint/no-use-before-define": "off"
  }
}

package.json:

{
  "name": "graph-userdata-gateway",
  "version": "1.0.0",
  "description": "Gateway for PowerApps Microsoft Graph API custom connector to query user data with application permissions.",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git@gitlab.yobitti.fi:powerapps/graph-userdata-gateway.git"
  },
  "author": "Benjamin Pettinen / YO-bitti Oy",
  "license": "UNLICENSED",
  "dependencies": {
    "@microsoft/microsoft-graph-client": "^3.0.0",
    "dedent": "^0.7.0",
    "express": "^4.17.1",
    "isomorphic-fetch": "^3.0.0",
    "md5": "^2.3.0",
    "node-fetch": "^2.6.1"
  },
  "devDependencies": {
    "@types/dedent": "^0.7.0",
    "@types/express": "^4.17.13",
    "@types/isomorphic-fetch": "0.0.35",
    "@types/md5": "^2.3.1",
    "@types/node-fetch": "^2.5.12",
    "@typescript-eslint/eslint-plugin": "^4.29.2",
    "@typescript-eslint/parser": "^4.29.2",
    "eslint": "^7.32.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-airbnb-typescript": "^13.0.0",
    "eslint-plugin-import": "^2.24.1",
    "typescript": "^4.3.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "esModuleInterop": true,
    "noImplicitAny": true,
    "moduleResolution": "Node",
    "outDir": "dist",
    "sourceMap": true
  }
}

I've tried deleting the whole node_mobules and re-running npm install as well as played with the extends in the .eslintrc.json. If I remove airbnb-typescript/base the error disappears, but I lose the Airbnb style from ESLint. Using airbnb-base instead works, but then ESLint complains about Missing file extension for abc.ts and Unable to resolve path to module abc. I have also multiple time restarted VSC and the ESLint server.

Body:
In my case, I was able to fix it by adding the "allowSyntheticDefaultImports" setting to "compilerOptions" in "tsconfig.json".

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
  }
}


答:
For count number of E values create helper column tmp and caout values by sum:

```<code>df = (df[df.assign(tmp = df['Type']=='E')
           .groupby(['date','Id'])['tmp'].transform('sum').gt(1)])
</code>```

Title: Select values with condition count() Python

Body:
I want select all data of values have two type 'E' in data values. In this data, we can have many type 'S' but it's only one value of type 'E'.

For example: ID: 1114 have two 'Type': 'E' in values so show all values of 1114.

dataframe 1:

id /date /origine /destination /horaire A /horaire B/ Type /Other data

1112 2021-03-11 Paris / Marseille/10:00/14:00/A / ..
1112 2021-03-11 Paris / Marseille/10:00/14:00/E /..
1112 2021-03-11 Paris / Marseille/10:00/14:00/S /..
1112 2021-03-11 Paris / Lyon/10:00/12:00/S/..
1112 2021-03-11 Paris / Marseille/10:00/14:00/S/..
1112 2021-03-11 Paris / Marseille/10:00/14:00/C/..
1114 2021-05-11 Paris / Bordeaux/09:00/13:00/A/..
1114 2021-05-11 Paris / Bordeaux/09:00/13:00/E/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:20/14:00/E/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/C/..

data output:

id /date /origine /destination /horaire A /horaire B/ Type /Other data

1114 2021-05-11 Paris / Bordeaux/09:00/13:00/A/..
1114 2021-05-11 Paris / Bordeaux/09:00/13:00/E/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:20/14:00/E/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/S/..
1114 2021-05-11 Paris / Bordeaux/10:00/14:00/C/..

I wrote this code:

mask = df.groupby(['date','Id']).apply(lambda x: x['Type'].value_counts())
data_set = df[((df['Type']=='E).isin(mask.index[mask > 1]))]
data_set

But my output is empty

Body:
For count number of E values create helper column tmp and caout values by sum:

df = (df[df.assign(tmp = df['Type']=='E')
           .groupby(['date','Id'])['tmp'].transform('sum').gt(1)])


问:
Git: Undo a commit after several good commits have been commited afterwards
I have a beginner question around git and GitHub i was hoping someone could help with.

I have accidentally committed a change in  piece of code that contains credentials on my local private repository on my local machine.

My pseudo commit history looks like the below and i am using the desktop application for GitHub to make these commits. I made the mistaken commit at id 3 but then all my other commits from four to seven are a big body of work and I do not wish to lose them.

Since this is my own repository the quick method might be to simply copy out the files i changed and revert back all my changes to id 3 and then copy in my good changed files. I was wondering if there was a better Git way

```<code>commit first change  id 1
commit second change id 2
commit third change  id 3 - here is where the password was committed
commit first change  id 4
commit second change id 5
commit first change  id 6
commit second change id 7
</code>```

Thank you very much for your time

答:
You either can do squash:

```<code>git rebase -i <commit_id or HEAD~5>
# move your cursor on the commit line & delete that commit by pressing double `d`
git push -f origin <branch>
</code>```

It helps to delete selected commits only, without changing commits after and before that commit.

Or, soft reset and commit:

```<code>git reset --soft <commit_id or HEAD~5>
git add .
git commit -m "<message>"
git push -f origin <branch>
</code>```

It deletes all commits from the commit_id or HEAD~5 and makes a single commit.

Body:
I have a beginner question around git and GitHub i was hoping someone could help with.

I have accidentally committed a change in  piece of code that contains credentials on my local private repository on my local machine.

My pseudo commit history looks like the below and i am using the desktop application for GitHub to make these commits. I made the mistaken commit at id 3 but then all my other commits from four to seven are a big body of work and I do not wish to lose them.

Since this is my own repository the quick method might be to simply copy out the files i changed and revert back all my changes to id 3 and then copy in my good changed files. I was wondering if there was a better Git way

commit first change  id 1
commit second change id 2
commit third change  id 3 - here is where the password was committed
commit first change  id 4
commit second change id 5
commit first change  id 6
commit second change id 7

Thank you very much for your time

Body:
You either can do squash:

git rebase -i <commit_id or HEAD~5>
# move your cursor on the commit line & delete that commit by pressing double `d`
git push -f origin <branch>

It helps to delete selected commits only, without changing commits after and before that commit.

Or, soft reset and commit:

git reset --soft <commit_id or HEAD~5>
git add .
git commit -m "<message>"
git push -f origin <branch>

It deletes all commits from the commit_id or HEAD~5 and makes a single commit.


问:
How to tell `git diff` to make a diff usable with `patch -p0`?
I have a file in a git repo. I checked it out from branch release, edited it to fix a problem, and checked it in to a new branch bugfix. I now want to make a diff file which captures this edit. I want to apply this diff file, using patch -p0, to a separate copy of the release branch, which is outside of git control. After the patch, I want the file to match what I have in branch bugfix.

I tried using the command git diff release bugfix -- myfile.m4. It gave me a .diff file which begins,

```<code>index 17641f7482..2b31725fae 100644
--- a/myfile.m4
+++ b/myfile.m4
[… rest of diff elided …]
</code>```

When I apply this diff to my separate repo using patch -p0, it fails. Patch is unable to find paths a/myfile.m4 and b/myfile.m4, because of course they don't exist. There are no directories a and b in my source. Note, if I could use patch -p1, then the diff would work as a patch. But, because of tooling constraints, I am not easily able to use patch -p1.

I would like the .diff file to leave out the a/ and b/ prefixes. I would like the diff file to read something like:

```<code>index 87641f7482..2821725fae 100644
--- myfile.m4
+++ myfile.m4
[… rest of diff elided …]
</code>```

Is there a way to make git diff produce a diff without those non-existent path prefixes?

There is a workaround: checkout the file from the release branch, rename it myfile.m4.orig, then checkout the modified file from the bugfix branch, then do diff -u myfile.m4.orig myfile.m4. This gives me a diff which I can use with patch -p0. But I want to avoid making a separate file with a contrived file name.

答:
You can use --dst-prefix= and --src-prefix= to specify the destination and source prefixes, I guess that you might be able to set them to an empty string:

```<code>$ git diff --src-prefix= --dst-prefix= release bugfix -- myfile.m4
</code>```

As pointed out in the comments, you can also use --no-prefix:

```<code>$ git diff --no-prefix release bugfix -- myfile.m4
</code>```

Body:
I have a file in a git repo. I checked it out from branch release, edited it to fix a problem, and checked it in to a new branch bugfix. I now want to make a diff file which captures this edit. I want to apply this diff file, using patch -p0, to a separate copy of the release branch, which is outside of git control. After the patch, I want the file to match what I have in branch bugfix.

I tried using the command git diff release bugfix -- myfile.m4. It gave me a .diff file which begins,

index 17641f7482..2b31725fae 100644
--- a/myfile.m4
+++ b/myfile.m4
[… rest of diff elided …]

When I apply this diff to my separate repo using patch -p0, it fails. Patch is unable to find paths a/myfile.m4 and b/myfile.m4, because of course they don't exist. There are no directories a and b in my source. Note, if I could use patch -p1, then the diff would work as a patch. But, because of tooling constraints, I am not easily able to use patch -p1.

I would like the .diff file to leave out the a/ and b/ prefixes. I would like the diff file to read something like:

index 87641f7482..2821725fae 100644
--- myfile.m4
+++ myfile.m4
[… rest of diff elided …]

Is there a way to make git diff produce a diff without those non-existent path prefixes?

There is a workaround: checkout the file from the release branch, rename it myfile.m4.orig, then checkout the modified file from the bugfix branch, then do diff -u myfile.m4.orig myfile.m4. This gives me a diff which I can use with patch -p0. But I want to avoid making a separate file with a contrived file name.

Body:
You can use --dst-prefix= and --src-prefix= to specify the destination and source prefixes, I guess that you might be able to set them to an empty string:

$ git diff --src-prefix= --dst-prefix= release bugfix -- myfile.m4

As pointed out in the comments, you can also use --no-prefix:

$ git diff --no-prefix release bugfix -- myfile.m4


问:
Cannot upload images when WordPress is sat on a virtual host configuration
This is my first post to this Forum, please forgive me if this has been answered elsewhere--I did search and was unable to find an answer to my particular problem, so any help would be greatly appreciated.

I am working on a WP site for a client who wants to upload images to new posts (who doesn't hey?). In setting up the site I have done the following:

1) Enabled File Upload by CHMOD default dir to 777.
2) Changed max file size.
3) Changed allowed filetypes to include necessary file types.

When I try to upload anything I get the following error:

“Bobst Expertfold 80 110 (Dec 2010).jpg” has failed to upload due to an error
The uploaded file could not be moved to /var/www/vhosts/glossopcartons.com/httpdocs/wp-content/uploads/2010/12.

The above error mentions 'glossopcartons.com', this WP site is actually sat on glossopcartons.co.uk. It's obvious that there is some kind of virtual host configuration going on and the image is trying to be uploaded to a folder on a different domain (glossopcartons.com instead of glossopcartons.co.uk).

I don't manage the hosting, I have just been assigned with the build. However, I have access to the plesk cpanel but I dont know what I need to do?

Does anyone know what is causing this problem? The site has actually been made live and this issue has been spotted after the launch(everything worked fine on the test server), and I am scratching my head trying to figure it out.

Is there something I can put in my wp-config.php or .htaccess file to tell WP to upload to a different location.

Any help would be greatly appreciated.

Dan

答: Make sure PHP lets you upload files larger than what you are trying to upload.</p>


问:
How can I fill my rich model from repository when I am no using ORM?
I am trying to develop my application using the DDD approach and I should set all of my properties private. I need to use Aerospike as my database and there is no ORM to fill my properties magically like EntityFramework with a private default constructor.
Now, How can I fill this reach model without exposing a full property constructor that can be accessible everywhere and can breach the rule of encapsulation business domain rules?

making all properties protected and creating an internal inherited class inside the repository namespace that can act as a proxy object to fill property can be a solution But I have no idea about the best practice and acceptable design.

答:
I'm not familiar with Aerospike, but here are my thoughts. First, EF is able to set private properties because it uses reflection to do so. And it needs a parameterless constructor for this. So you could do it the same way: create an object and set properties via reflection.

Or, as others pointed out in the comments, you will anyway need methods to set your private properties, so just use them to instantiate your model. You use private setters and methods in order to ensure that the state of your DDD object is valid and do some internal checks, e.g.:

```<code>public class Whatever {
   private int age;

   public int Age { get; private set; }

   public void UpdateAge(int a) {
      if (a > 0) {
         this.age = a;
      }

      throw new MyException();
   }
}
</code>```

So just use UpdateAge() and the like. On the other hand it's not necessary to run extra validations if you are instantiating from a database, because all the data in the DB is valid. You could introduce some private variable, like needsValidation, and set it to false in case you are instantiating from the DB via e.g. an internal constructor. Whether it's really worth the effort depends on your use case.

Body:
I'm not familiar with Aerospike, but here are my thoughts. First, EF is able to set private properties because it uses reflection to do so. And it needs a parameterless constructor for this. So you could do it the same way: create an object and set properties via reflection.

Or, as others pointed out in the comments, you will anyway need methods to set your private properties, so just use them to instantiate your model. You use private setters and methods in order to ensure that the state of your DDD object is valid and do some internal checks, e.g.:

public class Whatever {
   private int age;

   public int Age { get; private set; }

   public void UpdateAge(int a) {
      if (a > 0) {
         this.age = a;
      }

      throw new MyException();
   }
}

So just use UpdateAge() and the like. On the other hand it's not necessary to run extra validations if you are instantiating from a database, because all the data in the DB is valid. You could introduce some private variable, like needsValidation, and set it to false in case you are instantiating from the DB via e.g. an internal constructor. Whether it's really worth the effort depends on your use case.


问:
Excel doesn't update value unless I hit Enter
I have a very annoying problem in one of my worksheets in a workbook. I am using EXCEL 2007. Any cell's value will not be updated unless I hit ENTER. Either if the formula in the cell includes an if condition, or a VLOOKUP function or even an AVERAGE function. All the calculations are set to automatic, Application.Calculation = xlAutomatic, and even the calculations for the specific worksheet are enabled, like : ws.EnableCalculation = TRUE.

Furthermore, the ScreenUpdating is set to TRUE. After I hit the ENTER or I drag down the right corner, the cells will be updated, and they will keep being updated if I make any change. However, after saving the file and reopening it again they will be frozen again. I haven't figured out exactly when they will stop being updated again. All the formatting are set to General or number.

Especially in IF conditions, when I check the calculations through the evaluate feature, the result is correct but it is not passed on the screen.

Any suggestion? This thing is driving me crazy.

答:
Found a simple solution.

Let's say once cell A1 is changed, so you expect cell B1 change the color by conditional formula.

Make the problematic cell - B1 has a formula with dependency to cell - A1

So, for example instead of my cell B1 just have text value "Text", i'll change it to formula like:

=IF(A1>0,"Text","Text") - means: if A1 > 0, then insert value "Text" to B1

The result is - each time cell A1 is recalculated, it forces also cell B1 color to be updated.