partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
HStoreColumn.relabeled_clone
Gets a re-labeled clone of this expression.
psqlextra/expressions.py
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
[ "Gets", "a", "re", "-", "labeled", "clone", "of", "this", "expression", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/expressions.py#L104-L112
[ "def", "relabeled_clone", "(", "self", ",", "relabels", ")", ":", "return", "self", ".", "__class__", "(", "relabels", ".", "get", "(", "self", ".", "alias", ",", "self", ".", "alias", ")", ",", "self", ".", "target", ",", "self", ".", "hstore_key", ",", "self", ".", "output_field", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRef.resolve_expression
Resolves the expression into a :see:HStoreColumn expression.
psqlextra/expressions.py
def resolve_expression(self, *args, **kwargs) -> HStoreColumn: """Resolves the expression into a :see:HStoreColumn expression.""" original_expression = super().resolve_expression(*args, **kwargs) expression = HStoreColumn( original_expression.alias, original_expression.target, self.key ) return expression
def resolve_expression(self, *args, **kwargs) -> HStoreColumn: """Resolves the expression into a :see:HStoreColumn expression.""" original_expression = super().resolve_expression(*args, **kwargs) expression = HStoreColumn( original_expression.alias, original_expression.target, self.key ) return expression
[ "Resolves", "the", "expression", "into", "a", ":", "see", ":", "HStoreColumn", "expression", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/expressions.py#L135-L144
[ "def", "resolve_expression", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "HStoreColumn", ":", "original_expression", "=", "super", "(", ")", ".", "resolve_expression", "(", "*", "args", ",", "*", "*", "kwargs", ")", "expression", "=", "HStoreColumn", "(", "original_expression", ".", "alias", ",", "original_expression", ".", "target", ",", "self", ".", "key", ")", "return", "expression" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
DateTimeEpochColumn.as_sql
Compiles this expression into SQL.
psqlextra/expressions.py
def as_sql(self, compiler, connection): """Compiles this expression into SQL.""" sql, params = super().as_sql(compiler, connection) return 'EXTRACT(epoch FROM {})'.format(sql), params
def as_sql(self, compiler, connection): """Compiles this expression into SQL.""" sql, params = super().as_sql(compiler, connection) return 'EXTRACT(epoch FROM {})'.format(sql), params
[ "Compiles", "this", "expression", "into", "SQL", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/expressions.py#L178-L182
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", ":", "sql", ",", "params", "=", "super", "(", ")", ".", "as_sql", "(", "compiler", ",", "connection", ")", "return", "'EXTRACT(epoch FROM {})'", ".", "format", "(", "sql", ")", ",", "params" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresQuery.rename_annotations
Renames the aliases for the specified annotations: .annotate(myfield=F('somestuf__myfield')) .rename_annotations(myfield='field') Arguments: annotations: The annotations to rename. Mapping the old name to the new name.
psqlextra/query.py
def rename_annotations(self, annotations) -> None: """Renames the aliases for the specified annotations: .annotate(myfield=F('somestuf__myfield')) .rename_annotations(myfield='field') Arguments: annotations: The annotations to rename. Mapping the old name to the new name. """ for old_name, new_name in annotations.items(): annotation = self.annotations.get(old_name) if not annotation: raise SuspiciousOperation(( 'Cannot rename annotation "{old_name}" to "{new_name}", because there' ' is no annotation named "{old_name}".' ).format(old_name=old_name, new_name=new_name)) self._annotations = OrderedDict( [(new_name, v) if k == old_name else (k, v) for k, v in self._annotations.items()]) if django.VERSION < (2, 0): self.set_annotation_mask( (new_name if v == old_name else v for v in (self.annotation_select_mask or [])))
def rename_annotations(self, annotations) -> None: """Renames the aliases for the specified annotations: .annotate(myfield=F('somestuf__myfield')) .rename_annotations(myfield='field') Arguments: annotations: The annotations to rename. Mapping the old name to the new name. """ for old_name, new_name in annotations.items(): annotation = self.annotations.get(old_name) if not annotation: raise SuspiciousOperation(( 'Cannot rename annotation "{old_name}" to "{new_name}", because there' ' is no annotation named "{old_name}".' ).format(old_name=old_name, new_name=new_name)) self._annotations = OrderedDict( [(new_name, v) if k == old_name else (k, v) for k, v in self._annotations.items()]) if django.VERSION < (2, 0): self.set_annotation_mask( (new_name if v == old_name else v for v in (self.annotation_select_mask or [])))
[ "Renames", "the", "aliases", "for", "the", "specified", "annotations", ":" ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/query.py#L25-L51
[ "def", "rename_annotations", "(", "self", ",", "annotations", ")", "->", "None", ":", "for", "old_name", ",", "new_name", "in", "annotations", ".", "items", "(", ")", ":", "annotation", "=", "self", ".", "annotations", ".", "get", "(", "old_name", ")", "if", "not", "annotation", ":", "raise", "SuspiciousOperation", "(", "(", "'Cannot rename annotation \"{old_name}\" to \"{new_name}\", because there'", "' is no annotation named \"{old_name}\".'", ")", ".", "format", "(", "old_name", "=", "old_name", ",", "new_name", "=", "new_name", ")", ")", "self", ".", "_annotations", "=", "OrderedDict", "(", "[", "(", "new_name", ",", "v", ")", "if", "k", "==", "old_name", "else", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_annotations", ".", "items", "(", ")", "]", ")", "if", "django", ".", "VERSION", "<", "(", "2", ",", "0", ")", ":", "self", ".", "set_annotation_mask", "(", "(", "new_name", "if", "v", "==", "old_name", "else", "v", "for", "v", "in", "(", "self", ".", "annotation_select_mask", "or", "[", "]", ")", ")", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresQuery.add_join_conditions
Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query doesn't already generate the initial join in the first place.
psqlextra/query.py
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query doesn't already generate the initial join in the first place. """ alias = self.get_initial_alias() opts = self.get_meta() for name, value in conditions.items(): parts = name.split(LOOKUP_SEP) join_info = self.setup_joins(parts, opts, alias, allow_many=True) self.trim_joins(join_info[1], join_info[3], join_info[4]) target_table = join_info[3][-1] field = join_info[1][-1] join = self.alias_map.get(target_table) if not join: raise SuspiciousOperation(( 'Cannot add an extra join condition for "%s", there\'s no' ' existing join to add it to.' ) % target_table) # convert the Join object into a ConditionalJoin object, which # allows us to add the extra condition if not isinstance(join, ConditionalJoin): self.alias_map[target_table] = ConditionalJoin.from_join(join) join = self.alias_map[target_table] join.add_condition(field, value)
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query doesn't already generate the initial join in the first place. """ alias = self.get_initial_alias() opts = self.get_meta() for name, value in conditions.items(): parts = name.split(LOOKUP_SEP) join_info = self.setup_joins(parts, opts, alias, allow_many=True) self.trim_joins(join_info[1], join_info[3], join_info[4]) target_table = join_info[3][-1] field = join_info[1][-1] join = self.alias_map.get(target_table) if not join: raise SuspiciousOperation(( 'Cannot add an extra join condition for "%s", there\'s no' ' existing join to add it to.' ) % target_table) # convert the Join object into a ConditionalJoin object, which # allows us to add the extra condition if not isinstance(join, ConditionalJoin): self.alias_map[target_table] = ConditionalJoin.from_join(join) join = self.alias_map[target_table] join.add_condition(field, value)
[ "Adds", "an", "extra", "condition", "to", "an", "existing", "JOIN", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/query.py#L53-L88
[ "def", "add_join_conditions", "(", "self", ",", "conditions", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "alias", "=", "self", ".", "get_initial_alias", "(", ")", "opts", "=", "self", ".", "get_meta", "(", ")", "for", "name", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "parts", "=", "name", ".", "split", "(", "LOOKUP_SEP", ")", "join_info", "=", "self", ".", "setup_joins", "(", "parts", ",", "opts", ",", "alias", ",", "allow_many", "=", "True", ")", "self", ".", "trim_joins", "(", "join_info", "[", "1", "]", ",", "join_info", "[", "3", "]", ",", "join_info", "[", "4", "]", ")", "target_table", "=", "join_info", "[", "3", "]", "[", "-", "1", "]", "field", "=", "join_info", "[", "1", "]", "[", "-", "1", "]", "join", "=", "self", ".", "alias_map", ".", "get", "(", "target_table", ")", "if", "not", "join", ":", "raise", "SuspiciousOperation", "(", "(", "'Cannot add an extra join condition for \"%s\", there\\'s no'", "' existing join to add it to.'", ")", "%", "target_table", ")", "# convert the Join object into a ConditionalJoin object, which", "# allows us to add the extra condition", "if", "not", "isinstance", "(", "join", ",", "ConditionalJoin", ")", ":", "self", ".", "alias_map", "[", "target_table", "]", "=", "ConditionalJoin", ".", "from_join", "(", "join", ")", "join", "=", "self", ".", "alias_map", "[", "target_table", "]", "join", ".", "add_condition", "(", "field", ",", "value", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresQuery.add_fields
Adds the given (model) fields to the select set. The field names are added in the order specified. This overrides the base class's add_fields method. This is called by the .values() or .values_list() method of the query set. It instructs the ORM to only select certain values. A lot of processing is neccesarry because it can be used to easily do joins. For example, `my_fk__name` pulls in the `name` field in foreign key `my_fk`. In our case, we want to be able to do `title__en`, where `title` is a HStoreField and `en` a key. This doesn't really involve a join. We iterate over the specified field names and filter out the ones that refer to HStoreField and compile it into an expression which is added to the list of to be selected fields using `self.add_select`.
psqlextra/query.py
def add_fields(self, field_names: List[str], allow_m2m: bool=True) -> bool: """ Adds the given (model) fields to the select set. The field names are added in the order specified. This overrides the base class's add_fields method. This is called by the .values() or .values_list() method of the query set. It instructs the ORM to only select certain values. A lot of processing is neccesarry because it can be used to easily do joins. For example, `my_fk__name` pulls in the `name` field in foreign key `my_fk`. In our case, we want to be able to do `title__en`, where `title` is a HStoreField and `en` a key. This doesn't really involve a join. We iterate over the specified field names and filter out the ones that refer to HStoreField and compile it into an expression which is added to the list of to be selected fields using `self.add_select`. """ alias = self.get_initial_alias() opts = self.get_meta() cols = [] for name in field_names: parts = name.split(LOOKUP_SEP) # it cannot be a special hstore thing if there's no __ in it if len(parts) > 1: column_name, hstore_key = parts[:2] is_hstore, field = self._is_hstore_field(column_name) if is_hstore: cols.append( HStoreColumn(self.model._meta.db_table or self.model.name, field, hstore_key) ) continue join_info = self.setup_joins(parts, opts, alias, allow_many=allow_m2m) targets, final_alias, joins = self.trim_joins( join_info[1], join_info[3], join_info[4] ) for target in targets: cols.append(target.get_col(final_alias)) if cols: self.set_select(cols)
def add_fields(self, field_names: List[str], allow_m2m: bool=True) -> bool: """ Adds the given (model) fields to the select set. The field names are added in the order specified. This overrides the base class's add_fields method. This is called by the .values() or .values_list() method of the query set. It instructs the ORM to only select certain values. A lot of processing is neccesarry because it can be used to easily do joins. For example, `my_fk__name` pulls in the `name` field in foreign key `my_fk`. In our case, we want to be able to do `title__en`, where `title` is a HStoreField and `en` a key. This doesn't really involve a join. We iterate over the specified field names and filter out the ones that refer to HStoreField and compile it into an expression which is added to the list of to be selected fields using `self.add_select`. """ alias = self.get_initial_alias() opts = self.get_meta() cols = [] for name in field_names: parts = name.split(LOOKUP_SEP) # it cannot be a special hstore thing if there's no __ in it if len(parts) > 1: column_name, hstore_key = parts[:2] is_hstore, field = self._is_hstore_field(column_name) if is_hstore: cols.append( HStoreColumn(self.model._meta.db_table or self.model.name, field, hstore_key) ) continue join_info = self.setup_joins(parts, opts, alias, allow_many=allow_m2m) targets, final_alias, joins = self.trim_joins( join_info[1], join_info[3], join_info[4] ) for target in targets: cols.append(target.get_col(final_alias)) if cols: self.set_select(cols)
[ "Adds", "the", "given", "(", "model", ")", "fields", "to", "the", "select", "set", ".", "The", "field", "names", "are", "added", "in", "the", "order", "specified", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/query.py#L90-L131
[ "def", "add_fields", "(", "self", ",", "field_names", ":", "List", "[", "str", "]", ",", "allow_m2m", ":", "bool", "=", "True", ")", "->", "bool", ":", "alias", "=", "self", ".", "get_initial_alias", "(", ")", "opts", "=", "self", ".", "get_meta", "(", ")", "cols", "=", "[", "]", "for", "name", "in", "field_names", ":", "parts", "=", "name", ".", "split", "(", "LOOKUP_SEP", ")", "# it cannot be a special hstore thing if there's no __ in it", "if", "len", "(", "parts", ")", ">", "1", ":", "column_name", ",", "hstore_key", "=", "parts", "[", ":", "2", "]", "is_hstore", ",", "field", "=", "self", ".", "_is_hstore_field", "(", "column_name", ")", "if", "is_hstore", ":", "cols", ".", "append", "(", "HStoreColumn", "(", "self", ".", "model", ".", "_meta", ".", "db_table", "or", "self", ".", "model", ".", "name", ",", "field", ",", "hstore_key", ")", ")", "continue", "join_info", "=", "self", ".", "setup_joins", "(", "parts", ",", "opts", ",", "alias", ",", "allow_many", "=", "allow_m2m", ")", "targets", ",", "final_alias", ",", "joins", "=", "self", ".", "trim_joins", "(", "join_info", "[", "1", "]", ",", "join_info", "[", "3", "]", ",", "join_info", "[", "4", "]", ")", "for", "target", "in", "targets", ":", "cols", ".", "append", "(", "target", ".", "get_col", "(", "final_alias", ")", ")", "if", "cols", ":", "self", ".", "set_select", "(", "cols", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresQuery._is_hstore_field
Gets whether the field with the specified name is a HStoreField. Returns A tuple of a boolean indicating whether the field with the specified name is a HStoreField, and the field instance.
psqlextra/query.py
def _is_hstore_field(self, field_name: str) -> Tuple[bool, Optional[models.Field]]: """Gets whether the field with the specified name is a HStoreField. Returns A tuple of a boolean indicating whether the field with the specified name is a HStoreField, and the field instance. """ field_instance = None for field in self.model._meta.local_concrete_fields: if field.name == field_name or field.column == field_name: field_instance = field break return isinstance(field_instance, HStoreField), field_instance
def _is_hstore_field(self, field_name: str) -> Tuple[bool, Optional[models.Field]]: """Gets whether the field with the specified name is a HStoreField. Returns A tuple of a boolean indicating whether the field with the specified name is a HStoreField, and the field instance. """ field_instance = None for field in self.model._meta.local_concrete_fields: if field.name == field_name or field.column == field_name: field_instance = field break return isinstance(field_instance, HStoreField), field_instance
[ "Gets", "whether", "the", "field", "with", "the", "specified", "name", "is", "a", "HStoreField", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/query.py#L133-L149
[ "def", "_is_hstore_field", "(", "self", ",", "field_name", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "Optional", "[", "models", ".", "Field", "]", "]", ":", "field_instance", "=", "None", "for", "field", "in", "self", ".", "model", ".", "_meta", ".", "local_concrete_fields", ":", "if", "field", ".", "name", "==", "field_name", "or", "field", ".", "column", "==", "field_name", ":", "field_instance", "=", "field", "break", "return", "isinstance", "(", "field_instance", ",", "HStoreField", ")", ",", "field_instance" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertQuery.values
Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. Update fields are fields that should be overwritten in case an update takes place rather than an insert. If we're dealing with a INSERT, these will not be used. Arguments: objs: The objects to apply this query to. insert_fields: The fields to use in the INSERT statement update_fields: The fields to only use in the UPDATE statement.
psqlextra/query.py
def values(self, objs: List, insert_fields: List, update_fields: List=[]): """Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. Update fields are fields that should be overwritten in case an update takes place rather than an insert. If we're dealing with a INSERT, these will not be used. Arguments: objs: The objects to apply this query to. insert_fields: The fields to use in the INSERT statement update_fields: The fields to only use in the UPDATE statement. """ self.insert_values(insert_fields, objs, raw=False) self.update_fields = update_fields
def values(self, objs: List, insert_fields: List, update_fields: List=[]): """Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. Update fields are fields that should be overwritten in case an update takes place rather than an insert. If we're dealing with a INSERT, these will not be used. Arguments: objs: The objects to apply this query to. insert_fields: The fields to use in the INSERT statement update_fields: The fields to only use in the UPDATE statement. """ self.insert_values(insert_fields, objs, raw=False) self.update_fields = update_fields
[ "Sets", "the", "values", "to", "be", "used", "in", "this", "query", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/query.py#L165-L189
[ "def", "values", "(", "self", ",", "objs", ":", "List", ",", "insert_fields", ":", "List", ",", "update_fields", ":", "List", "=", "[", "]", ")", ":", "self", ".", "insert_values", "(", "insert_fields", ",", "objs", ",", "raw", "=", "False", ")", "self", ".", "update_fields", "=", "update_fields" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin.create_model
Ran when a new model is created.
psqlextra/backend/hstore_required.py
def create_model(self, model): """Ran when a new model is created.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.add_field(model, field)
def create_model(self, model): """Ran when a new model is created.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.add_field(model, field)
[ "Ran", "when", "a", "new", "model", "is", "created", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L25-L32
[ "def", "create_model", "(", "self", ",", "model", ")", ":", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "not", "isinstance", "(", "field", ",", "HStoreField", ")", ":", "continue", "self", ".", "add_field", "(", "model", ",", "field", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin.delete_model
Ran when a model is being deleted.
psqlextra/backend/hstore_required.py
def delete_model(self, model): """Ran when a model is being deleted.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.remove_field(model, field)
def delete_model(self, model): """Ran when a model is being deleted.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.remove_field(model, field)
[ "Ran", "when", "a", "model", "is", "being", "deleted", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L34-L41
[ "def", "delete_model", "(", "self", ",", "model", ")", ":", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "not", "isinstance", "(", "field", ",", "HStoreField", ")", ":", "continue", "self", ".", "remove_field", "(", "model", ",", "field", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin.alter_db_table
Ran when the name of a model is changed.
psqlextra/backend/hstore_required.py
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for key in self._iterate_required_keys(field): self._rename_hstore_required( old_db_table, new_db_table, field, field, key )
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for key in self._iterate_required_keys(field): self._rename_hstore_required( old_db_table, new_db_table, field, field, key )
[ "Ran", "when", "the", "name", "of", "a", "model", "is", "changed", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L43-L57
[ "def", "alter_db_table", "(", "self", ",", "model", ",", "old_db_table", ",", "new_db_table", ")", ":", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "not", "isinstance", "(", "field", ",", "HStoreField", ")", ":", "continue", "for", "key", "in", "self", ".", "_iterate_required_keys", "(", "field", ")", ":", "self", ".", "_rename_hstore_required", "(", "old_db_table", ",", "new_db_table", ",", "field", ",", "field", ",", "key", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin.add_field
Ran when a field is added to a model.
psqlextra/backend/hstore_required.py
def add_field(self, model, field): """Ran when a field is added to a model.""" for key in self._iterate_required_keys(field): self._create_hstore_required( model._meta.db_table, field, key )
def add_field(self, model, field): """Ran when a field is added to a model.""" for key in self._iterate_required_keys(field): self._create_hstore_required( model._meta.db_table, field, key )
[ "Ran", "when", "a", "field", "is", "added", "to", "a", "model", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L59-L67
[ "def", "add_field", "(", "self", ",", "model", ",", "field", ")", ":", "for", "key", "in", "self", ".", "_iterate_required_keys", "(", "field", ")", ":", "self", ".", "_create_hstore_required", "(", "model", ".", "_meta", ".", "db_table", ",", "field", ",", "key", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin.remove_field
Ran when a field is removed from a model.
psqlextra/backend/hstore_required.py
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for key in self._iterate_required_keys(field): self._drop_hstore_required( model._meta.db_table, field, key )
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for key in self._iterate_required_keys(field): self._drop_hstore_required( model._meta.db_table, field, key )
[ "Ran", "when", "a", "field", "is", "removed", "from", "a", "model", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L69-L77
[ "def", "remove_field", "(", "self", ",", "model", ",", "field", ")", ":", "for", "key", "in", "self", ".", "_iterate_required_keys", "(", "field", ")", ":", "self", ".", "_drop_hstore_required", "(", "model", ".", "_meta", ".", "db_table", ",", "field", ",", "key", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin.alter_field
Ran when the configuration on a field changed.
psqlextra/backend/hstore_required.py
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstore: return old_required = getattr(old_field, 'required', []) or [] new_required = getattr(new_field, 'required', []) or [] # handle field renames before moving on if str(old_field.column) != str(new_field.column): for key in self._iterate_required_keys(old_field): self._rename_hstore_required( model._meta.db_table, model._meta.db_table, old_field, new_field, key ) # drop the constraints for keys that have been removed for key in old_required: if key not in new_required: self._drop_hstore_required( model._meta.db_table, old_field, key ) # create new constraints for keys that have been added for key in new_required: if key not in old_required: self._create_hstore_required( model._meta.db_table, new_field, key )
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstore: return old_required = getattr(old_field, 'required', []) or [] new_required = getattr(new_field, 'required', []) or [] # handle field renames before moving on if str(old_field.column) != str(new_field.column): for key in self._iterate_required_keys(old_field): self._rename_hstore_required( model._meta.db_table, model._meta.db_table, old_field, new_field, key ) # drop the constraints for keys that have been removed for key in old_required: if key not in new_required: self._drop_hstore_required( model._meta.db_table, old_field, key ) # create new constraints for keys that have been added for key in new_required: if key not in old_required: self._create_hstore_required( model._meta.db_table, new_field, key )
[ "Ran", "when", "the", "configuration", "on", "a", "field", "changed", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L79-L118
[ "def", "alter_field", "(", "self", ",", "model", ",", "old_field", ",", "new_field", ",", "strict", "=", "False", ")", ":", "is_old_field_hstore", "=", "isinstance", "(", "old_field", ",", "HStoreField", ")", "is_new_field_hstore", "=", "isinstance", "(", "new_field", ",", "HStoreField", ")", "if", "not", "is_old_field_hstore", "and", "not", "is_new_field_hstore", ":", "return", "old_required", "=", "getattr", "(", "old_field", ",", "'required'", ",", "[", "]", ")", "or", "[", "]", "new_required", "=", "getattr", "(", "new_field", ",", "'required'", ",", "[", "]", ")", "or", "[", "]", "# handle field renames before moving on", "if", "str", "(", "old_field", ".", "column", ")", "!=", "str", "(", "new_field", ".", "column", ")", ":", "for", "key", "in", "self", ".", "_iterate_required_keys", "(", "old_field", ")", ":", "self", ".", "_rename_hstore_required", "(", "model", ".", "_meta", ".", "db_table", ",", "model", ".", "_meta", ".", "db_table", ",", "old_field", ",", "new_field", ",", "key", ")", "# drop the constraints for keys that have been removed", "for", "key", "in", "old_required", ":", "if", "key", "not", "in", "new_required", ":", "self", ".", "_drop_hstore_required", "(", "model", ".", "_meta", ".", "db_table", ",", "old_field", ",", "key", ")", "# create new constraints for keys that have been added", "for", "key", "in", "new_required", ":", "if", "key", "not", "in", "old_required", ":", "self", ".", "_create_hstore_required", "(", "model", ".", "_meta", ".", "db_table", ",", "new_field", ",", "key", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin._create_hstore_required
Creates a REQUIRED CONSTRAINT for the specified hstore key.
psqlextra/backend/hstore_required.py
def _create_hstore_required(self, table_name, field, key): """Creates a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_create.format( name=self.quote_name(name), table=self.quote_name(table_name), field=self.quote_name(field.column), key=key ) self.execute(sql)
def _create_hstore_required(self, table_name, field, key): """Creates a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_create.format( name=self.quote_name(name), table=self.quote_name(table_name), field=self.quote_name(field.column), key=key ) self.execute(sql)
[ "Creates", "a", "REQUIRED", "CONSTRAINT", "for", "the", "specified", "hstore", "key", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L120-L132
[ "def", "_create_hstore_required", "(", "self", ",", "table_name", ",", "field", ",", "key", ")", ":", "name", "=", "self", ".", "_required_constraint_name", "(", "table_name", ",", "field", ",", "key", ")", "sql", "=", "self", ".", "sql_hstore_required_create", ".", "format", "(", "name", "=", "self", ".", "quote_name", "(", "name", ")", ",", "table", "=", "self", ".", "quote_name", "(", "table_name", ")", ",", "field", "=", "self", ".", "quote_name", "(", "field", ".", "column", ")", ",", "key", "=", "key", ")", "self", ".", "execute", "(", "sql", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin._rename_hstore_required
Renames an existing REQUIRED CONSTRAINT for the specified hstore key.
psqlextra/backend/hstore_required.py
def _rename_hstore_required(self, old_table_name, new_table_name, old_field, new_field, key): """Renames an existing REQUIRED CONSTRAINT for the specified hstore key.""" old_name = self._required_constraint_name( old_table_name, old_field, key) new_name = self._required_constraint_name( new_table_name, new_field, key) sql = self.sql_hstore_required_rename.format( table=self.quote_name(new_table_name), old_name=self.quote_name(old_name), new_name=self.quote_name(new_name) ) self.execute(sql)
def _rename_hstore_required(self, old_table_name, new_table_name, old_field, new_field, key): """Renames an existing REQUIRED CONSTRAINT for the specified hstore key.""" old_name = self._required_constraint_name( old_table_name, old_field, key) new_name = self._required_constraint_name( new_table_name, new_field, key) sql = self.sql_hstore_required_rename.format( table=self.quote_name(new_table_name), old_name=self.quote_name(old_name), new_name=self.quote_name(new_name) ) self.execute(sql)
[ "Renames", "an", "existing", "REQUIRED", "CONSTRAINT", "for", "the", "specified", "hstore", "key", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L134-L149
[ "def", "_rename_hstore_required", "(", "self", ",", "old_table_name", ",", "new_table_name", ",", "old_field", ",", "new_field", ",", "key", ")", ":", "old_name", "=", "self", ".", "_required_constraint_name", "(", "old_table_name", ",", "old_field", ",", "key", ")", "new_name", "=", "self", ".", "_required_constraint_name", "(", "new_table_name", ",", "new_field", ",", "key", ")", "sql", "=", "self", ".", "sql_hstore_required_rename", ".", "format", "(", "table", "=", "self", ".", "quote_name", "(", "new_table_name", ")", ",", "old_name", "=", "self", ".", "quote_name", "(", "old_name", ")", ",", "new_name", "=", "self", ".", "quote_name", "(", "new_name", ")", ")", "self", ".", "execute", "(", "sql", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin._drop_hstore_required
Drops a REQUIRED CONSTRAINT for the specified hstore key.
psqlextra/backend/hstore_required.py
def _drop_hstore_required(self, table_name, field, key): """Drops a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_drop.format( table=self.quote_name(table_name), name=self.quote_name(name) ) self.execute(sql)
def _drop_hstore_required(self, table_name, field, key): """Drops a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_drop.format( table=self.quote_name(table_name), name=self.quote_name(name) ) self.execute(sql)
[ "Drops", "a", "REQUIRED", "CONSTRAINT", "for", "the", "specified", "hstore", "key", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L151-L161
[ "def", "_drop_hstore_required", "(", "self", ",", "table_name", ",", "field", ",", "key", ")", ":", "name", "=", "self", ".", "_required_constraint_name", "(", "table_name", ",", "field", ",", "key", ")", "sql", "=", "self", ".", "sql_hstore_required_drop", ".", "format", "(", "table", "=", "self", ".", "quote_name", "(", "table_name", ")", ",", "name", "=", "self", ".", "quote_name", "(", "name", ")", ")", "self", ".", "execute", "(", "sql", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreRequiredSchemaEditorMixin._required_constraint_name
Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. Returns: The name for the UNIQUE index.
psqlextra/backend/hstore_required.py
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. Returns: The name for the UNIQUE index. """ return '{table}_{field}_required_{postfix}'.format( table=table, field=field.column, postfix=key )
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. Returns: The name for the UNIQUE index. """ return '{table}_{field}_required_{postfix}'.format( table=table, field=field.column, postfix=key )
[ "Gets", "the", "name", "for", "a", "CONSTRAINT", "that", "applies", "to", "a", "single", "hstore", "key", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_required.py#L164-L189
[ "def", "_required_constraint_name", "(", "table", ":", "str", ",", "field", ",", "key", ")", ":", "return", "'{table}_{field}_required_{postfix}'", ".", "format", "(", "table", "=", "table", ",", "field", "=", "field", ".", "column", ",", "postfix", "=", "key", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
ConditionalUniqueIndex.create_sql
Creates the actual SQL used when applying the migration.
psqlextra/indexes/conditional_unique_index.py
def create_sql(self, model, schema_editor, using=''): """Creates the actual SQL used when applying the migration.""" if django.VERSION >= (2, 0): statement = super().create_sql(model, schema_editor, using) statement.template = self.sql_create_index statement.parts['condition'] = self.condition return statement else: sql_create_index = self.sql_create_index sql_parameters = { **Index.get_sql_create_template_values(self, model, schema_editor, using), 'condition': self.condition } return sql_create_index % sql_parameters
def create_sql(self, model, schema_editor, using=''): """Creates the actual SQL used when applying the migration.""" if django.VERSION >= (2, 0): statement = super().create_sql(model, schema_editor, using) statement.template = self.sql_create_index statement.parts['condition'] = self.condition return statement else: sql_create_index = self.sql_create_index sql_parameters = { **Index.get_sql_create_template_values(self, model, schema_editor, using), 'condition': self.condition } return sql_create_index % sql_parameters
[ "Creates", "the", "actual", "SQL", "used", "when", "applying", "the", "migration", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/indexes/conditional_unique_index.py#L26-L39
[ "def", "create_sql", "(", "self", ",", "model", ",", "schema_editor", ",", "using", "=", "''", ")", ":", "if", "django", ".", "VERSION", ">=", "(", "2", ",", "0", ")", ":", "statement", "=", "super", "(", ")", ".", "create_sql", "(", "model", ",", "schema_editor", ",", "using", ")", "statement", ".", "template", "=", "self", ".", "sql_create_index", "statement", ".", "parts", "[", "'condition'", "]", "=", "self", ".", "condition", "return", "statement", "else", ":", "sql_create_index", "=", "self", ".", "sql_create_index", "sql_parameters", "=", "{", "*", "*", "Index", ".", "get_sql_create_template_values", "(", "self", ",", "model", ",", "schema_editor", ",", "using", ")", ",", "'condition'", ":", "self", ".", "condition", "}", "return", "sql_create_index", "%", "sql_parameters" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
ConditionalUniqueIndex.deconstruct
Serializes the :see:ConditionalUniqueIndex for the migrations file.
psqlextra/indexes/conditional_unique_index.py
def deconstruct(self): """Serializes the :see:ConditionalUniqueIndex for the migrations file.""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) path = path.replace('django.db.models.indexes', 'django.db.models') return path, (), {'fields': self.fields, 'name': self.name, 'condition': self.condition}
def deconstruct(self): """Serializes the :see:ConditionalUniqueIndex for the migrations file.""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) path = path.replace('django.db.models.indexes', 'django.db.models') return path, (), {'fields': self.fields, 'name': self.name, 'condition': self.condition}
[ "Serializes", "the", ":", "see", ":", "ConditionalUniqueIndex", "for", "the", "migrations", "file", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/indexes/conditional_unique_index.py#L41-L45
[ "def", "deconstruct", "(", "self", ")", ":", "path", "=", "'%s.%s'", "%", "(", "self", ".", "__class__", ".", "__module__", ",", "self", ".", "__class__", ".", "__name__", ")", "path", "=", "path", ".", "replace", "(", "'django.db.models.indexes'", ",", "'django.db.models'", ")", "return", "path", ",", "(", ")", ",", "{", "'fields'", ":", "self", ".", "fields", ",", "'name'", ":", "self", ".", "name", ",", "'condition'", ":", "self", ".", "condition", "}" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
create_command
Creates a custom setup.py command.
setup.py
def create_command(text, commands): """Creates a custom setup.py command.""" class CustomCommand(BaseCommand): description = text def run(self): for cmd in commands: subprocess.check_call(cmd) return CustomCommand
def create_command(text, commands): """Creates a custom setup.py command.""" class CustomCommand(BaseCommand): description = text def run(self): for cmd in commands: subprocess.check_call(cmd) return CustomCommand
[ "Creates", "a", "custom", "setup", ".", "py", "command", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/setup.py#L18-L28
[ "def", "create_command", "(", "text", ",", "commands", ")", ":", "class", "CustomCommand", "(", "BaseCommand", ")", ":", "description", "=", "text", "def", "run", "(", "self", ")", ":", "for", "cmd", "in", "commands", ":", "subprocess", ".", "check_call", "(", "cmd", ")", "return", "CustomCommand" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
_get_backend_base
Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base upon. As long as the specified base eventually also has the PostgreSQL back-end as a base, then everything should work as intended.
psqlextra/backend/base.py
def _get_backend_base(): """Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base upon. As long as the specified base eventually also has the PostgreSQL back-end as a base, then everything should work as intended. """ base_class_name = getattr( settings, 'POSTGRES_EXTRA_DB_BACKEND_BASE', 'django.db.backends.postgresql' ) base_class_module = importlib.import_module(base_class_name + '.base') base_class = getattr(base_class_module, 'DatabaseWrapper', None) if not base_class: raise ImproperlyConfigured(( '\'%s\' is not a valid database back-end.' ' The module does not define a DatabaseWrapper class.' ' Check the value of POSTGRES_EXTRA_DB_BACKEND_BASE.' ) % base_class_name) if isinstance(base_class, Psycopg2DatabaseWrapper): raise ImproperlyConfigured(( '\'%s\' is not a valid database back-end.' ' It does inherit from the PostgreSQL back-end.' ' Check the value of POSTGRES_EXTRA_DB_BACKEND_BASE.' ) % base_class_name) return base_class
def _get_backend_base(): """Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base upon. As long as the specified base eventually also has the PostgreSQL back-end as a base, then everything should work as intended. """ base_class_name = getattr( settings, 'POSTGRES_EXTRA_DB_BACKEND_BASE', 'django.db.backends.postgresql' ) base_class_module = importlib.import_module(base_class_name + '.base') base_class = getattr(base_class_module, 'DatabaseWrapper', None) if not base_class: raise ImproperlyConfigured(( '\'%s\' is not a valid database back-end.' ' The module does not define a DatabaseWrapper class.' ' Check the value of POSTGRES_EXTRA_DB_BACKEND_BASE.' ) % base_class_name) if isinstance(base_class, Psycopg2DatabaseWrapper): raise ImproperlyConfigured(( '\'%s\' is not a valid database back-end.' ' It does inherit from the PostgreSQL back-end.' ' Check the value of POSTGRES_EXTRA_DB_BACKEND_BASE.' ) % base_class_name) return base_class
[ "Gets", "the", "base", "class", "for", "the", "custom", "database", "back", "-", "end", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L16-L51
[ "def", "_get_backend_base", "(", ")", ":", "base_class_name", "=", "getattr", "(", "settings", ",", "'POSTGRES_EXTRA_DB_BACKEND_BASE'", ",", "'django.db.backends.postgresql'", ")", "base_class_module", "=", "importlib", ".", "import_module", "(", "base_class_name", "+", "'.base'", ")", "base_class", "=", "getattr", "(", "base_class_module", ",", "'DatabaseWrapper'", ",", "None", ")", "if", "not", "base_class", ":", "raise", "ImproperlyConfigured", "(", "(", "'\\'%s\\' is not a valid database back-end.'", "' The module does not define a DatabaseWrapper class.'", "' Check the value of POSTGRES_EXTRA_DB_BACKEND_BASE.'", ")", "%", "base_class_name", ")", "if", "isinstance", "(", "base_class", ",", "Psycopg2DatabaseWrapper", ")", ":", "raise", "ImproperlyConfigured", "(", "(", "'\\'%s\\' is not a valid database back-end.'", "' It does inherit from the PostgreSQL back-end.'", "' Check the value of POSTGRES_EXTRA_DB_BACKEND_BASE.'", ")", "%", "base_class_name", ")", "return", "base_class" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
SchemaEditor.create_model
Ran when a new model is created.
psqlextra/backend/base.py
def create_model(self, model): """Ran when a new model is created.""" super().create_model(model) for mixin in self.post_processing_mixins: mixin.create_model(model)
def create_model(self, model): """Ran when a new model is created.""" super().create_model(model) for mixin in self.post_processing_mixins: mixin.create_model(model)
[ "Ran", "when", "a", "new", "model", "is", "created", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L81-L87
[ "def", "create_model", "(", "self", ",", "model", ")", ":", "super", "(", ")", ".", "create_model", "(", "model", ")", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "create_model", "(", "model", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
SchemaEditor.delete_model
Ran when a model is being deleted.
psqlextra/backend/base.py
def delete_model(self, model): """Ran when a model is being deleted.""" for mixin in self.post_processing_mixins: mixin.delete_model(model) super().delete_model(model)
def delete_model(self, model): """Ran when a model is being deleted.""" for mixin in self.post_processing_mixins: mixin.delete_model(model) super().delete_model(model)
[ "Ran", "when", "a", "model", "is", "being", "deleted", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L89-L95
[ "def", "delete_model", "(", "self", ",", "model", ")", ":", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "delete_model", "(", "model", ")", "super", "(", ")", ".", "delete_model", "(", "model", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
SchemaEditor.alter_db_table
Ran when the name of a model is changed.
psqlextra/backend/base.py
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" super(SchemaEditor, self).alter_db_table( model, old_db_table, new_db_table ) for mixin in self.post_processing_mixins: mixin.alter_db_table( model, old_db_table, new_db_table )
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" super(SchemaEditor, self).alter_db_table( model, old_db_table, new_db_table ) for mixin in self.post_processing_mixins: mixin.alter_db_table( model, old_db_table, new_db_table )
[ "Ran", "when", "the", "name", "of", "a", "model", "is", "changed", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L97-L109
[ "def", "alter_db_table", "(", "self", ",", "model", ",", "old_db_table", ",", "new_db_table", ")", ":", "super", "(", "SchemaEditor", ",", "self", ")", ".", "alter_db_table", "(", "model", ",", "old_db_table", ",", "new_db_table", ")", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "alter_db_table", "(", "model", ",", "old_db_table", ",", "new_db_table", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
SchemaEditor.add_field
Ran when a field is added to a model.
psqlextra/backend/base.py
def add_field(self, model, field): """Ran when a field is added to a model.""" super(SchemaEditor, self).add_field(model, field) for mixin in self.post_processing_mixins: mixin.add_field(model, field)
def add_field(self, model, field): """Ran when a field is added to a model.""" super(SchemaEditor, self).add_field(model, field) for mixin in self.post_processing_mixins: mixin.add_field(model, field)
[ "Ran", "when", "a", "field", "is", "added", "to", "a", "model", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L111-L117
[ "def", "add_field", "(", "self", ",", "model", ",", "field", ")", ":", "super", "(", "SchemaEditor", ",", "self", ")", ".", "add_field", "(", "model", ",", "field", ")", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "add_field", "(", "model", ",", "field", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
SchemaEditor.remove_field
Ran when a field is removed from a model.
psqlextra/backend/base.py
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for mixin in self.post_processing_mixins: mixin.remove_field(model, field) super(SchemaEditor, self).remove_field(model, field)
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for mixin in self.post_processing_mixins: mixin.remove_field(model, field) super(SchemaEditor, self).remove_field(model, field)
[ "Ran", "when", "a", "field", "is", "removed", "from", "a", "model", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L119-L125
[ "def", "remove_field", "(", "self", ",", "model", ",", "field", ")", ":", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "remove_field", "(", "model", ",", "field", ")", "super", "(", "SchemaEditor", ",", "self", ")", ".", "remove_field", "(", "model", ",", "field", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
SchemaEditor.alter_field
Ran when the configuration on a field changed.
psqlextra/backend/base.py
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" super(SchemaEditor, self).alter_field( model, old_field, new_field, strict ) for mixin in self.post_processing_mixins: mixin.alter_field( model, old_field, new_field, strict )
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" super(SchemaEditor, self).alter_field( model, old_field, new_field, strict ) for mixin in self.post_processing_mixins: mixin.alter_field( model, old_field, new_field, strict )
[ "Ran", "when", "the", "configuration", "on", "a", "field", "changed", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L127-L137
[ "def", "alter_field", "(", "self", ",", "model", ",", "old_field", ",", "new_field", ",", "strict", "=", "False", ")", ":", "super", "(", "SchemaEditor", ",", "self", ")", ".", "alter_field", "(", "model", ",", "old_field", ",", "new_field", ",", "strict", ")", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "alter_field", "(", "model", ",", "old_field", ",", "new_field", ",", "strict", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
DatabaseWrapper.prepare_database
Ran to prepare the configured database. This is where we enable the `hstore` extension if it wasn't enabled yet.
psqlextra/backend/base.py
def prepare_database(self): """Ran to prepare the configured database. This is where we enable the `hstore` extension if it wasn't enabled yet.""" super().prepare_database() with self.cursor() as cursor: try: cursor.execute('CREATE EXTENSION IF NOT EXISTS hstore') except ProgrammingError: # permission denied logger.warning( 'Failed to create "hstore" extension. ' 'Tables with hstore columns may fail to migrate. ' 'If hstore is needed, make sure you are connected ' 'to the database as a superuser ' 'or add the extension manually.', exc_info=True)
def prepare_database(self): """Ran to prepare the configured database. This is where we enable the `hstore` extension if it wasn't enabled yet.""" super().prepare_database() with self.cursor() as cursor: try: cursor.execute('CREATE EXTENSION IF NOT EXISTS hstore') except ProgrammingError: # permission denied logger.warning( 'Failed to create "hstore" extension. ' 'Tables with hstore columns may fail to migrate. ' 'If hstore is needed, make sure you are connected ' 'to the database as a superuser ' 'or add the extension manually.', exc_info=True)
[ "Ran", "to", "prepare", "the", "configured", "database", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L149-L166
[ "def", "prepare_database", "(", "self", ")", ":", "super", "(", ")", ".", "prepare_database", "(", ")", "with", "self", ".", "cursor", "(", ")", "as", "cursor", ":", "try", ":", "cursor", ".", "execute", "(", "'CREATE EXTENSION IF NOT EXISTS hstore'", ")", "except", "ProgrammingError", ":", "# permission denied", "logger", ".", "warning", "(", "'Failed to create \"hstore\" extension. '", "'Tables with hstore columns may fail to migrate. '", "'If hstore is needed, make sure you are connected '", "'to the database as a superuser '", "'or add the extension manually.'", ",", "exc_info", "=", "True", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreField.get_prep_value
Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea.
psqlextra/fields/hstore_field.py
def get_prep_value(self, value): """Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea.""" value = Field.get_prep_value(self, value) if isinstance(value, dict): prep_value = {} for key, val in value.items(): if isinstance(val, Expression): prep_value[key] = val elif val is not None: prep_value[key] = str(val) else: prep_value[key] = val value = prep_value if isinstance(value, list): value = [str(item) for item in value] return value
def get_prep_value(self, value): """Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea.""" value = Field.get_prep_value(self, value) if isinstance(value, dict): prep_value = {} for key, val in value.items(): if isinstance(val, Expression): prep_value[key] = val elif val is not None: prep_value[key] = str(val) else: prep_value[key] = val value = prep_value if isinstance(value, list): value = [str(item) for item in value] return value
[ "Override", "the", "base", "class", "so", "it", "doesn", "t", "cast", "all", "values", "to", "strings", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/fields/hstore_field.py#L27-L51
[ "def", "get_prep_value", "(", "self", ",", "value", ")", ":", "value", "=", "Field", ".", "get_prep_value", "(", "self", ",", "value", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "prep_value", "=", "{", "}", "for", "key", ",", "val", "in", "value", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "Expression", ")", ":", "prep_value", "[", "key", "]", "=", "val", "elif", "val", "is", "not", "None", ":", "prep_value", "[", "key", "]", "=", "str", "(", "val", ")", "else", ":", "prep_value", "[", "key", "]", "=", "val", "value", "=", "prep_value", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "str", "(", "item", ")", "for", "item", "in", "value", "]", "return", "value" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreField.deconstruct
Gets the values to pass to :see:__init__ when re-creating this object.
psqlextra/fields/hstore_field.py
def deconstruct(self): """Gets the values to pass to :see:__init__ when re-creating this object.""" name, path, args, kwargs = super( HStoreField, self).deconstruct() if self.uniqueness is not None: kwargs['uniqueness'] = self.uniqueness if self.required is not None: kwargs['required'] = self.required return name, path, args, kwargs
def deconstruct(self): """Gets the values to pass to :see:__init__ when re-creating this object.""" name, path, args, kwargs = super( HStoreField, self).deconstruct() if self.uniqueness is not None: kwargs['uniqueness'] = self.uniqueness if self.required is not None: kwargs['required'] = self.required return name, path, args, kwargs
[ "Gets", "the", "values", "to", "pass", "to", ":", "see", ":", "__init__", "when", "re", "-", "creating", "this", "object", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/fields/hstore_field.py#L53-L66
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", "HStoreField", ",", "self", ")", ".", "deconstruct", "(", ")", "if", "self", ".", "uniqueness", "is", "not", "None", ":", "kwargs", "[", "'uniqueness'", "]", "=", "self", ".", "uniqueness", "if", "self", ".", "required", "is", "not", "None", ":", "kwargs", "[", "'required'", "]", "=", "self", ".", "required", "return", "name", ",", "path", ",", "args", ",", "kwargs" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresReturningUpdateCompiler._prepare_query_values
Extra prep on query values by converting dictionaries into :see:HStoreValue expressions. This allows putting expressions in a dictionary. The :see:HStoreValue will take care of resolving the expressions inside the dictionary.
psqlextra/compiler.py
def _prepare_query_values(self): """Extra prep on query values by converting dictionaries into :see:HStoreValue expressions. This allows putting expressions in a dictionary. The :see:HStoreValue will take care of resolving the expressions inside the dictionary.""" new_query_values = [] for field, model, val in self.query.values: if isinstance(val, dict): val = HStoreValue(val) new_query_values.append(( field, model, val )) self.query.values = new_query_values
def _prepare_query_values(self): """Extra prep on query values by converting dictionaries into :see:HStoreValue expressions. This allows putting expressions in a dictionary. The :see:HStoreValue will take care of resolving the expressions inside the dictionary.""" new_query_values = [] for field, model, val in self.query.values: if isinstance(val, dict): val = HStoreValue(val) new_query_values.append(( field, model, val )) self.query.values = new_query_values
[ "Extra", "prep", "on", "query", "values", "by", "converting", "dictionaries", "into", ":", "see", ":", "HStoreValue", "expressions", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L25-L44
[ "def", "_prepare_query_values", "(", "self", ")", ":", "new_query_values", "=", "[", "]", "for", "field", ",", "model", ",", "val", "in", "self", ".", "query", ".", "values", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "val", "=", "HStoreValue", "(", "val", ")", "new_query_values", ".", "append", "(", "(", "field", ",", "model", ",", "val", ")", ")", "self", ".", "query", ".", "values", "=", "new_query_values" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresReturningUpdateCompiler._form_returning
Builds the RETURNING part of the query.
psqlextra/compiler.py
def _form_returning(self): """Builds the RETURNING part of the query.""" qn = self.connection.ops.quote_name return ' RETURNING %s' % qn(self.query.model._meta.pk.attname)
def _form_returning(self): """Builds the RETURNING part of the query.""" qn = self.connection.ops.quote_name return ' RETURNING %s' % qn(self.query.model._meta.pk.attname)
[ "Builds", "the", "RETURNING", "part", "of", "the", "query", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L46-L50
[ "def", "_form_returning", "(", "self", ")", ":", "qn", "=", "self", ".", "connection", ".", "ops", ".", "quote_name", "return", "' RETURNING %s'", "%", "qn", "(", "self", ".", "query", ".", "model", ".", "_meta", ".", "pk", ".", "attname", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler.as_sql
Builds the SQL INSERT statement.
psqlextra/compiler.py
def as_sql(self, return_id=False): """Builds the SQL INSERT statement.""" queries = [ self._rewrite_insert(sql, params, return_id) for sql, params in super().as_sql() ] return queries
def as_sql(self, return_id=False): """Builds the SQL INSERT statement.""" queries = [ self._rewrite_insert(sql, params, return_id) for sql, params in super().as_sql() ] return queries
[ "Builds", "the", "SQL", "INSERT", "statement", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L62-L70
[ "def", "as_sql", "(", "self", ",", "return_id", "=", "False", ")", ":", "queries", "=", "[", "self", ".", "_rewrite_insert", "(", "sql", ",", "params", ",", "return_id", ")", "for", "sql", ",", "params", "in", "super", "(", ")", ".", "as_sql", "(", ")", "]", "return", "queries" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._rewrite_insert
Rewrites a formed SQL INSERT query to include the ON CONFLICT clause. Arguments: sql: The SQL INSERT query to rewrite. params: The parameters passed to the query. returning: What to put in the `RETURNING` clause of the resulting query. Returns: A tuple of the rewritten SQL query and new params.
psqlextra/compiler.py
def _rewrite_insert(self, sql, params, return_id=False): """Rewrites a formed SQL INSERT query to include the ON CONFLICT clause. Arguments: sql: The SQL INSERT query to rewrite. params: The parameters passed to the query. returning: What to put in the `RETURNING` clause of the resulting query. Returns: A tuple of the rewritten SQL query and new params. """ returning = self.qn(self.query.model._meta.pk.attname) if return_id else '*' if self.query.conflict_action.value == 'UPDATE': return self._rewrite_insert_update(sql, params, returning) elif self.query.conflict_action.value == 'NOTHING': return self._rewrite_insert_nothing(sql, params, returning) raise SuspiciousOperation(( '%s is not a valid conflict action, specify ' 'ConflictAction.UPDATE or ConflictAction.NOTHING.' ) % str(self.query.conflict_action))
def _rewrite_insert(self, sql, params, return_id=False): """Rewrites a formed SQL INSERT query to include the ON CONFLICT clause. Arguments: sql: The SQL INSERT query to rewrite. params: The parameters passed to the query. returning: What to put in the `RETURNING` clause of the resulting query. Returns: A tuple of the rewritten SQL query and new params. """ returning = self.qn(self.query.model._meta.pk.attname) if return_id else '*' if self.query.conflict_action.value == 'UPDATE': return self._rewrite_insert_update(sql, params, returning) elif self.query.conflict_action.value == 'NOTHING': return self._rewrite_insert_nothing(sql, params, returning) raise SuspiciousOperation(( '%s is not a valid conflict action, specify ' 'ConflictAction.UPDATE or ConflictAction.NOTHING.' ) % str(self.query.conflict_action))
[ "Rewrites", "a", "formed", "SQL", "INSERT", "query", "to", "include", "the", "ON", "CONFLICT", "clause", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L89-L118
[ "def", "_rewrite_insert", "(", "self", ",", "sql", ",", "params", ",", "return_id", "=", "False", ")", ":", "returning", "=", "self", ".", "qn", "(", "self", ".", "query", ".", "model", ".", "_meta", ".", "pk", ".", "attname", ")", "if", "return_id", "else", "'*'", "if", "self", ".", "query", ".", "conflict_action", ".", "value", "==", "'UPDATE'", ":", "return", "self", ".", "_rewrite_insert_update", "(", "sql", ",", "params", ",", "returning", ")", "elif", "self", ".", "query", ".", "conflict_action", ".", "value", "==", "'NOTHING'", ":", "return", "self", ".", "_rewrite_insert_nothing", "(", "sql", ",", "params", ",", "returning", ")", "raise", "SuspiciousOperation", "(", "(", "'%s is not a valid conflict action, specify '", "'ConflictAction.UPDATE or ConflictAction.NOTHING.'", ")", "%", "str", "(", "self", ".", "query", ".", "conflict_action", ")", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._rewrite_insert_update
Rewrites a formed SQL INSERT query to include the ON CONFLICT DO UPDATE clause.
psqlextra/compiler.py
def _rewrite_insert_update(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO UPDATE clause.""" update_columns = ', '.join([ '{0} = EXCLUDED.{0}'.format(self.qn(field.column)) for field in self.query.update_fields ]) # build the conflict target, the columns to watch # for conflicts conflict_target = self._build_conflict_target() index_predicate = self.query.index_predicate sql_template = ( '{insert} ON CONFLICT {conflict_target} DO UPDATE ' 'SET {update_columns} RETURNING {returning}' ) if index_predicate: sql_template = ( '{insert} ON CONFLICT {conflict_target} WHERE {index_predicate} DO UPDATE ' 'SET {update_columns} RETURNING {returning}' ) return ( sql_template.format( insert=sql, conflict_target=conflict_target, update_columns=update_columns, returning=returning, index_predicate=index_predicate, ), params )
def _rewrite_insert_update(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO UPDATE clause.""" update_columns = ', '.join([ '{0} = EXCLUDED.{0}'.format(self.qn(field.column)) for field in self.query.update_fields ]) # build the conflict target, the columns to watch # for conflicts conflict_target = self._build_conflict_target() index_predicate = self.query.index_predicate sql_template = ( '{insert} ON CONFLICT {conflict_target} DO UPDATE ' 'SET {update_columns} RETURNING {returning}' ) if index_predicate: sql_template = ( '{insert} ON CONFLICT {conflict_target} WHERE {index_predicate} DO UPDATE ' 'SET {update_columns} RETURNING {returning}' ) return ( sql_template.format( insert=sql, conflict_target=conflict_target, update_columns=update_columns, returning=returning, index_predicate=index_predicate, ), params )
[ "Rewrites", "a", "formed", "SQL", "INSERT", "query", "to", "include", "the", "ON", "CONFLICT", "DO", "UPDATE", "clause", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L120-L155
[ "def", "_rewrite_insert_update", "(", "self", ",", "sql", ",", "params", ",", "returning", ")", ":", "update_columns", "=", "', '", ".", "join", "(", "[", "'{0} = EXCLUDED.{0}'", ".", "format", "(", "self", ".", "qn", "(", "field", ".", "column", ")", ")", "for", "field", "in", "self", ".", "query", ".", "update_fields", "]", ")", "# build the conflict target, the columns to watch", "# for conflicts", "conflict_target", "=", "self", ".", "_build_conflict_target", "(", ")", "index_predicate", "=", "self", ".", "query", ".", "index_predicate", "sql_template", "=", "(", "'{insert} ON CONFLICT {conflict_target} DO UPDATE '", "'SET {update_columns} RETURNING {returning}'", ")", "if", "index_predicate", ":", "sql_template", "=", "(", "'{insert} ON CONFLICT {conflict_target} WHERE {index_predicate} DO UPDATE '", "'SET {update_columns} RETURNING {returning}'", ")", "return", "(", "sql_template", ".", "format", "(", "insert", "=", "sql", ",", "conflict_target", "=", "conflict_target", ",", "update_columns", "=", "update_columns", ",", "returning", "=", "returning", ",", "index_predicate", "=", "index_predicate", ",", ")", ",", "params", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._rewrite_insert_nothing
Rewrites a formed SQL INSERT query to include the ON CONFLICT DO NOTHING clause.
psqlextra/compiler.py
def _rewrite_insert_nothing(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO NOTHING clause.""" # build the conflict target, the columns to watch # for conflicts conflict_target = self._build_conflict_target() where_clause = ' AND '.join([ '{0} = %s'.format(self._format_field_name(field_name)) for field_name in self.query.conflict_target ]) where_clause_params = [ self._format_field_value(field_name) for field_name in self.query.conflict_target ] params = params + tuple(where_clause_params) # this looks complicated, and it is, but it is for a reason... a normal # ON CONFLICT DO NOTHING doesn't return anything if the row already exists # so we do DO UPDATE instead that never executes to lock the row, and then # select from the table in case we're dealing with an existing row.. return ( ( 'WITH insdata AS (' '{insert} ON CONFLICT {conflict_target} DO UPDATE' ' SET {pk_column} = NULL WHERE FALSE RETURNING {returning})' ' SELECT * FROM insdata UNION ALL' ' SELECT {returning} FROM {table} WHERE {where_clause} LIMIT 1;' ).format( insert=sql, conflict_target=conflict_target, pk_column=self.qn(self.query.model._meta.pk.column), returning=returning, table=self.query.objs[0]._meta.db_table, where_clause=where_clause ), params )
def _rewrite_insert_nothing(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO NOTHING clause.""" # build the conflict target, the columns to watch # for conflicts conflict_target = self._build_conflict_target() where_clause = ' AND '.join([ '{0} = %s'.format(self._format_field_name(field_name)) for field_name in self.query.conflict_target ]) where_clause_params = [ self._format_field_value(field_name) for field_name in self.query.conflict_target ] params = params + tuple(where_clause_params) # this looks complicated, and it is, but it is for a reason... a normal # ON CONFLICT DO NOTHING doesn't return anything if the row already exists # so we do DO UPDATE instead that never executes to lock the row, and then # select from the table in case we're dealing with an existing row.. return ( ( 'WITH insdata AS (' '{insert} ON CONFLICT {conflict_target} DO UPDATE' ' SET {pk_column} = NULL WHERE FALSE RETURNING {returning})' ' SELECT * FROM insdata UNION ALL' ' SELECT {returning} FROM {table} WHERE {where_clause} LIMIT 1;' ).format( insert=sql, conflict_target=conflict_target, pk_column=self.qn(self.query.model._meta.pk.column), returning=returning, table=self.query.objs[0]._meta.db_table, where_clause=where_clause ), params )
[ "Rewrites", "a", "formed", "SQL", "INSERT", "query", "to", "include", "the", "ON", "CONFLICT", "DO", "NOTHING", "clause", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L157-L197
[ "def", "_rewrite_insert_nothing", "(", "self", ",", "sql", ",", "params", ",", "returning", ")", ":", "# build the conflict target, the columns to watch", "# for conflicts", "conflict_target", "=", "self", ".", "_build_conflict_target", "(", ")", "where_clause", "=", "' AND '", ".", "join", "(", "[", "'{0} = %s'", ".", "format", "(", "self", ".", "_format_field_name", "(", "field_name", ")", ")", "for", "field_name", "in", "self", ".", "query", ".", "conflict_target", "]", ")", "where_clause_params", "=", "[", "self", ".", "_format_field_value", "(", "field_name", ")", "for", "field_name", "in", "self", ".", "query", ".", "conflict_target", "]", "params", "=", "params", "+", "tuple", "(", "where_clause_params", ")", "# this looks complicated, and it is, but it is for a reason... a normal", "# ON CONFLICT DO NOTHING doesn't return anything if the row already exists", "# so we do DO UPDATE instead that never executes to lock the row, and then", "# select from the table in case we're dealing with an existing row..", "return", "(", "(", "'WITH insdata AS ('", "'{insert} ON CONFLICT {conflict_target} DO UPDATE'", "' SET {pk_column} = NULL WHERE FALSE RETURNING {returning})'", "' SELECT * FROM insdata UNION ALL'", "' SELECT {returning} FROM {table} WHERE {where_clause} LIMIT 1;'", ")", ".", "format", "(", "insert", "=", "sql", ",", "conflict_target", "=", "conflict_target", ",", "pk_column", "=", "self", ".", "qn", "(", "self", ".", "query", ".", "model", ".", "_meta", ".", "pk", ".", "column", ")", ",", "returning", "=", "returning", ",", "table", "=", "self", ".", "query", ".", "objs", "[", "0", "]", ".", "_meta", ".", "db_table", ",", "where_clause", "=", "where_clause", ")", ",", "params", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._build_conflict_target
Builds the `conflict_target` for the ON CONFLICT clause.
psqlextra/compiler.py
def _build_conflict_target(self): """Builds the `conflict_target` for the ON CONFLICT clause.""" conflict_target = [] if not isinstance(self.query.conflict_target, list): raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' 'a list of column names, or tuples with column ' 'names and hstore key.' ) % str(self.query.conflict_target)) def _assert_valid_field(field_name): field_name = self._normalize_field_name(field_name) if self._get_model_field(field_name): return raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' 'a list of column names, or tuples with column ' 'names and hstore key.' ) % str(field_name)) for field_name in self.query.conflict_target: _assert_valid_field(field_name) # special handling for hstore keys if isinstance(field_name, tuple): conflict_target.append( '(%s->\'%s\')' % ( self._format_field_name(field_name), field_name[1] ) ) else: conflict_target.append( self._format_field_name(field_name)) return '(%s)' % ','.join(conflict_target)
def _build_conflict_target(self): """Builds the `conflict_target` for the ON CONFLICT clause.""" conflict_target = [] if not isinstance(self.query.conflict_target, list): raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' 'a list of column names, or tuples with column ' 'names and hstore key.' ) % str(self.query.conflict_target)) def _assert_valid_field(field_name): field_name = self._normalize_field_name(field_name) if self._get_model_field(field_name): return raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' 'a list of column names, or tuples with column ' 'names and hstore key.' ) % str(field_name)) for field_name in self.query.conflict_target: _assert_valid_field(field_name) # special handling for hstore keys if isinstance(field_name, tuple): conflict_target.append( '(%s->\'%s\')' % ( self._format_field_name(field_name), field_name[1] ) ) else: conflict_target.append( self._format_field_name(field_name)) return '(%s)' % ','.join(conflict_target)
[ "Builds", "the", "conflict_target", "for", "the", "ON", "CONFLICT", "clause", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L199-L238
[ "def", "_build_conflict_target", "(", "self", ")", ":", "conflict_target", "=", "[", "]", "if", "not", "isinstance", "(", "self", ".", "query", ".", "conflict_target", ",", "list", ")", ":", "raise", "SuspiciousOperation", "(", "(", "'%s is not a valid conflict target, specify '", "'a list of column names, or tuples with column '", "'names and hstore key.'", ")", "%", "str", "(", "self", ".", "query", ".", "conflict_target", ")", ")", "def", "_assert_valid_field", "(", "field_name", ")", ":", "field_name", "=", "self", ".", "_normalize_field_name", "(", "field_name", ")", "if", "self", ".", "_get_model_field", "(", "field_name", ")", ":", "return", "raise", "SuspiciousOperation", "(", "(", "'%s is not a valid conflict target, specify '", "'a list of column names, or tuples with column '", "'names and hstore key.'", ")", "%", "str", "(", "field_name", ")", ")", "for", "field_name", "in", "self", ".", "query", ".", "conflict_target", ":", "_assert_valid_field", "(", "field_name", ")", "# special handling for hstore keys", "if", "isinstance", "(", "field_name", ",", "tuple", ")", ":", "conflict_target", ".", "append", "(", "'(%s->\\'%s\\')'", "%", "(", "self", ".", "_format_field_name", "(", "field_name", ")", ",", "field_name", "[", "1", "]", ")", ")", "else", ":", "conflict_target", ".", "append", "(", "self", ".", "_format_field_name", "(", "field_name", ")", ")", "return", "'(%s)'", "%", "','", ".", "join", "(", "conflict_target", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._get_model_field
Gets the field on a model with the specified name. Arguments: name: The name of the field to look for. This can be both the actual field name, or the name of the column, both will work :) Returns: The field with the specified name or None if no such field exists.
psqlextra/compiler.py
def _get_model_field(self, name: str): """Gets the field on a model with the specified name. Arguments: name: The name of the field to look for. This can be both the actual field name, or the name of the column, both will work :) Returns: The field with the specified name or None if no such field exists. """ field_name = self._normalize_field_name(name) # 'pk' has special meaning and always refers to the primary # key of a model, we have to respect this de-facto standard behaviour if field_name == 'pk' and self.query.model._meta.pk: return self.query.model._meta.pk for field in self.query.model._meta.local_concrete_fields: if field.name == field_name or field.column == field_name: return field return None
def _get_model_field(self, name: str): """Gets the field on a model with the specified name. Arguments: name: The name of the field to look for. This can be both the actual field name, or the name of the column, both will work :) Returns: The field with the specified name or None if no such field exists. """ field_name = self._normalize_field_name(name) # 'pk' has special meaning and always refers to the primary # key of a model, we have to respect this de-facto standard behaviour if field_name == 'pk' and self.query.model._meta.pk: return self.query.model._meta.pk for field in self.query.model._meta.local_concrete_fields: if field.name == field_name or field.column == field_name: return field return None
[ "Gets", "the", "field", "on", "a", "model", "with", "the", "specified", "name", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L240-L266
[ "def", "_get_model_field", "(", "self", ",", "name", ":", "str", ")", ":", "field_name", "=", "self", ".", "_normalize_field_name", "(", "name", ")", "# 'pk' has special meaning and always refers to the primary", "# key of a model, we have to respect this de-facto standard behaviour", "if", "field_name", "==", "'pk'", "and", "self", ".", "query", ".", "model", ".", "_meta", ".", "pk", ":", "return", "self", ".", "query", ".", "model", ".", "_meta", ".", "pk", "for", "field", "in", "self", ".", "query", ".", "model", ".", "_meta", ".", "local_concrete_fields", ":", "if", "field", ".", "name", "==", "field_name", "or", "field", ".", "column", "==", "field_name", ":", "return", "field", "return", "None" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._format_field_name
Formats a field's name for usage in SQL. Arguments: field_name: The field name to format. Returns: The specified field name formatted for usage in SQL.
psqlextra/compiler.py
def _format_field_name(self, field_name) -> str: """Formats a field's name for usage in SQL. Arguments: field_name: The field name to format. Returns: The specified field name formatted for usage in SQL. """ field = self._get_model_field(field_name) return self.qn(field.column)
def _format_field_name(self, field_name) -> str: """Formats a field's name for usage in SQL. Arguments: field_name: The field name to format. Returns: The specified field name formatted for usage in SQL. """ field = self._get_model_field(field_name) return self.qn(field.column)
[ "Formats", "a", "field", "s", "name", "for", "usage", "in", "SQL", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L268-L281
[ "def", "_format_field_name", "(", "self", ",", "field_name", ")", "->", "str", ":", "field", "=", "self", ".", "_get_model_field", "(", "field_name", ")", "return", "self", ".", "qn", "(", "field", ".", "column", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._format_field_value
Formats a field's value for usage in SQL. Arguments: field_name: The name of the field to format the value of. Returns: The field's value formatted for usage in SQL.
psqlextra/compiler.py
def _format_field_value(self, field_name) -> str: """Formats a field's value for usage in SQL. Arguments: field_name: The name of the field to format the value of. Returns: The field's value formatted for usage in SQL. """ field_name = self._normalize_field_name(field_name) field = self._get_model_field(field_name) return SQLInsertCompiler.prepare_value( self, field, # Note: this deliberately doesn't use `pre_save_val` as we don't # want things like auto_now on DateTimeField (etc.) to change the # value. We rely on pre_save having already been done by the # underlying compiler so that things like FileField have already had # the opportunity to save out their data. getattr(self.query.objs[0], field.attname) )
def _format_field_value(self, field_name) -> str: """Formats a field's value for usage in SQL. Arguments: field_name: The name of the field to format the value of. Returns: The field's value formatted for usage in SQL. """ field_name = self._normalize_field_name(field_name) field = self._get_model_field(field_name) return SQLInsertCompiler.prepare_value( self, field, # Note: this deliberately doesn't use `pre_save_val` as we don't # want things like auto_now on DateTimeField (etc.) to change the # value. We rely on pre_save having already been done by the # underlying compiler so that things like FileField have already had # the opportunity to save out their data. getattr(self.query.objs[0], field.attname) )
[ "Formats", "a", "field", "s", "value", "for", "usage", "in", "SQL", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L283-L308
[ "def", "_format_field_value", "(", "self", ",", "field_name", ")", "->", "str", ":", "field_name", "=", "self", ".", "_normalize_field_name", "(", "field_name", ")", "field", "=", "self", ".", "_get_model_field", "(", "field_name", ")", "return", "SQLInsertCompiler", ".", "prepare_value", "(", "self", ",", "field", ",", "# Note: this deliberately doesn't use `pre_save_val` as we don't", "# want things like auto_now on DateTimeField (etc.) to change the", "# value. We rely on pre_save having already been done by the", "# underlying compiler so that things like FileField have already had", "# the opportunity to save out their data.", "getattr", "(", "self", ".", "query", ".", "objs", "[", "0", "]", ",", "field", ".", "attname", ")", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
PostgresInsertCompiler._normalize_field_name
Normalizes a field name into a string by extracting the field name if it was specified as a reference to a HStore key (as a tuple). Arguments: field_name: The field name to normalize. Returns: The normalized field name.
psqlextra/compiler.py
def _normalize_field_name(self, field_name) -> str: """Normalizes a field name into a string by extracting the field name if it was specified as a reference to a HStore key (as a tuple). Arguments: field_name: The field name to normalize. Returns: The normalized field name. """ if isinstance(field_name, tuple): field_name, _ = field_name return field_name
def _normalize_field_name(self, field_name) -> str: """Normalizes a field name into a string by extracting the field name if it was specified as a reference to a HStore key (as a tuple). Arguments: field_name: The field name to normalize. Returns: The normalized field name. """ if isinstance(field_name, tuple): field_name, _ = field_name return field_name
[ "Normalizes", "a", "field", "name", "into", "a", "string", "by", "extracting", "the", "field", "name", "if", "it", "was", "specified", "as", "a", "reference", "to", "a", "HStore", "key", "(", "as", "a", "tuple", ")", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/compiler.py#L310-L326
[ "def", "_normalize_field_name", "(", "self", ",", "field_name", ")", "->", "str", ":", "if", "isinstance", "(", "field_name", ",", "tuple", ")", ":", "field_name", ",", "_", "=", "field_name", "return", "field_name" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin.alter_db_table
Ran when the name of a model is changed.
psqlextra/backend/hstore_unique.py
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for keys in self._iterate_uniqueness_keys(field): self._rename_hstore_unique( old_db_table, new_db_table, field, field, keys )
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for keys in self._iterate_uniqueness_keys(field): self._rename_hstore_unique( old_db_table, new_db_table, field, field, keys )
[ "Ran", "when", "the", "name", "of", "a", "model", "is", "changed", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L40-L54
[ "def", "alter_db_table", "(", "self", ",", "model", ",", "old_db_table", ",", "new_db_table", ")", ":", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "not", "isinstance", "(", "field", ",", "HStoreField", ")", ":", "continue", "for", "keys", "in", "self", ".", "_iterate_uniqueness_keys", "(", "field", ")", ":", "self", ".", "_rename_hstore_unique", "(", "old_db_table", ",", "new_db_table", ",", "field", ",", "field", ",", "keys", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin.add_field
Ran when a field is added to a model.
psqlextra/backend/hstore_unique.py
def add_field(self, model, field): """Ran when a field is added to a model.""" for keys in self._iterate_uniqueness_keys(field): self._create_hstore_unique( model, field, keys )
def add_field(self, model, field): """Ran when a field is added to a model.""" for keys in self._iterate_uniqueness_keys(field): self._create_hstore_unique( model, field, keys )
[ "Ran", "when", "a", "field", "is", "added", "to", "a", "model", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L56-L64
[ "def", "add_field", "(", "self", ",", "model", ",", "field", ")", ":", "for", "keys", "in", "self", ".", "_iterate_uniqueness_keys", "(", "field", ")", ":", "self", ".", "_create_hstore_unique", "(", "model", ",", "field", ",", "keys", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin.remove_field
Ran when a field is removed from a model.
psqlextra/backend/hstore_unique.py
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for keys in self._iterate_uniqueness_keys(field): self._drop_hstore_unique( model, field, keys )
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for keys in self._iterate_uniqueness_keys(field): self._drop_hstore_unique( model, field, keys )
[ "Ran", "when", "a", "field", "is", "removed", "from", "a", "model", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L66-L74
[ "def", "remove_field", "(", "self", ",", "model", ",", "field", ")", ":", "for", "keys", "in", "self", ".", "_iterate_uniqueness_keys", "(", "field", ")", ":", "self", ".", "_drop_hstore_unique", "(", "model", ",", "field", ",", "keys", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin.alter_field
Ran when the configuration on a field changed.
psqlextra/backend/hstore_unique.py
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstore: return old_uniqueness = getattr(old_field, 'uniqueness', []) or [] new_uniqueness = getattr(new_field, 'uniqueness', []) or [] # handle field renames before moving on if str(old_field.column) != str(new_field.column): for keys in self._iterate_uniqueness_keys(old_field): self._rename_hstore_unique( model._meta.db_table, model._meta.db_table, old_field, new_field, keys ) # drop the indexes for keys that have been removed for keys in old_uniqueness: if keys not in new_uniqueness: self._drop_hstore_unique( model, old_field, self._compose_keys(keys) ) # create new indexes for keys that have been added for keys in new_uniqueness: if keys not in old_uniqueness: self._create_hstore_unique( model, new_field, self._compose_keys(keys) )
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstore: return old_uniqueness = getattr(old_field, 'uniqueness', []) or [] new_uniqueness = getattr(new_field, 'uniqueness', []) or [] # handle field renames before moving on if str(old_field.column) != str(new_field.column): for keys in self._iterate_uniqueness_keys(old_field): self._rename_hstore_unique( model._meta.db_table, model._meta.db_table, old_field, new_field, keys ) # drop the indexes for keys that have been removed for keys in old_uniqueness: if keys not in new_uniqueness: self._drop_hstore_unique( model, old_field, self._compose_keys(keys) ) # create new indexes for keys that have been added for keys in new_uniqueness: if keys not in old_uniqueness: self._create_hstore_unique( model, new_field, self._compose_keys(keys) )
[ "Ran", "when", "the", "configuration", "on", "a", "field", "changed", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L76-L115
[ "def", "alter_field", "(", "self", ",", "model", ",", "old_field", ",", "new_field", ",", "strict", "=", "False", ")", ":", "is_old_field_hstore", "=", "isinstance", "(", "old_field", ",", "HStoreField", ")", "is_new_field_hstore", "=", "isinstance", "(", "new_field", ",", "HStoreField", ")", "if", "not", "is_old_field_hstore", "and", "not", "is_new_field_hstore", ":", "return", "old_uniqueness", "=", "getattr", "(", "old_field", ",", "'uniqueness'", ",", "[", "]", ")", "or", "[", "]", "new_uniqueness", "=", "getattr", "(", "new_field", ",", "'uniqueness'", ",", "[", "]", ")", "or", "[", "]", "# handle field renames before moving on", "if", "str", "(", "old_field", ".", "column", ")", "!=", "str", "(", "new_field", ".", "column", ")", ":", "for", "keys", "in", "self", ".", "_iterate_uniqueness_keys", "(", "old_field", ")", ":", "self", ".", "_rename_hstore_unique", "(", "model", ".", "_meta", ".", "db_table", ",", "model", ".", "_meta", ".", "db_table", ",", "old_field", ",", "new_field", ",", "keys", ")", "# drop the indexes for keys that have been removed", "for", "keys", "in", "old_uniqueness", ":", "if", "keys", "not", "in", "new_uniqueness", ":", "self", ".", "_drop_hstore_unique", "(", "model", ",", "old_field", ",", "self", ".", "_compose_keys", "(", "keys", ")", ")", "# create new indexes for keys that have been added", "for", "keys", "in", "new_uniqueness", ":", "if", "keys", "not", "in", "old_uniqueness", ":", "self", ".", "_create_hstore_unique", "(", "model", ",", "new_field", ",", "self", ".", "_compose_keys", "(", "keys", ")", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin._create_hstore_unique
Creates a UNIQUE constraint for the specified hstore keys.
psqlextra/backend/hstore_unique.py
def _create_hstore_unique(self, model, field, keys): """Creates a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) columns = [ '(%s->\'%s\')' % (field.column, key) for key in keys ] sql = self.sql_hstore_unique_create.format( name=self.quote_name(name), table=self.quote_name(model._meta.db_table), columns=','.join(columns) ) self.execute(sql)
def _create_hstore_unique(self, model, field, keys): """Creates a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) columns = [ '(%s->\'%s\')' % (field.column, key) for key in keys ] sql = self.sql_hstore_unique_create.format( name=self.quote_name(name), table=self.quote_name(model._meta.db_table), columns=','.join(columns) ) self.execute(sql)
[ "Creates", "a", "UNIQUE", "constraint", "for", "the", "specified", "hstore", "keys", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L117-L131
[ "def", "_create_hstore_unique", "(", "self", ",", "model", ",", "field", ",", "keys", ")", ":", "name", "=", "self", ".", "_unique_constraint_name", "(", "model", ".", "_meta", ".", "db_table", ",", "field", ",", "keys", ")", "columns", "=", "[", "'(%s->\\'%s\\')'", "%", "(", "field", ".", "column", ",", "key", ")", "for", "key", "in", "keys", "]", "sql", "=", "self", ".", "sql_hstore_unique_create", ".", "format", "(", "name", "=", "self", ".", "quote_name", "(", "name", ")", ",", "table", "=", "self", ".", "quote_name", "(", "model", ".", "_meta", ".", "db_table", ")", ",", "columns", "=", "','", ".", "join", "(", "columns", ")", ")", "self", ".", "execute", "(", "sql", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin._rename_hstore_unique
Renames an existing UNIQUE constraint for the specified hstore keys.
psqlextra/backend/hstore_unique.py
def _rename_hstore_unique(self, old_table_name, new_table_name, old_field, new_field, keys): """Renames an existing UNIQUE constraint for the specified hstore keys.""" old_name = self._unique_constraint_name( old_table_name, old_field, keys) new_name = self._unique_constraint_name( new_table_name, new_field, keys) sql = self.sql_hstore_unique_rename.format( old_name=self.quote_name(old_name), new_name=self.quote_name(new_name) ) self.execute(sql)
def _rename_hstore_unique(self, old_table_name, new_table_name, old_field, new_field, keys): """Renames an existing UNIQUE constraint for the specified hstore keys.""" old_name = self._unique_constraint_name( old_table_name, old_field, keys) new_name = self._unique_constraint_name( new_table_name, new_field, keys) sql = self.sql_hstore_unique_rename.format( old_name=self.quote_name(old_name), new_name=self.quote_name(new_name) ) self.execute(sql)
[ "Renames", "an", "existing", "UNIQUE", "constraint", "for", "the", "specified", "hstore", "keys", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L133-L147
[ "def", "_rename_hstore_unique", "(", "self", ",", "old_table_name", ",", "new_table_name", ",", "old_field", ",", "new_field", ",", "keys", ")", ":", "old_name", "=", "self", ".", "_unique_constraint_name", "(", "old_table_name", ",", "old_field", ",", "keys", ")", "new_name", "=", "self", ".", "_unique_constraint_name", "(", "new_table_name", ",", "new_field", ",", "keys", ")", "sql", "=", "self", ".", "sql_hstore_unique_rename", ".", "format", "(", "old_name", "=", "self", ".", "quote_name", "(", "old_name", ")", ",", "new_name", "=", "self", ".", "quote_name", "(", "new_name", ")", ")", "self", ".", "execute", "(", "sql", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin._drop_hstore_unique
Drops a UNIQUE constraint for the specified hstore keys.
psqlextra/backend/hstore_unique.py
def _drop_hstore_unique(self, model, field, keys): """Drops a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) sql = self.sql_hstore_unique_drop.format(name=self.quote_name(name)) self.execute(sql)
def _drop_hstore_unique(self, model, field, keys): """Drops a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) sql = self.sql_hstore_unique_drop.format(name=self.quote_name(name)) self.execute(sql)
[ "Drops", "a", "UNIQUE", "constraint", "for", "the", "specified", "hstore", "keys", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L149-L155
[ "def", "_drop_hstore_unique", "(", "self", ",", "model", ",", "field", ",", "keys", ")", ":", "name", "=", "self", ".", "_unique_constraint_name", "(", "model", ".", "_meta", ".", "db_table", ",", "field", ",", "keys", ")", "sql", "=", "self", ".", "sql_hstore_unique_drop", ".", "format", "(", "name", "=", "self", ".", "quote_name", "(", "name", ")", ")", "self", ".", "execute", "(", "sql", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin._unique_constraint_name
Gets the name for a UNIQUE INDEX that applies to one or more keys in a hstore field. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. This can also be a tuple of multiple names. Returns: The name for the UNIQUE index.
psqlextra/backend/hstore_unique.py
def _unique_constraint_name(table: str, field, keys): """Gets the name for a UNIQUE INDEX that applies to one or more keys in a hstore field. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. This can also be a tuple of multiple names. Returns: The name for the UNIQUE index. """ postfix = '_'.join(keys) return '{table}_{field}_unique_{postfix}'.format( table=table, field=field.column, postfix=postfix )
def _unique_constraint_name(table: str, field, keys): """Gets the name for a UNIQUE INDEX that applies to one or more keys in a hstore field. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. This can also be a tuple of multiple names. Returns: The name for the UNIQUE index. """ postfix = '_'.join(keys) return '{table}_{field}_unique_{postfix}'.format( table=table, field=field.column, postfix=postfix )
[ "Gets", "the", "name", "for", "a", "UNIQUE", "INDEX", "that", "applies", "to", "one", "or", "more", "keys", "in", "a", "hstore", "field", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L158-L186
[ "def", "_unique_constraint_name", "(", "table", ":", "str", ",", "field", ",", "keys", ")", ":", "postfix", "=", "'_'", ".", "join", "(", "keys", ")", "return", "'{table}_{field}_unique_{postfix}'", ".", "format", "(", "table", "=", "table", ",", "field", "=", "field", ".", "column", ",", "postfix", "=", "postfix", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
HStoreUniqueSchemaEditorMixin._iterate_uniqueness_keys
Iterates over the keys marked as "unique" in the specified field. Arguments: field: The field of which key's to iterate over.
psqlextra/backend/hstore_unique.py
def _iterate_uniqueness_keys(self, field): """Iterates over the keys marked as "unique" in the specified field. Arguments: field: The field of which key's to iterate over. """ uniqueness = getattr(field, 'uniqueness', None) if not uniqueness: return for keys in uniqueness: composed_keys = self._compose_keys(keys) yield composed_keys
def _iterate_uniqueness_keys(self, field): """Iterates over the keys marked as "unique" in the specified field. Arguments: field: The field of which key's to iterate over. """ uniqueness = getattr(field, 'uniqueness', None) if not uniqueness: return for keys in uniqueness: composed_keys = self._compose_keys(keys) yield composed_keys
[ "Iterates", "over", "the", "keys", "marked", "as", "unique", "in", "the", "specified", "field", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/hstore_unique.py#L188-L204
[ "def", "_iterate_uniqueness_keys", "(", "self", ",", "field", ")", ":", "uniqueness", "=", "getattr", "(", "field", ",", "'uniqueness'", ",", "None", ")", "if", "not", "uniqueness", ":", "return", "for", "keys", "in", "uniqueness", ":", "composed_keys", "=", "self", ".", "_compose_keys", "(", "keys", ")", "yield", "composed_keys" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
ConditionalJoin.add_condition
Adds an extra condition to this join. Arguments: field: The field that the condition will apply to. value: The value to compare.
psqlextra/datastructures.py
def add_condition(self, field, value: Any) -> None: """Adds an extra condition to this join. Arguments: field: The field that the condition will apply to. value: The value to compare. """ self.extra_conditions.append((field, value))
def add_condition(self, field, value: Any) -> None: """Adds an extra condition to this join. Arguments: field: The field that the condition will apply to. value: The value to compare. """ self.extra_conditions.append((field, value))
[ "Adds", "an", "extra", "condition", "to", "this", "join", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/datastructures.py#L17-L28
[ "def", "add_condition", "(", "self", ",", "field", ",", "value", ":", "Any", ")", "->", "None", ":", "self", ".", "extra_conditions", ".", "append", "(", "(", "field", ",", "value", ")", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
ConditionalJoin.as_sql
Compiles this JOIN into a SQL string.
psqlextra/datastructures.py
def as_sql(self, compiler, connection) -> Tuple[str, List[Any]]: """Compiles this JOIN into a SQL string.""" sql, params = super().as_sql(compiler, connection) qn = compiler.quote_name_unless_alias # generate the extra conditions extra_conditions = ' AND '.join([ '{}.{} = %s'.format( qn(self.table_name), qn(field.column) ) for field, value in self.extra_conditions ]) # add to the existing params, so the connector will # actually nicely format the value for us for _, value in self.extra_conditions: params.append(value) # rewrite the sql to include the extra conditions rewritten_sql = sql.replace(')', ' AND {})'.format(extra_conditions)) return rewritten_sql, params
def as_sql(self, compiler, connection) -> Tuple[str, List[Any]]: """Compiles this JOIN into a SQL string.""" sql, params = super().as_sql(compiler, connection) qn = compiler.quote_name_unless_alias # generate the extra conditions extra_conditions = ' AND '.join([ '{}.{} = %s'.format( qn(self.table_name), qn(field.column) ) for field, value in self.extra_conditions ]) # add to the existing params, so the connector will # actually nicely format the value for us for _, value in self.extra_conditions: params.append(value) # rewrite the sql to include the extra conditions rewritten_sql = sql.replace(')', ' AND {})'.format(extra_conditions)) return rewritten_sql, params
[ "Compiles", "this", "JOIN", "into", "a", "SQL", "string", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/datastructures.py#L30-L52
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", "->", "Tuple", "[", "str", ",", "List", "[", "Any", "]", "]", ":", "sql", ",", "params", "=", "super", "(", ")", ".", "as_sql", "(", "compiler", ",", "connection", ")", "qn", "=", "compiler", ".", "quote_name_unless_alias", "# generate the extra conditions", "extra_conditions", "=", "' AND '", ".", "join", "(", "[", "'{}.{} = %s'", ".", "format", "(", "qn", "(", "self", ".", "table_name", ")", ",", "qn", "(", "field", ".", "column", ")", ")", "for", "field", ",", "value", "in", "self", ".", "extra_conditions", "]", ")", "# add to the existing params, so the connector will", "# actually nicely format the value for us", "for", "_", ",", "value", "in", "self", ".", "extra_conditions", ":", "params", ".", "append", "(", "value", ")", "# rewrite the sql to include the extra conditions", "rewritten_sql", "=", "sql", ".", "replace", "(", "')'", ",", "' AND {})'", ".", "format", "(", "extra_conditions", ")", ")", "return", "rewritten_sql", ",", "params" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
ConditionalJoin.from_join
Creates a new :see:ConditionalJoin from the specified :see:Join object. Arguments: join: The :see:Join object to create the :see:ConditionalJoin object from. Returns: A :see:ConditionalJoin object created from the :see:Join object.
psqlextra/datastructures.py
def from_join(cls, join: Join) -> 'ConditionalJoin': """Creates a new :see:ConditionalJoin from the specified :see:Join object. Arguments: join: The :see:Join object to create the :see:ConditionalJoin object from. Returns: A :see:ConditionalJoin object created from the :see:Join object. """ return cls( join.table_name, join.parent_alias, join.table_alias, join.join_type, join.join_field, join.nullable )
def from_join(cls, join: Join) -> 'ConditionalJoin': """Creates a new :see:ConditionalJoin from the specified :see:Join object. Arguments: join: The :see:Join object to create the :see:ConditionalJoin object from. Returns: A :see:ConditionalJoin object created from the :see:Join object. """ return cls( join.table_name, join.parent_alias, join.table_alias, join.join_type, join.join_field, join.nullable )
[ "Creates", "a", "new", ":", "see", ":", "ConditionalJoin", "from", "the", "specified", ":", "see", ":", "Join", "object", "." ]
SectorLabs/django-postgres-extra
python
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/datastructures.py#L55-L76
[ "def", "from_join", "(", "cls", ",", "join", ":", "Join", ")", "->", "'ConditionalJoin'", ":", "return", "cls", "(", "join", ".", "table_name", ",", "join", ".", "parent_alias", ",", "join", ".", "table_alias", ",", "join", ".", "join_type", ",", "join", ".", "join_field", ",", "join", ".", "nullable", ")" ]
eef2ed5504d225858d4e4f5d77a838082ca6053e
test
tdist95conf_level
Approximate the 95% confidence interval for Student's T distribution. Given the degrees of freedom, returns an approximation to the 95% confidence interval for the Student's T distribution. Args: df: An integer, the number of degrees of freedom. Returns: A float.
performance/compare.py
def tdist95conf_level(df): """Approximate the 95% confidence interval for Student's T distribution. Given the degrees of freedom, returns an approximation to the 95% confidence interval for the Student's T distribution. Args: df: An integer, the number of degrees of freedom. Returns: A float. """ df = int(round(df)) highest_table_df = len(_T_DIST_95_CONF_LEVELS) if df >= 200: return 1.960 if df >= 100: return 1.984 if df >= 80: return 1.990 if df >= 60: return 2.000 if df >= 50: return 2.009 if df >= 40: return 2.021 if df >= highest_table_df: return _T_DIST_95_CONF_LEVELS[highest_table_df - 1] return _T_DIST_95_CONF_LEVELS[df]
def tdist95conf_level(df): """Approximate the 95% confidence interval for Student's T distribution. Given the degrees of freedom, returns an approximation to the 95% confidence interval for the Student's T distribution. Args: df: An integer, the number of degrees of freedom. Returns: A float. """ df = int(round(df)) highest_table_df = len(_T_DIST_95_CONF_LEVELS) if df >= 200: return 1.960 if df >= 100: return 1.984 if df >= 80: return 1.990 if df >= 60: return 2.000 if df >= 50: return 2.009 if df >= 40: return 2.021 if df >= highest_table_df: return _T_DIST_95_CONF_LEVELS[highest_table_df - 1] return _T_DIST_95_CONF_LEVELS[df]
[ "Approximate", "the", "95%", "confidence", "interval", "for", "Student", "s", "T", "distribution", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/compare.py#L39-L67
[ "def", "tdist95conf_level", "(", "df", ")", ":", "df", "=", "int", "(", "round", "(", "df", ")", ")", "highest_table_df", "=", "len", "(", "_T_DIST_95_CONF_LEVELS", ")", "if", "df", ">=", "200", ":", "return", "1.960", "if", "df", ">=", "100", ":", "return", "1.984", "if", "df", ">=", "80", ":", "return", "1.990", "if", "df", ">=", "60", ":", "return", "2.000", "if", "df", ">=", "50", ":", "return", "2.009", "if", "df", ">=", "40", ":", "return", "2.021", "if", "df", ">=", "highest_table_df", ":", "return", "_T_DIST_95_CONF_LEVELS", "[", "highest_table_df", "-", "1", "]", "return", "_T_DIST_95_CONF_LEVELS", "[", "df", "]" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
pooled_sample_variance
Find the pooled sample variance for two samples. Args: sample1: one sample. sample2: the other sample. Returns: Pooled sample variance, as a float.
performance/compare.py
def pooled_sample_variance(sample1, sample2): """Find the pooled sample variance for two samples. Args: sample1: one sample. sample2: the other sample. Returns: Pooled sample variance, as a float. """ deg_freedom = len(sample1) + len(sample2) - 2 mean1 = statistics.mean(sample1) squares1 = ((x - mean1) ** 2 for x in sample1) mean2 = statistics.mean(sample2) squares2 = ((x - mean2) ** 2 for x in sample2) return (math.fsum(squares1) + math.fsum(squares2)) / float(deg_freedom)
def pooled_sample_variance(sample1, sample2): """Find the pooled sample variance for two samples. Args: sample1: one sample. sample2: the other sample. Returns: Pooled sample variance, as a float. """ deg_freedom = len(sample1) + len(sample2) - 2 mean1 = statistics.mean(sample1) squares1 = ((x - mean1) ** 2 for x in sample1) mean2 = statistics.mean(sample2) squares2 = ((x - mean2) ** 2 for x in sample2) return (math.fsum(squares1) + math.fsum(squares2)) / float(deg_freedom)
[ "Find", "the", "pooled", "sample", "variance", "for", "two", "samples", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/compare.py#L70-L86
[ "def", "pooled_sample_variance", "(", "sample1", ",", "sample2", ")", ":", "deg_freedom", "=", "len", "(", "sample1", ")", "+", "len", "(", "sample2", ")", "-", "2", "mean1", "=", "statistics", ".", "mean", "(", "sample1", ")", "squares1", "=", "(", "(", "x", "-", "mean1", ")", "**", "2", "for", "x", "in", "sample1", ")", "mean2", "=", "statistics", ".", "mean", "(", "sample2", ")", "squares2", "=", "(", "(", "x", "-", "mean2", ")", "**", "2", "for", "x", "in", "sample2", ")", "return", "(", "math", ".", "fsum", "(", "squares1", ")", "+", "math", ".", "fsum", "(", "squares2", ")", ")", "/", "float", "(", "deg_freedom", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
tscore
Calculate a t-test score for the difference between two samples. Args: sample1: one sample. sample2: the other sample. Returns: The t-test score, as a float.
performance/compare.py
def tscore(sample1, sample2): """Calculate a t-test score for the difference between two samples. Args: sample1: one sample. sample2: the other sample. Returns: The t-test score, as a float. """ if len(sample1) != len(sample2): raise ValueError("different number of values") error = pooled_sample_variance(sample1, sample2) / len(sample1) diff = statistics.mean(sample1) - statistics.mean(sample2) return diff / math.sqrt(error * 2)
def tscore(sample1, sample2): """Calculate a t-test score for the difference between two samples. Args: sample1: one sample. sample2: the other sample. Returns: The t-test score, as a float. """ if len(sample1) != len(sample2): raise ValueError("different number of values") error = pooled_sample_variance(sample1, sample2) / len(sample1) diff = statistics.mean(sample1) - statistics.mean(sample2) return diff / math.sqrt(error * 2)
[ "Calculate", "a", "t", "-", "test", "score", "for", "the", "difference", "between", "two", "samples", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/compare.py#L89-L103
[ "def", "tscore", "(", "sample1", ",", "sample2", ")", ":", "if", "len", "(", "sample1", ")", "!=", "len", "(", "sample2", ")", ":", "raise", "ValueError", "(", "\"different number of values\"", ")", "error", "=", "pooled_sample_variance", "(", "sample1", ",", "sample2", ")", "/", "len", "(", "sample1", ")", "diff", "=", "statistics", ".", "mean", "(", "sample1", ")", "-", "statistics", ".", "mean", "(", "sample2", ")", "return", "diff", "/", "math", ".", "sqrt", "(", "error", "*", "2", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
is_significant
Determine whether two samples differ significantly. This uses a Student's two-sample, two-tailed t-test with alpha=0.95. Args: sample1: one sample. sample2: the other sample. Returns: (significant, t_score) where significant is a bool indicating whether the two samples differ significantly; t_score is the score from the two-sample T test.
performance/compare.py
def is_significant(sample1, sample2): """Determine whether two samples differ significantly. This uses a Student's two-sample, two-tailed t-test with alpha=0.95. Args: sample1: one sample. sample2: the other sample. Returns: (significant, t_score) where significant is a bool indicating whether the two samples differ significantly; t_score is the score from the two-sample T test. """ deg_freedom = len(sample1) + len(sample2) - 2 critical_value = tdist95conf_level(deg_freedom) t_score = tscore(sample1, sample2) return (abs(t_score) >= critical_value, t_score)
def is_significant(sample1, sample2): """Determine whether two samples differ significantly. This uses a Student's two-sample, two-tailed t-test with alpha=0.95. Args: sample1: one sample. sample2: the other sample. Returns: (significant, t_score) where significant is a bool indicating whether the two samples differ significantly; t_score is the score from the two-sample T test. """ deg_freedom = len(sample1) + len(sample2) - 2 critical_value = tdist95conf_level(deg_freedom) t_score = tscore(sample1, sample2) return (abs(t_score) >= critical_value, t_score)
[ "Determine", "whether", "two", "samples", "differ", "significantly", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/compare.py#L106-L123
[ "def", "is_significant", "(", "sample1", ",", "sample2", ")", ":", "deg_freedom", "=", "len", "(", "sample1", ")", "+", "len", "(", "sample2", ")", "-", "2", "critical_value", "=", "tdist95conf_level", "(", "deg_freedom", ")", "t_score", "=", "tscore", "(", "sample1", ",", "sample2", ")", "return", "(", "abs", "(", "t_score", ")", ">=", "critical_value", ",", "t_score", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
topoSort
Return a topological sorting of nodes in a graph. roots - list of root nodes to search from getParents - function which returns the parents of a given node
performance/benchmarks/bm_mdp.py
def topoSort(roots, getParents): """Return a topological sorting of nodes in a graph. roots - list of root nodes to search from getParents - function which returns the parents of a given node """ results = [] visited = set() # Use iterative version to avoid stack limits for large datasets stack = [(node, 0) for node in roots] while stack: current, state = stack.pop() if state == 0: # before recursing if current not in visited: visited.add(current) stack.append((current, 1)) stack.extend((parent, 0) for parent in getParents(current)) else: # after recursing assert(current in visited) results.append(current) return results
def topoSort(roots, getParents): """Return a topological sorting of nodes in a graph. roots - list of root nodes to search from getParents - function which returns the parents of a given node """ results = [] visited = set() # Use iterative version to avoid stack limits for large datasets stack = [(node, 0) for node in roots] while stack: current, state = stack.pop() if state == 0: # before recursing if current not in visited: visited.add(current) stack.append((current, 1)) stack.extend((parent, 0) for parent in getParents(current)) else: # after recursing assert(current in visited) results.append(current) return results
[ "Return", "a", "topological", "sorting", "of", "nodes", "in", "a", "graph", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_mdp.py#L9-L33
[ "def", "topoSort", "(", "roots", ",", "getParents", ")", ":", "results", "=", "[", "]", "visited", "=", "set", "(", ")", "# Use iterative version to avoid stack limits for large datasets", "stack", "=", "[", "(", "node", ",", "0", ")", "for", "node", "in", "roots", "]", "while", "stack", ":", "current", ",", "state", "=", "stack", ".", "pop", "(", ")", "if", "state", "==", "0", ":", "# before recursing", "if", "current", "not", "in", "visited", ":", "visited", ".", "add", "(", "current", ")", "stack", ".", "append", "(", "(", "current", ",", "1", ")", ")", "stack", ".", "extend", "(", "(", "parent", ",", "0", ")", "for", "parent", "in", "getParents", "(", "current", ")", ")", "else", ":", "# after recursing", "assert", "(", "current", "in", "visited", ")", "results", ".", "append", "(", "current", ")", "return", "results" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
permutations
permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)
performance/benchmarks/bm_nqueens.py
def permutations(iterable, r=None): """permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)""" pool = tuple(iterable) n = len(pool) if r is None: r = n indices = list(range(n)) cycles = list(range(n - r + 1, n + 1))[::-1] yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i + 1:] + indices[i:i + 1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return
def permutations(iterable, r=None): """permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)""" pool = tuple(iterable) n = len(pool) if r is None: r = n indices = list(range(n)) cycles = list(range(n - r + 1, n + 1))[::-1] yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i + 1:] + indices[i:i + 1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return
[ "permutations", "(", "range", "(", "3", ")", "2", ")", "--", ">", "(", "0", "1", ")", "(", "0", "2", ")", "(", "1", "0", ")", "(", "1", "2", ")", "(", "2", "0", ")", "(", "2", "1", ")" ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_nqueens.py#L9-L30
[ "def", "permutations", "(", "iterable", ",", "r", "=", "None", ")", ":", "pool", "=", "tuple", "(", "iterable", ")", "n", "=", "len", "(", "pool", ")", "if", "r", "is", "None", ":", "r", "=", "n", "indices", "=", "list", "(", "range", "(", "n", ")", ")", "cycles", "=", "list", "(", "range", "(", "n", "-", "r", "+", "1", ",", "n", "+", "1", ")", ")", "[", ":", ":", "-", "1", "]", "yield", "tuple", "(", "pool", "[", "i", "]", "for", "i", "in", "indices", "[", ":", "r", "]", ")", "while", "n", ":", "for", "i", "in", "reversed", "(", "range", "(", "r", ")", ")", ":", "cycles", "[", "i", "]", "-=", "1", "if", "cycles", "[", "i", "]", "==", "0", ":", "indices", "[", "i", ":", "]", "=", "indices", "[", "i", "+", "1", ":", "]", "+", "indices", "[", "i", ":", "i", "+", "1", "]", "cycles", "[", "i", "]", "=", "n", "-", "i", "else", ":", "j", "=", "cycles", "[", "i", "]", "indices", "[", "i", "]", ",", "indices", "[", "-", "j", "]", "=", "indices", "[", "-", "j", "]", ",", "indices", "[", "i", "]", "yield", "tuple", "(", "pool", "[", "i", "]", "for", "i", "in", "indices", "[", ":", "r", "]", ")", "break", "else", ":", "return" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
n_queens
N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the queen, and the index into the tuple indicates the row.
performance/benchmarks/bm_nqueens.py
def n_queens(queen_count): """N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the queen, and the index into the tuple indicates the row. """ cols = range(queen_count) for vec in permutations(cols): if (queen_count == len(set(vec[i] + i for i in cols)) == len(set(vec[i] - i for i in cols))): yield vec
def n_queens(queen_count): """N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the queen, and the index into the tuple indicates the row. """ cols = range(queen_count) for vec in permutations(cols): if (queen_count == len(set(vec[i] + i for i in cols)) == len(set(vec[i] - i for i in cols))): yield vec
[ "N", "-", "Queens", "solver", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_nqueens.py#L34-L50
[ "def", "n_queens", "(", "queen_count", ")", ":", "cols", "=", "range", "(", "queen_count", ")", "for", "vec", "in", "permutations", "(", "cols", ")", ":", "if", "(", "queen_count", "==", "len", "(", "set", "(", "vec", "[", "i", "]", "+", "i", "for", "i", "in", "cols", ")", ")", "==", "len", "(", "set", "(", "vec", "[", "i", "]", "-", "i", "for", "i", "in", "cols", ")", ")", ")", ":", "yield", "vec" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
UCTNode.play
uct tree search
performance/benchmarks/bm_go.py
def play(self, board): """ uct tree search """ color = board.color node = self path = [node] while True: pos = node.select(board) if pos == PASS: break board.move(pos) child = node.pos_child[pos] if not child: child = node.pos_child[pos] = UCTNode() child.unexplored = board.useful_moves() child.pos = pos child.parent = node path.append(child) break path.append(child) node = child self.random_playout(board) self.update_path(board, color, path)
def play(self, board): """ uct tree search """ color = board.color node = self path = [node] while True: pos = node.select(board) if pos == PASS: break board.move(pos) child = node.pos_child[pos] if not child: child = node.pos_child[pos] = UCTNode() child.unexplored = board.useful_moves() child.pos = pos child.parent = node path.append(child) break path.append(child) node = child self.random_playout(board) self.update_path(board, color, path)
[ "uct", "tree", "search" ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_go.py#L329-L350
[ "def", "play", "(", "self", ",", "board", ")", ":", "color", "=", "board", ".", "color", "node", "=", "self", "path", "=", "[", "node", "]", "while", "True", ":", "pos", "=", "node", ".", "select", "(", "board", ")", "if", "pos", "==", "PASS", ":", "break", "board", ".", "move", "(", "pos", ")", "child", "=", "node", ".", "pos_child", "[", "pos", "]", "if", "not", "child", ":", "child", "=", "node", ".", "pos_child", "[", "pos", "]", "=", "UCTNode", "(", ")", "child", ".", "unexplored", "=", "board", ".", "useful_moves", "(", ")", "child", ".", "pos", "=", "pos", "child", ".", "parent", "=", "node", "path", ".", "append", "(", "child", ")", "break", "path", ".", "append", "(", "child", ")", "node", "=", "child", "self", ".", "random_playout", "(", "board", ")", "self", ".", "update_path", "(", "board", ",", "color", ",", "path", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
UCTNode.select
select move; unexplored children first, then according to uct value
performance/benchmarks/bm_go.py
def select(self, board): """ select move; unexplored children first, then according to uct value """ if self.unexplored: i = random.randrange(len(self.unexplored)) pos = self.unexplored[i] self.unexplored[i] = self.unexplored[len(self.unexplored) - 1] self.unexplored.pop() return pos elif self.bestchild: return self.bestchild.pos else: return PASS
def select(self, board): """ select move; unexplored children first, then according to uct value """ if self.unexplored: i = random.randrange(len(self.unexplored)) pos = self.unexplored[i] self.unexplored[i] = self.unexplored[len(self.unexplored) - 1] self.unexplored.pop() return pos elif self.bestchild: return self.bestchild.pos else: return PASS
[ "select", "move", ";", "unexplored", "children", "first", "then", "according", "to", "uct", "value" ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_go.py#L352-L363
[ "def", "select", "(", "self", ",", "board", ")", ":", "if", "self", ".", "unexplored", ":", "i", "=", "random", ".", "randrange", "(", "len", "(", "self", ".", "unexplored", ")", ")", "pos", "=", "self", ".", "unexplored", "[", "i", "]", "self", ".", "unexplored", "[", "i", "]", "=", "self", ".", "unexplored", "[", "len", "(", "self", ".", "unexplored", ")", "-", "1", "]", "self", ".", "unexplored", ".", "pop", "(", ")", "return", "pos", "elif", "self", ".", "bestchild", ":", "return", "self", ".", "bestchild", ".", "pos", "else", ":", "return", "PASS" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
UCTNode.random_playout
random play until both players pass
performance/benchmarks/bm_go.py
def random_playout(self, board): """ random play until both players pass """ for x in range(MAXMOVES): # XXX while not self.finished? if board.finished: break board.move(board.random_move())
def random_playout(self, board): """ random play until both players pass """ for x in range(MAXMOVES): # XXX while not self.finished? if board.finished: break board.move(board.random_move())
[ "random", "play", "until", "both", "players", "pass" ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_go.py#L365-L370
[ "def", "random_playout", "(", "self", ",", "board", ")", ":", "for", "x", "in", "range", "(", "MAXMOVES", ")", ":", "# XXX while not self.finished?", "if", "board", ".", "finished", ":", "break", "board", ".", "move", "(", "board", ".", "random_move", "(", ")", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
UCTNode.update_path
update win/loss count along path
performance/benchmarks/bm_go.py
def update_path(self, board, color, path): """ update win/loss count along path """ wins = board.score(BLACK) >= board.score(WHITE) for node in path: if color == BLACK: color = WHITE else: color = BLACK if wins == (color == BLACK): node.wins += 1 else: node.losses += 1 if node.parent: node.parent.bestchild = node.parent.best_child()
def update_path(self, board, color, path): """ update win/loss count along path """ wins = board.score(BLACK) >= board.score(WHITE) for node in path: if color == BLACK: color = WHITE else: color = BLACK if wins == (color == BLACK): node.wins += 1 else: node.losses += 1 if node.parent: node.parent.bestchild = node.parent.best_child()
[ "update", "win", "/", "loss", "count", "along", "path" ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_go.py#L372-L385
[ "def", "update_path", "(", "self", ",", "board", ",", "color", ",", "path", ")", ":", "wins", "=", "board", ".", "score", "(", "BLACK", ")", ">=", "board", ".", "score", "(", "WHITE", ")", "for", "node", "in", "path", ":", "if", "color", "==", "BLACK", ":", "color", "=", "WHITE", "else", ":", "color", "=", "BLACK", "if", "wins", "==", "(", "color", "==", "BLACK", ")", ":", "node", ".", "wins", "+=", "1", "else", ":", "node", ".", "losses", "+=", "1", "if", "node", ".", "parent", ":", "node", ".", "parent", ".", "bestchild", "=", "node", ".", "parent", ".", "best_child", "(", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
filter_benchmarks
Filters out benchmarks not supported by both Pythons. Args: benchmarks: a set() of benchmark names bench_funcs: dict mapping benchmark names to functions python: the interpereter commands (as lists) Returns: The filtered set of benchmark names
performance/benchmarks/__init__.py
def filter_benchmarks(benchmarks, bench_funcs, base_ver): """Filters out benchmarks not supported by both Pythons. Args: benchmarks: a set() of benchmark names bench_funcs: dict mapping benchmark names to functions python: the interpereter commands (as lists) Returns: The filtered set of benchmark names """ for bm in list(benchmarks): func = bench_funcs[bm] if getattr(func, '_python2_only', False) and (3, 0) <= base_ver: benchmarks.discard(bm) logging.info("Skipping Python2-only benchmark %s; " "not compatible with Python %s" % (bm, base_ver)) continue return benchmarks
def filter_benchmarks(benchmarks, bench_funcs, base_ver): """Filters out benchmarks not supported by both Pythons. Args: benchmarks: a set() of benchmark names bench_funcs: dict mapping benchmark names to functions python: the interpereter commands (as lists) Returns: The filtered set of benchmark names """ for bm in list(benchmarks): func = bench_funcs[bm] if getattr(func, '_python2_only', False) and (3, 0) <= base_ver: benchmarks.discard(bm) logging.info("Skipping Python2-only benchmark %s; " "not compatible with Python %s" % (bm, base_ver)) continue return benchmarks
[ "Filters", "out", "benchmarks", "not", "supported", "by", "both", "Pythons", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/__init__.py#L323-L341
[ "def", "filter_benchmarks", "(", "benchmarks", ",", "bench_funcs", ",", "base_ver", ")", ":", "for", "bm", "in", "list", "(", "benchmarks", ")", ":", "func", "=", "bench_funcs", "[", "bm", "]", "if", "getattr", "(", "func", ",", "'_python2_only'", ",", "False", ")", "and", "(", "3", ",", "0", ")", "<=", "base_ver", ":", "benchmarks", ".", "discard", "(", "bm", ")", "logging", ".", "info", "(", "\"Skipping Python2-only benchmark %s; \"", "\"not compatible with Python %s\"", "%", "(", "bm", ",", "base_ver", ")", ")", "continue", "return", "benchmarks" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
expand_benchmark_name
Recursively expand name benchmark names. Args: bm_name: string naming a benchmark or benchmark group. Yields: Names of actual benchmarks, with all group names fully expanded.
performance/benchmarks/__init__.py
def expand_benchmark_name(bm_name, bench_groups): """Recursively expand name benchmark names. Args: bm_name: string naming a benchmark or benchmark group. Yields: Names of actual benchmarks, with all group names fully expanded. """ expansion = bench_groups.get(bm_name) if expansion: for name in expansion: for name in expand_benchmark_name(name, bench_groups): yield name else: yield bm_name
def expand_benchmark_name(bm_name, bench_groups): """Recursively expand name benchmark names. Args: bm_name: string naming a benchmark or benchmark group. Yields: Names of actual benchmarks, with all group names fully expanded. """ expansion = bench_groups.get(bm_name) if expansion: for name in expansion: for name in expand_benchmark_name(name, bench_groups): yield name else: yield bm_name
[ "Recursively", "expand", "name", "benchmark", "names", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/__init__.py#L344-L359
[ "def", "expand_benchmark_name", "(", "bm_name", ",", "bench_groups", ")", ":", "expansion", "=", "bench_groups", ".", "get", "(", "bm_name", ")", "if", "expansion", ":", "for", "name", "in", "expansion", ":", "for", "name", "in", "expand_benchmark_name", "(", "name", ",", "bench_groups", ")", ":", "yield", "name", "else", ":", "yield", "bm_name" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
gen_string_table
Generates the list of strings that will be used in the benchmarks. All strings have repeated prefixes and suffices, and n specifies the number of repetitions.
performance/benchmarks/bm_regex_effbot.py
def gen_string_table(n): """Generates the list of strings that will be used in the benchmarks. All strings have repeated prefixes and suffices, and n specifies the number of repetitions. """ strings = [] def append(s): if USE_BYTES_IN_PY3K: strings.append(s.encode('latin1')) else: strings.append(s) append('-' * n + 'Perl' + '-' * n) append('P' * n + 'Perl' + 'P' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'Python' + '-' * n) append('P' * n + 'Python' + 'P' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Perl' + '-' * n) append('P' * n + 'Perl' + 'P' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'PythonPython' + '-' * n) append('P' * n + 'PythonPython' + 'P' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'Python' + '-' * n) return strings
def gen_string_table(n): """Generates the list of strings that will be used in the benchmarks. All strings have repeated prefixes and suffices, and n specifies the number of repetitions. """ strings = [] def append(s): if USE_BYTES_IN_PY3K: strings.append(s.encode('latin1')) else: strings.append(s) append('-' * n + 'Perl' + '-' * n) append('P' * n + 'Perl' + 'P' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'Python' + '-' * n) append('P' * n + 'Python' + 'P' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Python' + '-' * n) append('-' * n + 'Perl' + '-' * n) append('P' * n + 'Perl' + 'P' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'Perl' + '-' * n) append('-' * n + 'PythonPython' + '-' * n) append('P' * n + 'PythonPython' + 'P' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'a5,b7,c9,' + '-' * n) append('-' * n + 'Python' + '-' * n) return strings
[ "Generates", "the", "list", "of", "strings", "that", "will", "be", "used", "in", "the", "benchmarks", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_regex_effbot.py#L60-L94
[ "def", "gen_string_table", "(", "n", ")", ":", "strings", "=", "[", "]", "def", "append", "(", "s", ")", ":", "if", "USE_BYTES_IN_PY3K", ":", "strings", ".", "append", "(", "s", ".", "encode", "(", "'latin1'", ")", ")", "else", ":", "strings", ".", "append", "(", "s", ")", "append", "(", "'-'", "*", "n", "+", "'Perl'", "+", "'-'", "*", "n", ")", "append", "(", "'P'", "*", "n", "+", "'Perl'", "+", "'P'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Perl'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Perl'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Python'", "+", "'-'", "*", "n", ")", "append", "(", "'P'", "*", "n", "+", "'Python'", "+", "'P'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Python'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Python'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Python'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Python'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Perl'", "+", "'-'", "*", "n", ")", "append", "(", "'P'", "*", "n", "+", "'Perl'", "+", "'P'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Perl'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Perl'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'PythonPython'", "+", "'-'", "*", "n", ")", "append", "(", "'P'", "*", "n", "+", "'PythonPython'", "+", "'P'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'a5,b7,c9,'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'a5,b7,c9,'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'a5,b7,c9,'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'a5,b7,c9,'", "+", "'-'", "*", "n", ")", "append", "(", "'-'", "*", "n", "+", "'Python'", "+", "'-'", "*", "n", ")", "return", "strings" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
init_benchmarks
Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benchmark are used. The generated list of strings is cached in the string_tables variable, which is indexed by n. Returns: A list of string prefix/suffix lengths.
performance/benchmarks/bm_regex_effbot.py
def init_benchmarks(n_values=None): """Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benchmark are used. The generated list of strings is cached in the string_tables variable, which is indexed by n. Returns: A list of string prefix/suffix lengths. """ if n_values is None: n_values = (0, 5, 50, 250, 1000, 5000, 10000) string_tables = {n: gen_string_table(n) for n in n_values} regexs = gen_regex_table() data = [] for n in n_values: for id in xrange(len(regexs)): regex = regexs[id] string = string_tables[n][id] data.append((regex, string)) return data
def init_benchmarks(n_values=None): """Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benchmark are used. The generated list of strings is cached in the string_tables variable, which is indexed by n. Returns: A list of string prefix/suffix lengths. """ if n_values is None: n_values = (0, 5, 50, 250, 1000, 5000, 10000) string_tables = {n: gen_string_table(n) for n in n_values} regexs = gen_regex_table() data = [] for n in n_values: for id in xrange(len(regexs)): regex = regexs[id] string = string_tables[n][id] data.append((regex, string)) return data
[ "Initialize", "the", "strings", "we", "ll", "run", "the", "regexes", "against", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_regex_effbot.py#L97-L126
[ "def", "init_benchmarks", "(", "n_values", "=", "None", ")", ":", "if", "n_values", "is", "None", ":", "n_values", "=", "(", "0", ",", "5", ",", "50", ",", "250", ",", "1000", ",", "5000", ",", "10000", ")", "string_tables", "=", "{", "n", ":", "gen_string_table", "(", "n", ")", "for", "n", "in", "n_values", "}", "regexs", "=", "gen_regex_table", "(", ")", "data", "=", "[", "]", "for", "n", "in", "n_values", ":", "for", "id", "in", "xrange", "(", "len", "(", "regexs", ")", ")", ":", "regex", "=", "regexs", "[", "id", "]", "string", "=", "string_tables", "[", "n", "]", "[", "id", "]", "data", ".", "append", "(", "(", "regex", ",", "string", ")", ")", "return", "data" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
combinations
Pure-Python implementation of itertools.combinations(l, 2).
performance/benchmarks/bm_nbody.py
def combinations(l): """Pure-Python implementation of itertools.combinations(l, 2).""" result = [] for x in xrange(len(l) - 1): ls = l[x + 1:] for y in ls: result.append((l[x], y)) return result
def combinations(l): """Pure-Python implementation of itertools.combinations(l, 2).""" result = [] for x in xrange(len(l) - 1): ls = l[x + 1:] for y in ls: result.append((l[x], y)) return result
[ "Pure", "-", "Python", "implementation", "of", "itertools", ".", "combinations", "(", "l", "2", ")", "." ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_nbody.py#L25-L32
[ "def", "combinations", "(", "l", ")", ":", "result", "=", "[", "]", "for", "x", "in", "xrange", "(", "len", "(", "l", ")", "-", "1", ")", ":", "ls", "=", "l", "[", "x", "+", "1", ":", "]", "for", "y", "in", "ls", ":", "result", ".", "append", "(", "(", "l", "[", "x", "]", ",", "y", ")", ")", "return", "result" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
Spline.GetDomain
Returns the domain of the B-Spline
performance/benchmarks/bm_chaos.py
def GetDomain(self): """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree])
def GetDomain(self): """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree])
[ "Returns", "the", "domain", "of", "the", "B", "-", "Spline" ]
python/performance
python
https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/benchmarks/bm_chaos.py#L95-L98
[ "def", "GetDomain", "(", "self", ")", ":", "return", "(", "self", ".", "knots", "[", "self", ".", "degree", "-", "1", "]", ",", "self", ".", "knots", "[", "len", "(", "self", ".", "knots", ")", "-", "self", ".", "degree", "]", ")" ]
2a9524c0a5714e85106671bc61d750e800fe17db
test
Mattermost.fetch_items
Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
perceval/backends/core/mattermost.py
def fetch_items(self, category, **kwargs): """Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Fetching messages of '%s' - '%s' channel from %s", self.url, self.channel, str(from_date)) fetching = True page = 0 nposts = 0 # Convert timestamp to integer for comparing since = int(from_date.timestamp() * 1000) while fetching: raw_posts = self.client.posts(self.channel, page=page) posts_before = nposts for post in self._parse_posts(raw_posts): if post['update_at'] < since: fetching = False break # Fetch user data user_id = post['user_id'] user = self._get_or_fetch_user(user_id) post['user_data'] = user yield post nposts += 1 if fetching: # If no new posts were fetched; stop the process if posts_before == nposts: fetching = False else: page += 1 logger.info("Fetch process completed: %s posts fetched", nposts)
def fetch_items(self, category, **kwargs): """Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Fetching messages of '%s' - '%s' channel from %s", self.url, self.channel, str(from_date)) fetching = True page = 0 nposts = 0 # Convert timestamp to integer for comparing since = int(from_date.timestamp() * 1000) while fetching: raw_posts = self.client.posts(self.channel, page=page) posts_before = nposts for post in self._parse_posts(raw_posts): if post['update_at'] < since: fetching = False break # Fetch user data user_id = post['user_id'] user = self._get_or_fetch_user(user_id) post['user_data'] = user yield post nposts += 1 if fetching: # If no new posts were fetched; stop the process if posts_before == nposts: fetching = False else: page += 1 logger.info("Fetch process completed: %s posts fetched", nposts)
[ "Fetch", "the", "messages", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L116-L161
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "logger", ".", "info", "(", "\"Fetching messages of '%s' - '%s' channel from %s\"", ",", "self", ".", "url", ",", "self", ".", "channel", ",", "str", "(", "from_date", ")", ")", "fetching", "=", "True", "page", "=", "0", "nposts", "=", "0", "# Convert timestamp to integer for comparing", "since", "=", "int", "(", "from_date", ".", "timestamp", "(", ")", "*", "1000", ")", "while", "fetching", ":", "raw_posts", "=", "self", ".", "client", ".", "posts", "(", "self", ".", "channel", ",", "page", "=", "page", ")", "posts_before", "=", "nposts", "for", "post", "in", "self", ".", "_parse_posts", "(", "raw_posts", ")", ":", "if", "post", "[", "'update_at'", "]", "<", "since", ":", "fetching", "=", "False", "break", "# Fetch user data", "user_id", "=", "post", "[", "'user_id'", "]", "user", "=", "self", ".", "_get_or_fetch_user", "(", "user_id", ")", "post", "[", "'user_data'", "]", "=", "user", "yield", "post", "nposts", "+=", "1", "if", "fetching", ":", "# If no new posts were fetched; stop the process", "if", "posts_before", "==", "nposts", ":", "fetching", "=", "False", "else", ":", "page", "+=", "1", "logger", ".", "info", "(", "\"Fetch process completed: %s posts fetched\"", ",", "nposts", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
Mattermost._init_client
Init client
perceval/backends/core/mattermost.py
def _init_client(self, from_archive=False): """Init client""" return MattermostClient(self.url, self.api_token, max_items=self.max_items, sleep_for_rate=self.sleep_for_rate, min_rate_to_sleep=self.min_rate_to_sleep, sleep_time=self.sleep_time, archive=self.archive, from_archive=from_archive)
def _init_client(self, from_archive=False): """Init client""" return MattermostClient(self.url, self.api_token, max_items=self.max_items, sleep_for_rate=self.sleep_for_rate, min_rate_to_sleep=self.min_rate_to_sleep, sleep_time=self.sleep_time, archive=self.archive, from_archive=from_archive)
[ "Init", "client" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L224-L232
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "MattermostClient", "(", "self", ".", "url", ",", "self", ".", "api_token", ",", "max_items", "=", "self", ".", "max_items", ",", "sleep_for_rate", "=", "self", ".", "sleep_for_rate", ",", "min_rate_to_sleep", "=", "self", ".", "min_rate_to_sleep", ",", "sleep_time", "=", "self", ".", "sleep_time", ",", "archive", "=", "self", ".", "archive", ",", "from_archive", "=", "from_archive", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
Mattermost._parse_posts
Parse posts and returns in order.
perceval/backends/core/mattermost.py
def _parse_posts(self, raw_posts): """Parse posts and returns in order.""" parsed_posts = self.parse_json(raw_posts) # Posts are not sorted. The order is provided by # 'order' key. for post_id in parsed_posts['order']: yield parsed_posts['posts'][post_id]
def _parse_posts(self, raw_posts): """Parse posts and returns in order.""" parsed_posts = self.parse_json(raw_posts) # Posts are not sorted. The order is provided by # 'order' key. for post_id in parsed_posts['order']: yield parsed_posts['posts'][post_id]
[ "Parse", "posts", "and", "returns", "in", "order", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L234-L242
[ "def", "_parse_posts", "(", "self", ",", "raw_posts", ")", ":", "parsed_posts", "=", "self", ".", "parse_json", "(", "raw_posts", ")", "# Posts are not sorted. The order is provided by", "# 'order' key.", "for", "post_id", "in", "parsed_posts", "[", "'order'", "]", ":", "yield", "parsed_posts", "[", "'posts'", "]", "[", "post_id", "]" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
MattermostClient.posts
Fetch the history of a channel.
perceval/backends/core/mattermost.py
def posts(self, channel, page=None): """Fetch the history of a channel.""" entrypoint = self.RCHANNELS + '/' + channel + '/' + self.RPOSTS params = { self.PPER_PAGE: self.max_items } if page is not None: params[self.PPAGE] = page response = self._fetch(entrypoint, params) return response
def posts(self, channel, page=None): """Fetch the history of a channel.""" entrypoint = self.RCHANNELS + '/' + channel + '/' + self.RPOSTS params = { self.PPER_PAGE: self.max_items } if page is not None: params[self.PPAGE] = page response = self._fetch(entrypoint, params) return response
[ "Fetch", "the", "history", "of", "a", "channel", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L297-L311
[ "def", "posts", "(", "self", ",", "channel", ",", "page", "=", "None", ")", ":", "entrypoint", "=", "self", ".", "RCHANNELS", "+", "'/'", "+", "channel", "+", "'/'", "+", "self", ".", "RPOSTS", "params", "=", "{", "self", ".", "PPER_PAGE", ":", "self", ".", "max_items", "}", "if", "page", "is", "not", "None", ":", "params", "[", "self", ".", "PPAGE", "]", "=", "page", "response", "=", "self", ".", "_fetch", "(", "entrypoint", ",", "params", ")", "return", "response" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
MattermostClient.user
Fetch user data.
perceval/backends/core/mattermost.py
def user(self, user): """Fetch user data.""" entrypoint = self.RUSERS + '/' + user response = self._fetch(entrypoint, None) return response
def user(self, user): """Fetch user data.""" entrypoint = self.RUSERS + '/' + user response = self._fetch(entrypoint, None) return response
[ "Fetch", "user", "data", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L313-L319
[ "def", "user", "(", "self", ",", "user", ")", ":", "entrypoint", "=", "self", ".", "RUSERS", "+", "'/'", "+", "user", "response", "=", "self", ".", "_fetch", "(", "entrypoint", ",", "None", ")", "return", "response" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
MattermostClient._fetch
Fetch a resource. :param entrypoint: entrypoint to access :param params: dict with the HTTP parameters needed to access the given entry point
perceval/backends/core/mattermost.py
def _fetch(self, entry_point, params): """Fetch a resource. :param entrypoint: entrypoint to access :param params: dict with the HTTP parameters needed to access the given entry point """ url = self.API_URL % {'base_url': self.base_url, 'entrypoint': entry_point} logger.debug("Mattermost client requests: %s params: %s", entry_point, str(params)) r = self.fetch(url, payload=params) return r.text
def _fetch(self, entry_point, params): """Fetch a resource. :param entrypoint: entrypoint to access :param params: dict with the HTTP parameters needed to access the given entry point """ url = self.API_URL % {'base_url': self.base_url, 'entrypoint': entry_point} logger.debug("Mattermost client requests: %s params: %s", entry_point, str(params)) r = self.fetch(url, payload=params) return r.text
[ "Fetch", "a", "resource", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L358-L372
[ "def", "_fetch", "(", "self", ",", "entry_point", ",", "params", ")", ":", "url", "=", "self", ".", "API_URL", "%", "{", "'base_url'", ":", "self", ".", "base_url", ",", "'entrypoint'", ":", "entry_point", "}", "logger", ".", "debug", "(", "\"Mattermost client requests: %s params: %s\"", ",", "entry_point", ",", "str", "(", "params", ")", ")", "r", "=", "self", ".", "fetch", "(", "url", ",", "payload", "=", "params", ")", "return", "r", ".", "text" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
PipermailCommand._pre_init
Initialize mailing lists directory path
perceval/backends/core/pipermail.py
def _pre_init(self): """Initialize mailing lists directory path""" if not self.parsed_args.mboxes_path: base_path = os.path.expanduser('~/.perceval/mailinglists/') dirpath = os.path.join(base_path, self.parsed_args.url) else: dirpath = self.parsed_args.mboxes_path setattr(self.parsed_args, 'dirpath', dirpath)
def _pre_init(self): """Initialize mailing lists directory path""" if not self.parsed_args.mboxes_path: base_path = os.path.expanduser('~/.perceval/mailinglists/') dirpath = os.path.join(base_path, self.parsed_args.url) else: dirpath = self.parsed_args.mboxes_path setattr(self.parsed_args, 'dirpath', dirpath)
[ "Initialize", "mailing", "lists", "directory", "path" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/pipermail.py#L136-L145
[ "def", "_pre_init", "(", "self", ")", ":", "if", "not", "self", ".", "parsed_args", ".", "mboxes_path", ":", "base_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.perceval/mailinglists/'", ")", "dirpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "self", ".", "parsed_args", ".", "url", ")", "else", ":", "dirpath", "=", "self", ".", "parsed_args", ".", "mboxes_path", "setattr", "(", "self", ".", "parsed_args", ",", "'dirpath'", ",", "dirpath", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
PipermailList.fetch
Fetch the mbox files from the remote archiver. Stores the archives in the path given during the initialization of this object. Those archives which a not valid extension will be ignored. Pipermail archives usually have on their file names the date of the archives stored following the schema year-month. When `from_date` property is called, it will return the mboxes which their year and month are equal or after that date. :param from_date: fetch archives that store messages equal or after the given date; only year and month values are compared :returns: a list of tuples, storing the links and paths of the fetched archives
perceval/backends/core/pipermail.py
def fetch(self, from_date=DEFAULT_DATETIME): """Fetch the mbox files from the remote archiver. Stores the archives in the path given during the initialization of this object. Those archives which a not valid extension will be ignored. Pipermail archives usually have on their file names the date of the archives stored following the schema year-month. When `from_date` property is called, it will return the mboxes which their year and month are equal or after that date. :param from_date: fetch archives that store messages equal or after the given date; only year and month values are compared :returns: a list of tuples, storing the links and paths of the fetched archives """ logger.info("Downloading mboxes from '%s' to since %s", self.url, str(from_date)) logger.debug("Storing mboxes in '%s'", self.dirpath) from_date = datetime_to_utc(from_date) r = requests.get(self.url, verify=self.verify) r.raise_for_status() links = self._parse_archive_links(r.text) fetched = [] if not os.path.exists(self.dirpath): os.makedirs(self.dirpath) for l in links: filename = os.path.basename(l) mbox_dt = self._parse_date_from_filepath(filename) if ((from_date.year == mbox_dt.year and from_date.month == mbox_dt.month) or from_date < mbox_dt): filepath = os.path.join(self.dirpath, filename) success = self._download_archive(l, filepath) if success: fetched.append((l, filepath)) logger.info("%s/%s MBoxes downloaded", len(fetched), len(links)) return fetched
def fetch(self, from_date=DEFAULT_DATETIME): """Fetch the mbox files from the remote archiver. Stores the archives in the path given during the initialization of this object. Those archives which a not valid extension will be ignored. Pipermail archives usually have on their file names the date of the archives stored following the schema year-month. When `from_date` property is called, it will return the mboxes which their year and month are equal or after that date. :param from_date: fetch archives that store messages equal or after the given date; only year and month values are compared :returns: a list of tuples, storing the links and paths of the fetched archives """ logger.info("Downloading mboxes from '%s' to since %s", self.url, str(from_date)) logger.debug("Storing mboxes in '%s'", self.dirpath) from_date = datetime_to_utc(from_date) r = requests.get(self.url, verify=self.verify) r.raise_for_status() links = self._parse_archive_links(r.text) fetched = [] if not os.path.exists(self.dirpath): os.makedirs(self.dirpath) for l in links: filename = os.path.basename(l) mbox_dt = self._parse_date_from_filepath(filename) if ((from_date.year == mbox_dt.year and from_date.month == mbox_dt.month) or from_date < mbox_dt): filepath = os.path.join(self.dirpath, filename) success = self._download_archive(l, filepath) if success: fetched.append((l, filepath)) logger.info("%s/%s MBoxes downloaded", len(fetched), len(links)) return fetched
[ "Fetch", "the", "mbox", "files", "from", "the", "remote", "archiver", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/pipermail.py#L185-L237
[ "def", "fetch", "(", "self", ",", "from_date", "=", "DEFAULT_DATETIME", ")", ":", "logger", ".", "info", "(", "\"Downloading mboxes from '%s' to since %s\"", ",", "self", ".", "url", ",", "str", "(", "from_date", ")", ")", "logger", ".", "debug", "(", "\"Storing mboxes in '%s'\"", ",", "self", ".", "dirpath", ")", "from_date", "=", "datetime_to_utc", "(", "from_date", ")", "r", "=", "requests", ".", "get", "(", "self", ".", "url", ",", "verify", "=", "self", ".", "verify", ")", "r", ".", "raise_for_status", "(", ")", "links", "=", "self", ".", "_parse_archive_links", "(", "r", ".", "text", ")", "fetched", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "dirpath", ")", ":", "os", ".", "makedirs", "(", "self", ".", "dirpath", ")", "for", "l", "in", "links", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "l", ")", "mbox_dt", "=", "self", ".", "_parse_date_from_filepath", "(", "filename", ")", "if", "(", "(", "from_date", ".", "year", "==", "mbox_dt", ".", "year", "and", "from_date", ".", "month", "==", "mbox_dt", ".", "month", ")", "or", "from_date", "<", "mbox_dt", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirpath", ",", "filename", ")", "success", "=", "self", ".", "_download_archive", "(", "l", ",", "filepath", ")", "if", "success", ":", "fetched", ".", "append", "(", "(", "l", ",", "filepath", ")", ")", "logger", ".", "info", "(", "\"%s/%s MBoxes downloaded\"", ",", "len", "(", "fetched", ")", ",", "len", "(", "links", ")", ")", "return", "fetched" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
PipermailList.mboxes
Get the mboxes managed by this mailing list. Returns the archives sorted by date in ascending order. :returns: a list of `.MBoxArchive` objects
perceval/backends/core/pipermail.py
def mboxes(self): """Get the mboxes managed by this mailing list. Returns the archives sorted by date in ascending order. :returns: a list of `.MBoxArchive` objects """ archives = [] for mbox in super().mboxes: dt = self._parse_date_from_filepath(mbox.filepath) archives.append((dt, mbox)) archives.sort(key=lambda x: x[0]) return [a[1] for a in archives]
def mboxes(self): """Get the mboxes managed by this mailing list. Returns the archives sorted by date in ascending order. :returns: a list of `.MBoxArchive` objects """ archives = [] for mbox in super().mboxes: dt = self._parse_date_from_filepath(mbox.filepath) archives.append((dt, mbox)) archives.sort(key=lambda x: x[0]) return [a[1] for a in archives]
[ "Get", "the", "mboxes", "managed", "by", "this", "mailing", "list", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/pipermail.py#L240-L255
[ "def", "mboxes", "(", "self", ")", ":", "archives", "=", "[", "]", "for", "mbox", "in", "super", "(", ")", ".", "mboxes", ":", "dt", "=", "self", ".", "_parse_date_from_filepath", "(", "mbox", ".", "filepath", ")", "archives", ".", "append", "(", "(", "dt", ",", "mbox", ")", ")", "archives", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "return", "[", "a", "[", "1", "]", "for", "a", "in", "archives", "]" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
RSS.fetch
Fetch the entries from the url. The method retrieves all entries from a RSS url :param category: the category of items to fetch :returns: a generator of entries
perceval/backends/core/rss.py
def fetch(self, category=CATEGORY_ENTRY): """Fetch the entries from the url. The method retrieves all entries from a RSS url :param category: the category of items to fetch :returns: a generator of entries """ kwargs = {} items = super().fetch(category, **kwargs) return items
def fetch(self, category=CATEGORY_ENTRY): """Fetch the entries from the url. The method retrieves all entries from a RSS url :param category: the category of items to fetch :returns: a generator of entries """ kwargs = {} items = super().fetch(category, **kwargs) return items
[ "Fetch", "the", "entries", "from", "the", "url", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/rss.py#L61-L73
[ "def", "fetch", "(", "self", ",", "category", "=", "CATEGORY_ENTRY", ")", ":", "kwargs", "=", "{", "}", "items", "=", "super", "(", ")", ".", "fetch", "(", "category", ",", "*", "*", "kwargs", ")", "return", "items" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
RSS.fetch_items
Fetch the entries :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
perceval/backends/core/rss.py
def fetch_items(self, category, **kwargs): """Fetch the entries :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ logger.info("Looking for rss entries at feed '%s'", self.url) nentries = 0 # number of entries raw_entries = self.client.get_entries() entries = self.parse_feed(raw_entries)['entries'] for item in entries: yield item nentries += 1 logger.info("Total number of entries: %i", nentries)
def fetch_items(self, category, **kwargs): """Fetch the entries :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ logger.info("Looking for rss entries at feed '%s'", self.url) nentries = 0 # number of entries raw_entries = self.client.get_entries() entries = self.parse_feed(raw_entries)['entries'] for item in entries: yield item nentries += 1 logger.info("Total number of entries: %i", nentries)
[ "Fetch", "the", "entries" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/rss.py#L75-L93
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "\"Looking for rss entries at feed '%s'\"", ",", "self", ".", "url", ")", "nentries", "=", "0", "# number of entries", "raw_entries", "=", "self", ".", "client", ".", "get_entries", "(", ")", "entries", "=", "self", ".", "parse_feed", "(", "raw_entries", ")", "[", "'entries'", "]", "for", "item", "in", "entries", ":", "yield", "item", "nentries", "+=", "1", "logger", ".", "info", "(", "\"Total number of entries: %i\"", ",", "nentries", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
RSS._init_client
Init client
perceval/backends/core/rss.py
def _init_client(self, from_archive=False): """Init client""" return RSSClient(self.url, self.archive, from_archive)
def _init_client(self, from_archive=False): """Init client""" return RSSClient(self.url, self.archive, from_archive)
[ "Init", "client" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/rss.py#L145-L148
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "RSSClient", "(", "self", ".", "url", ",", "self", ".", "archive", ",", "from_archive", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
RSSCommand.setup_cmd_parser
Returns the RSS argument parser.
perceval/backends/core/rss.py
def setup_cmd_parser(cls): """Returns the RSS argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, archive=True) # Required arguments parser.parser.add_argument('url', help="URL of the RSS feed") return parser
def setup_cmd_parser(cls): """Returns the RSS argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, archive=True) # Required arguments parser.parser.add_argument('url', help="URL of the RSS feed") return parser
[ "Returns", "the", "RSS", "argument", "parser", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/rss.py#L180-L190
[ "def", "setup_cmd_parser", "(", "cls", ")", ":", "parser", "=", "BackendCommandArgumentParser", "(", "cls", ".", "BACKEND", ".", "CATEGORIES", ",", "archive", "=", "True", ")", "# Required arguments", "parser", ".", "parser", ".", "add_argument", "(", "'url'", ",", "help", "=", "\"URL of the RSS feed\"", ")", "return", "parser" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaREST.fetch
Fetch the bugs from the repository. The method retrieves, from a Bugzilla repository, the bugs updated since the given date. :param category: the category of items to fetch :param from_date: obtain bugs updated since this date :returns: a generator of bugs
perceval/backends/core/bugzillarest.py
def fetch(self, category=CATEGORY_BUG, from_date=DEFAULT_DATETIME): """Fetch the bugs from the repository. The method retrieves, from a Bugzilla repository, the bugs updated since the given date. :param category: the category of items to fetch :param from_date: obtain bugs updated since this date :returns: a generator of bugs """ if not from_date: from_date = DEFAULT_DATETIME kwargs = {'from_date': from_date} items = super().fetch(category, **kwargs) return items
def fetch(self, category=CATEGORY_BUG, from_date=DEFAULT_DATETIME): """Fetch the bugs from the repository. The method retrieves, from a Bugzilla repository, the bugs updated since the given date. :param category: the category of items to fetch :param from_date: obtain bugs updated since this date :returns: a generator of bugs """ if not from_date: from_date = DEFAULT_DATETIME kwargs = {'from_date': from_date} items = super().fetch(category, **kwargs) return items
[ "Fetch", "the", "bugs", "from", "the", "repository", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L79-L96
[ "def", "fetch", "(", "self", ",", "category", "=", "CATEGORY_BUG", ",", "from_date", "=", "DEFAULT_DATETIME", ")", ":", "if", "not", "from_date", ":", "from_date", "=", "DEFAULT_DATETIME", "kwargs", "=", "{", "'from_date'", ":", "from_date", "}", "items", "=", "super", "(", ")", ".", "fetch", "(", "category", ",", "*", "*", "kwargs", ")", "return", "items" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaREST.fetch_items
Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
perceval/backends/core/bugzillarest.py
def fetch_items(self, category, **kwargs): """Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for bugs: '%s' updated from '%s'", self.url, str(from_date)) nbugs = 0 for bug in self.__fetch_and_parse_bugs(from_date): nbugs += 1 yield bug logger.info("Fetch process completed: %s bugs fetched", nbugs)
def fetch_items(self, category, **kwargs): """Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for bugs: '%s' updated from '%s'", self.url, str(from_date)) nbugs = 0 for bug in self.__fetch_and_parse_bugs(from_date): nbugs += 1 yield bug logger.info("Fetch process completed: %s bugs fetched", nbugs)
[ "Fetch", "the", "bugs" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L98-L117
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "logger", ".", "info", "(", "\"Looking for bugs: '%s' updated from '%s'\"", ",", "self", ".", "url", ",", "str", "(", "from_date", ")", ")", "nbugs", "=", "0", "for", "bug", "in", "self", ".", "__fetch_and_parse_bugs", "(", "from_date", ")", ":", "nbugs", "+=", "1", "yield", "bug", "logger", ".", "info", "(", "\"Fetch process completed: %s bugs fetched\"", ",", "nbugs", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaREST._init_client
Init client
perceval/backends/core/bugzillarest.py
def _init_client(self, from_archive=False): """Init client""" return BugzillaRESTClient(self.url, user=self.user, password=self.password, api_token=self.api_token, archive=self.archive, from_archive=from_archive)
def _init_client(self, from_archive=False): """Init client""" return BugzillaRESTClient(self.url, user=self.user, password=self.password, api_token=self.api_token, archive=self.archive, from_archive=from_archive)
[ "Init", "client" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L167-L171
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "BugzillaRESTClient", "(", "self", ".", "url", ",", "user", "=", "self", ".", "user", ",", "password", "=", "self", ".", "password", ",", "api_token", "=", "self", ".", "api_token", ",", "archive", "=", "self", ".", "archive", ",", "from_archive", "=", "from_archive", ")" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.login
Authenticate a user in the server. :param user: Bugzilla user :param password: user password
perceval/backends/core/bugzillarest.py
def login(self, user, password): """Authenticate a user in the server. :param user: Bugzilla user :param password: user password """ params = { self.PBUGZILLA_LOGIN: user, self.PBUGZILLA_PASSWORD: password } try: r = self.call(self.RLOGIN, params) except requests.exceptions.HTTPError as e: cause = ("Bugzilla REST client could not authenticate user %s. " "See exception: %s") % (user, str(e)) raise BackendError(cause=cause) data = json.loads(r) self.api_token = data['token']
def login(self, user, password): """Authenticate a user in the server. :param user: Bugzilla user :param password: user password """ params = { self.PBUGZILLA_LOGIN: user, self.PBUGZILLA_PASSWORD: password } try: r = self.call(self.RLOGIN, params) except requests.exceptions.HTTPError as e: cause = ("Bugzilla REST client could not authenticate user %s. " "See exception: %s") % (user, str(e)) raise BackendError(cause=cause) data = json.loads(r) self.api_token = data['token']
[ "Authenticate", "a", "user", "in", "the", "server", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L305-L324
[ "def", "login", "(", "self", ",", "user", ",", "password", ")", ":", "params", "=", "{", "self", ".", "PBUGZILLA_LOGIN", ":", "user", ",", "self", ".", "PBUGZILLA_PASSWORD", ":", "password", "}", "try", ":", "r", "=", "self", ".", "call", "(", "self", ".", "RLOGIN", ",", "params", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "e", ":", "cause", "=", "(", "\"Bugzilla REST client could not authenticate user %s. \"", "\"See exception: %s\"", ")", "%", "(", "user", ",", "str", "(", "e", ")", ")", "raise", "BackendError", "(", "cause", "=", "cause", ")", "data", "=", "json", ".", "loads", "(", "r", ")", "self", ".", "api_token", "=", "data", "[", "'token'", "]" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.bugs
Get the information of a list of bugs. :param from_date: retrieve bugs that where updated from that date; dates are converted to UTC :param offset: starting position for the search; i.e to return 11th element, set this value to 10. :param max_bugs: maximum number of bugs to reteurn per query
perceval/backends/core/bugzillarest.py
def bugs(self, from_date=DEFAULT_DATETIME, offset=None, max_bugs=MAX_BUGS): """Get the information of a list of bugs. :param from_date: retrieve bugs that where updated from that date; dates are converted to UTC :param offset: starting position for the search; i.e to return 11th element, set this value to 10. :param max_bugs: maximum number of bugs to reteurn per query """ date = datetime_to_utc(from_date) date = date.strftime("%Y-%m-%dT%H:%M:%SZ") params = { self.PLAST_CHANGE_TIME: date, self.PLIMIT: max_bugs, self.PORDER: self.VCHANGE_DATE_ORDER, self.PINCLUDE_FIELDS: self.VINCLUDE_ALL } if offset: params[self.POFFSET] = offset response = self.call(self.RBUG, params) return response
def bugs(self, from_date=DEFAULT_DATETIME, offset=None, max_bugs=MAX_BUGS): """Get the information of a list of bugs. :param from_date: retrieve bugs that where updated from that date; dates are converted to UTC :param offset: starting position for the search; i.e to return 11th element, set this value to 10. :param max_bugs: maximum number of bugs to reteurn per query """ date = datetime_to_utc(from_date) date = date.strftime("%Y-%m-%dT%H:%M:%SZ") params = { self.PLAST_CHANGE_TIME: date, self.PLIMIT: max_bugs, self.PORDER: self.VCHANGE_DATE_ORDER, self.PINCLUDE_FIELDS: self.VINCLUDE_ALL } if offset: params[self.POFFSET] = offset response = self.call(self.RBUG, params) return response
[ "Get", "the", "information", "of", "a", "list", "of", "bugs", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L326-L350
[ "def", "bugs", "(", "self", ",", "from_date", "=", "DEFAULT_DATETIME", ",", "offset", "=", "None", ",", "max_bugs", "=", "MAX_BUGS", ")", ":", "date", "=", "datetime_to_utc", "(", "from_date", ")", "date", "=", "date", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", "params", "=", "{", "self", ".", "PLAST_CHANGE_TIME", ":", "date", ",", "self", ".", "PLIMIT", ":", "max_bugs", ",", "self", ".", "PORDER", ":", "self", ".", "VCHANGE_DATE_ORDER", ",", "self", ".", "PINCLUDE_FIELDS", ":", "self", ".", "VINCLUDE_ALL", "}", "if", "offset", ":", "params", "[", "self", ".", "POFFSET", "]", "=", "offset", "response", "=", "self", ".", "call", "(", "self", ".", "RBUG", ",", "params", ")", "return", "response" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.comments
Get the comments of the given bugs. :param bug_ids: list of bug identifiers
perceval/backends/core/bugzillarest.py
def comments(self, *bug_ids): """Get the comments of the given bugs. :param bug_ids: list of bug identifiers """ # Hack. The first value must be a valid bug id resource = urijoin(self.RBUG, bug_ids[0], self.RCOMMENT) params = { self.PIDS: bug_ids } response = self.call(resource, params) return response
def comments(self, *bug_ids): """Get the comments of the given bugs. :param bug_ids: list of bug identifiers """ # Hack. The first value must be a valid bug id resource = urijoin(self.RBUG, bug_ids[0], self.RCOMMENT) params = { self.PIDS: bug_ids } response = self.call(resource, params) return response
[ "Get", "the", "comments", "of", "the", "given", "bugs", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L352-L366
[ "def", "comments", "(", "self", ",", "*", "bug_ids", ")", ":", "# Hack. The first value must be a valid bug id", "resource", "=", "urijoin", "(", "self", ".", "RBUG", ",", "bug_ids", "[", "0", "]", ",", "self", ".", "RCOMMENT", ")", "params", "=", "{", "self", ".", "PIDS", ":", "bug_ids", "}", "response", "=", "self", ".", "call", "(", "resource", ",", "params", ")", "return", "response" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.history
Get the history of the given bugs. :param bug_ids: list of bug identifiers
perceval/backends/core/bugzillarest.py
def history(self, *bug_ids): """Get the history of the given bugs. :param bug_ids: list of bug identifiers """ resource = urijoin(self.RBUG, bug_ids[0], self.RHISTORY) params = { self.PIDS: bug_ids } response = self.call(resource, params) return response
def history(self, *bug_ids): """Get the history of the given bugs. :param bug_ids: list of bug identifiers """ resource = urijoin(self.RBUG, bug_ids[0], self.RHISTORY) params = { self.PIDS: bug_ids } response = self.call(resource, params) return response
[ "Get", "the", "history", "of", "the", "given", "bugs", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L368-L381
[ "def", "history", "(", "self", ",", "*", "bug_ids", ")", ":", "resource", "=", "urijoin", "(", "self", ".", "RBUG", ",", "bug_ids", "[", "0", "]", ",", "self", ".", "RHISTORY", ")", "params", "=", "{", "self", ".", "PIDS", ":", "bug_ids", "}", "response", "=", "self", ".", "call", "(", "resource", ",", "params", ")", "return", "response" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.attachments
Get the attachments of the given bugs. :param bug_id: list of bug identifiers
perceval/backends/core/bugzillarest.py
def attachments(self, *bug_ids): """Get the attachments of the given bugs. :param bug_id: list of bug identifiers """ resource = urijoin(self.RBUG, bug_ids[0], self.RATTACHMENT) params = { self.PIDS: bug_ids, self.PEXCLUDE_FIELDS: self.VEXCLUDE_ATTCH_DATA } response = self.call(resource, params) return response
def attachments(self, *bug_ids): """Get the attachments of the given bugs. :param bug_id: list of bug identifiers """ resource = urijoin(self.RBUG, bug_ids[0], self.RATTACHMENT) params = { self.PIDS: bug_ids, self.PEXCLUDE_FIELDS: self.VEXCLUDE_ATTCH_DATA } response = self.call(resource, params) return response
[ "Get", "the", "attachments", "of", "the", "given", "bugs", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L383-L397
[ "def", "attachments", "(", "self", ",", "*", "bug_ids", ")", ":", "resource", "=", "urijoin", "(", "self", ".", "RBUG", ",", "bug_ids", "[", "0", "]", ",", "self", ".", "RATTACHMENT", ")", "params", "=", "{", "self", ".", "PIDS", ":", "bug_ids", ",", "self", ".", "PEXCLUDE_FIELDS", ":", "self", ".", "VEXCLUDE_ATTCH_DATA", "}", "response", "=", "self", ".", "call", "(", "resource", ",", "params", ")", "return", "response" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.call
Retrive the given resource. :param resource: resource to retrieve :param params: dict with the HTTP parameters needed to retrieve the given resource :raises BugzillaRESTError: raised when an error is returned by the server
perceval/backends/core/bugzillarest.py
def call(self, resource, params): """Retrive the given resource. :param resource: resource to retrieve :param params: dict with the HTTP parameters needed to retrieve the given resource :raises BugzillaRESTError: raised when an error is returned by the server """ url = self.URL % {'base': self.base_url, 'resource': resource} if self.api_token: params[self.PBUGZILLA_TOKEN] = self.api_token logger.debug("Bugzilla REST client requests: %s params: %s", resource, str(params)) r = self.fetch(url, payload=params) # Check for possible Bugzilla API errors result = r.json() if result.get('error', False): raise BugzillaRESTError(error=result['message'], code=result['code']) return r.text
def call(self, resource, params): """Retrive the given resource. :param resource: resource to retrieve :param params: dict with the HTTP parameters needed to retrieve the given resource :raises BugzillaRESTError: raised when an error is returned by the server """ url = self.URL % {'base': self.base_url, 'resource': resource} if self.api_token: params[self.PBUGZILLA_TOKEN] = self.api_token logger.debug("Bugzilla REST client requests: %s params: %s", resource, str(params)) r = self.fetch(url, payload=params) # Check for possible Bugzilla API errors result = r.json() if result.get('error', False): raise BugzillaRESTError(error=result['message'], code=result['code']) return r.text
[ "Retrive", "the", "given", "resource", "." ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L399-L426
[ "def", "call", "(", "self", ",", "resource", ",", "params", ")", ":", "url", "=", "self", ".", "URL", "%", "{", "'base'", ":", "self", ".", "base_url", ",", "'resource'", ":", "resource", "}", "if", "self", ".", "api_token", ":", "params", "[", "self", ".", "PBUGZILLA_TOKEN", "]", "=", "self", ".", "api_token", "logger", ".", "debug", "(", "\"Bugzilla REST client requests: %s params: %s\"", ",", "resource", ",", "str", "(", "params", ")", ")", "r", "=", "self", ".", "fetch", "(", "url", ",", "payload", "=", "params", ")", "# Check for possible Bugzilla API errors", "result", "=", "r", ".", "json", "(", ")", "if", "result", ".", "get", "(", "'error'", ",", "False", ")", ":", "raise", "BugzillaRESTError", "(", "error", "=", "result", "[", "'message'", "]", ",", "code", "=", "result", "[", "'code'", "]", ")", "return", "r", ".", "text" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
BugzillaRESTClient.sanitize_for_archive
Sanitize payload of a HTTP request by removing the login, password and token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :returns url, headers and the sanitized payload
perceval/backends/core/bugzillarest.py
def sanitize_for_archive(url, headers, payload): """Sanitize payload of a HTTP request by removing the login, password and token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :returns url, headers and the sanitized payload """ if BugzillaRESTClient.PBUGZILLA_LOGIN in payload: payload.pop(BugzillaRESTClient.PBUGZILLA_LOGIN) if BugzillaRESTClient.PBUGZILLA_PASSWORD in payload: payload.pop(BugzillaRESTClient.PBUGZILLA_PASSWORD) if BugzillaRESTClient.PBUGZILLA_TOKEN in payload: payload.pop(BugzillaRESTClient.PBUGZILLA_TOKEN) return url, headers, payload
def sanitize_for_archive(url, headers, payload): """Sanitize payload of a HTTP request by removing the login, password and token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :returns url, headers and the sanitized payload """ if BugzillaRESTClient.PBUGZILLA_LOGIN in payload: payload.pop(BugzillaRESTClient.PBUGZILLA_LOGIN) if BugzillaRESTClient.PBUGZILLA_PASSWORD in payload: payload.pop(BugzillaRESTClient.PBUGZILLA_PASSWORD) if BugzillaRESTClient.PBUGZILLA_TOKEN in payload: payload.pop(BugzillaRESTClient.PBUGZILLA_TOKEN) return url, headers, payload
[ "Sanitize", "payload", "of", "a", "HTTP", "request", "by", "removing", "the", "login", "password", "and", "token", "information", "before", "storing", "/", "retrieving", "archived", "items" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/bugzillarest.py#L429-L448
[ "def", "sanitize_for_archive", "(", "url", ",", "headers", ",", "payload", ")", ":", "if", "BugzillaRESTClient", ".", "PBUGZILLA_LOGIN", "in", "payload", ":", "payload", ".", "pop", "(", "BugzillaRESTClient", ".", "PBUGZILLA_LOGIN", ")", "if", "BugzillaRESTClient", ".", "PBUGZILLA_PASSWORD", "in", "payload", ":", "payload", ".", "pop", "(", "BugzillaRESTClient", ".", "PBUGZILLA_PASSWORD", ")", "if", "BugzillaRESTClient", ".", "PBUGZILLA_TOKEN", "in", "payload", ":", "payload", ".", "pop", "(", "BugzillaRESTClient", ".", "PBUGZILLA_TOKEN", ")", "return", "url", ",", "headers", ",", "payload" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
GitLab.fetch_items
Fetch the items (issues or merge_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
perceval/backends/core/gitlab.py
def fetch_items(self, category, **kwargs): """Fetch the items (issues or merge_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] if category == CATEGORY_ISSUE: items = self.__fetch_issues(from_date) else: items = self.__fetch_merge_requests(from_date) return items
def fetch_items(self, category, **kwargs): """Fetch the items (issues or merge_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] if category == CATEGORY_ISSUE: items = self.__fetch_issues(from_date) else: items = self.__fetch_merge_requests(from_date) return items
[ "Fetch", "the", "items", "(", "issues", "or", "merge_requests", ")" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L131-L146
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "if", "category", "==", "CATEGORY_ISSUE", ":", "items", "=", "self", ".", "__fetch_issues", "(", "from_date", ")", "else", ":", "items", "=", "self", ".", "__fetch_merge_requests", "(", "from_date", ")", "return", "items" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
GitLab.__fetch_issues
Fetch the issues
perceval/backends/core/gitlab.py
def __fetch_issues(self, from_date): """Fetch the issues""" issues_groups = self.client.issues(from_date=from_date) for raw_issues in issues_groups: issues = json.loads(raw_issues) for issue in issues: issue_id = issue['iid'] if self.blacklist_ids and issue_id in self.blacklist_ids: logger.warning("Skipping blacklisted issue %s", issue_id) continue self.__init_issue_extra_fields(issue) issue['notes_data'] = \ self.__get_issue_notes(issue_id) issue['award_emoji_data'] = \ self.__get_award_emoji(GitLabClient.ISSUES, issue_id) yield issue
def __fetch_issues(self, from_date): """Fetch the issues""" issues_groups = self.client.issues(from_date=from_date) for raw_issues in issues_groups: issues = json.loads(raw_issues) for issue in issues: issue_id = issue['iid'] if self.blacklist_ids and issue_id in self.blacklist_ids: logger.warning("Skipping blacklisted issue %s", issue_id) continue self.__init_issue_extra_fields(issue) issue['notes_data'] = \ self.__get_issue_notes(issue_id) issue['award_emoji_data'] = \ self.__get_award_emoji(GitLabClient.ISSUES, issue_id) yield issue
[ "Fetch", "the", "issues" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L209-L230
[ "def", "__fetch_issues", "(", "self", ",", "from_date", ")", ":", "issues_groups", "=", "self", ".", "client", ".", "issues", "(", "from_date", "=", "from_date", ")", "for", "raw_issues", "in", "issues_groups", ":", "issues", "=", "json", ".", "loads", "(", "raw_issues", ")", "for", "issue", "in", "issues", ":", "issue_id", "=", "issue", "[", "'iid'", "]", "if", "self", ".", "blacklist_ids", "and", "issue_id", "in", "self", ".", "blacklist_ids", ":", "logger", ".", "warning", "(", "\"Skipping blacklisted issue %s\"", ",", "issue_id", ")", "continue", "self", ".", "__init_issue_extra_fields", "(", "issue", ")", "issue", "[", "'notes_data'", "]", "=", "self", ".", "__get_issue_notes", "(", "issue_id", ")", "issue", "[", "'award_emoji_data'", "]", "=", "self", ".", "__get_award_emoji", "(", "GitLabClient", ".", "ISSUES", ",", "issue_id", ")", "yield", "issue" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
GitLab.__get_issue_notes
Get issue notes
perceval/backends/core/gitlab.py
def __get_issue_notes(self, issue_id): """Get issue notes""" notes = [] group_notes = self.client.notes(GitLabClient.ISSUES, issue_id) for raw_notes in group_notes: for note in json.loads(raw_notes): note_id = note['id'] note['award_emoji_data'] = \ self.__get_note_award_emoji(GitLabClient.ISSUES, issue_id, note_id) notes.append(note) return notes
def __get_issue_notes(self, issue_id): """Get issue notes""" notes = [] group_notes = self.client.notes(GitLabClient.ISSUES, issue_id) for raw_notes in group_notes: for note in json.loads(raw_notes): note_id = note['id'] note['award_emoji_data'] = \ self.__get_note_award_emoji(GitLabClient.ISSUES, issue_id, note_id) notes.append(note) return notes
[ "Get", "issue", "notes" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L232-L247
[ "def", "__get_issue_notes", "(", "self", ",", "issue_id", ")", ":", "notes", "=", "[", "]", "group_notes", "=", "self", ".", "client", ".", "notes", "(", "GitLabClient", ".", "ISSUES", ",", "issue_id", ")", "for", "raw_notes", "in", "group_notes", ":", "for", "note", "in", "json", ".", "loads", "(", "raw_notes", ")", ":", "note_id", "=", "note", "[", "'id'", "]", "note", "[", "'award_emoji_data'", "]", "=", "self", ".", "__get_note_award_emoji", "(", "GitLabClient", ".", "ISSUES", ",", "issue_id", ",", "note_id", ")", "notes", ".", "append", "(", "note", ")", "return", "notes" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
GitLab.__fetch_merge_requests
Fetch the merge requests
perceval/backends/core/gitlab.py
def __fetch_merge_requests(self, from_date): """Fetch the merge requests""" merges_groups = self.client.merges(from_date=from_date) for raw_merges in merges_groups: merges = json.loads(raw_merges) for merge in merges: merge_id = merge['iid'] if self.blacklist_ids and merge_id in self.blacklist_ids: logger.warning("Skipping blacklisted merge request %s", merge_id) continue # The single merge_request API call returns a more # complete merge request, thus we inflate it with # other data (e.g., notes, emojis, versions) merge_full_raw = self.client.merge(merge_id) merge_full = json.loads(merge_full_raw) self.__init_merge_extra_fields(merge_full) merge_full['notes_data'] = self.__get_merge_notes(merge_id) merge_full['award_emoji_data'] = self.__get_award_emoji(GitLabClient.MERGES, merge_id) merge_full['versions_data'] = self.__get_merge_versions(merge_id) yield merge_full
def __fetch_merge_requests(self, from_date): """Fetch the merge requests""" merges_groups = self.client.merges(from_date=from_date) for raw_merges in merges_groups: merges = json.loads(raw_merges) for merge in merges: merge_id = merge['iid'] if self.blacklist_ids and merge_id in self.blacklist_ids: logger.warning("Skipping blacklisted merge request %s", merge_id) continue # The single merge_request API call returns a more # complete merge request, thus we inflate it with # other data (e.g., notes, emojis, versions) merge_full_raw = self.client.merge(merge_id) merge_full = json.loads(merge_full_raw) self.__init_merge_extra_fields(merge_full) merge_full['notes_data'] = self.__get_merge_notes(merge_id) merge_full['award_emoji_data'] = self.__get_award_emoji(GitLabClient.MERGES, merge_id) merge_full['versions_data'] = self.__get_merge_versions(merge_id) yield merge_full
[ "Fetch", "the", "merge", "requests" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L249-L275
[ "def", "__fetch_merge_requests", "(", "self", ",", "from_date", ")", ":", "merges_groups", "=", "self", ".", "client", ".", "merges", "(", "from_date", "=", "from_date", ")", "for", "raw_merges", "in", "merges_groups", ":", "merges", "=", "json", ".", "loads", "(", "raw_merges", ")", "for", "merge", "in", "merges", ":", "merge_id", "=", "merge", "[", "'iid'", "]", "if", "self", ".", "blacklist_ids", "and", "merge_id", "in", "self", ".", "blacklist_ids", ":", "logger", ".", "warning", "(", "\"Skipping blacklisted merge request %s\"", ",", "merge_id", ")", "continue", "# The single merge_request API call returns a more", "# complete merge request, thus we inflate it with", "# other data (e.g., notes, emojis, versions)", "merge_full_raw", "=", "self", ".", "client", ".", "merge", "(", "merge_id", ")", "merge_full", "=", "json", ".", "loads", "(", "merge_full_raw", ")", "self", ".", "__init_merge_extra_fields", "(", "merge_full", ")", "merge_full", "[", "'notes_data'", "]", "=", "self", ".", "__get_merge_notes", "(", "merge_id", ")", "merge_full", "[", "'award_emoji_data'", "]", "=", "self", ".", "__get_award_emoji", "(", "GitLabClient", ".", "MERGES", ",", "merge_id", ")", "merge_full", "[", "'versions_data'", "]", "=", "self", ".", "__get_merge_versions", "(", "merge_id", ")", "yield", "merge_full" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
GitLab.__get_merge_notes
Get merge notes
perceval/backends/core/gitlab.py
def __get_merge_notes(self, merge_id): """Get merge notes""" notes = [] group_notes = self.client.notes(GitLabClient.MERGES, merge_id) for raw_notes in group_notes: for note in json.loads(raw_notes): note_id = note['id'] note['award_emoji_data'] = \ self.__get_note_award_emoji(GitLabClient.MERGES, merge_id, note_id) notes.append(note) return notes
def __get_merge_notes(self, merge_id): """Get merge notes""" notes = [] group_notes = self.client.notes(GitLabClient.MERGES, merge_id) for raw_notes in group_notes: for note in json.loads(raw_notes): note_id = note['id'] note['award_emoji_data'] = \ self.__get_note_award_emoji(GitLabClient.MERGES, merge_id, note_id) notes.append(note) return notes
[ "Get", "merge", "notes" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L277-L291
[ "def", "__get_merge_notes", "(", "self", ",", "merge_id", ")", ":", "notes", "=", "[", "]", "group_notes", "=", "self", ".", "client", ".", "notes", "(", "GitLabClient", ".", "MERGES", ",", "merge_id", ")", "for", "raw_notes", "in", "group_notes", ":", "for", "note", "in", "json", ".", "loads", "(", "raw_notes", ")", ":", "note_id", "=", "note", "[", "'id'", "]", "note", "[", "'award_emoji_data'", "]", "=", "self", ".", "__get_note_award_emoji", "(", "GitLabClient", ".", "MERGES", ",", "merge_id", ",", "note_id", ")", "notes", ".", "append", "(", "note", ")", "return", "notes" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e
test
GitLab.__get_merge_versions
Get merge versions
perceval/backends/core/gitlab.py
def __get_merge_versions(self, merge_id): """Get merge versions""" versions = [] group_versions = self.client.merge_versions(merge_id) for raw_versions in group_versions: for version in json.loads(raw_versions): version_id = version['id'] version_full_raw = self.client.merge_version(merge_id, version_id) version_full = json.loads(version_full_raw) version_full.pop('diffs', None) versions.append(version_full) return versions
def __get_merge_versions(self, merge_id): """Get merge versions""" versions = [] group_versions = self.client.merge_versions(merge_id) for raw_versions in group_versions: for version in json.loads(raw_versions): version_id = version['id'] version_full_raw = self.client.merge_version(merge_id, version_id) version_full = json.loads(version_full_raw) version_full.pop('diffs', None) versions.append(version_full) return versions
[ "Get", "merge", "versions" ]
chaoss/grimoirelab-perceval
python
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L293-L309
[ "def", "__get_merge_versions", "(", "self", ",", "merge_id", ")", ":", "versions", "=", "[", "]", "group_versions", "=", "self", ".", "client", ".", "merge_versions", "(", "merge_id", ")", "for", "raw_versions", "in", "group_versions", ":", "for", "version", "in", "json", ".", "loads", "(", "raw_versions", ")", ":", "version_id", "=", "version", "[", "'id'", "]", "version_full_raw", "=", "self", ".", "client", ".", "merge_version", "(", "merge_id", ",", "version_id", ")", "version_full", "=", "json", ".", "loads", "(", "version_full_raw", ")", "version_full", ".", "pop", "(", "'diffs'", ",", "None", ")", "versions", ".", "append", "(", "version_full", ")", "return", "versions" ]
41c908605e88b7ebc3a536c643fa0f212eaf9e0e