id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
249,200 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess._find_models | def _find_models(self, constructor, table_name, constraints=None, *, columns=None,
order_by=None, limiting=None):
"""Calls DataAccess.find_all and passes the results to the given constructor."""
for record in self.find_all(table_name, constraints, columns=columns, order_by=order_by,
limiting=limiting):
yield constructor(record) | python | def _find_models(self, constructor, table_name, constraints=None, *, columns=None,
order_by=None, limiting=None):
"""Calls DataAccess.find_all and passes the results to the given constructor."""
for record in self.find_all(table_name, constraints, columns=columns, order_by=order_by,
limiting=limiting):
yield constructor(record) | [
"def",
"_find_models",
"(",
"self",
",",
"constructor",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"limiting",
"=",
"None",
")",
":",
"for",
"record",
"in",
"self",
".",
"find_all",
"(",
"table_name",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
",",
"limiting",
"=",
"limiting",
")",
":",
"yield",
"constructor",
"(",
"record",
")"
] | Calls DataAccess.find_all and passes the results to the given constructor. | [
"Calls",
"DataAccess",
".",
"find_all",
"and",
"passes",
"the",
"results",
"to",
"the",
"given",
"constructor",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L16-L21 |
249,201 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.find_model | def find_model(self, constructor, constraints=None, *, columns=None, table_name=None,
order_by=None):
"""Specialization of DataAccess.find that returns a model instead of cursor object."""
return self._find_model(constructor, table_name or constructor.table_name, constraints,
columns=columns, order_by=order_by) | python | def find_model(self, constructor, constraints=None, *, columns=None, table_name=None,
order_by=None):
"""Specialization of DataAccess.find that returns a model instead of cursor object."""
return self._find_model(constructor, table_name or constructor.table_name, constraints,
columns=columns, order_by=order_by) | [
"def",
"find_model",
"(",
"self",
",",
"constructor",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"table_name",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"return",
"self",
".",
"_find_model",
"(",
"constructor",
",",
"table_name",
"or",
"constructor",
".",
"table_name",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
")"
] | Specialization of DataAccess.find that returns a model instead of cursor object. | [
"Specialization",
"of",
"DataAccess",
".",
"find",
"that",
"returns",
"a",
"model",
"instead",
"of",
"cursor",
"object",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L23-L27 |
249,202 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.find_models | def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,
limiting=None, table_name=None):
"""Specialization of DataAccess.find_all that returns models instead of cursor objects."""
return self._find_models(
constructor, table_name or constructor.table_name, constraints, columns=columns,
order_by=order_by, limiting=limiting) | python | def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,
limiting=None, table_name=None):
"""Specialization of DataAccess.find_all that returns models instead of cursor objects."""
return self._find_models(
constructor, table_name or constructor.table_name, constraints, columns=columns,
order_by=order_by, limiting=limiting) | [
"def",
"find_models",
"(",
"self",
",",
"constructor",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"limiting",
"=",
"None",
",",
"table_name",
"=",
"None",
")",
":",
"return",
"self",
".",
"_find_models",
"(",
"constructor",
",",
"table_name",
"or",
"constructor",
".",
"table_name",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
",",
"limiting",
"=",
"limiting",
")"
] | Specialization of DataAccess.find_all that returns models instead of cursor objects. | [
"Specialization",
"of",
"DataAccess",
".",
"find_all",
"that",
"returns",
"models",
"instead",
"of",
"cursor",
"objects",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L29-L34 |
249,203 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.page_models | def page_models(self, constructor, paging, constraints=None, *, columns=None, order_by=None):
"""Specialization of DataAccess.page that returns models instead of cursor objects."""
records, count = self.page(constructor.table_name, paging, constraints, columns=columns,
order_by=order_by)
return ([constructor(r) for r in records], count) | python | def page_models(self, constructor, paging, constraints=None, *, columns=None, order_by=None):
"""Specialization of DataAccess.page that returns models instead of cursor objects."""
records, count = self.page(constructor.table_name, paging, constraints, columns=columns,
order_by=order_by)
return ([constructor(r) for r in records], count) | [
"def",
"page_models",
"(",
"self",
",",
"constructor",
",",
"paging",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"records",
",",
"count",
"=",
"self",
".",
"page",
"(",
"constructor",
".",
"table_name",
",",
"paging",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
")",
"return",
"(",
"[",
"constructor",
"(",
"r",
")",
"for",
"r",
"in",
"records",
"]",
",",
"count",
")"
] | Specialization of DataAccess.page that returns models instead of cursor objects. | [
"Specialization",
"of",
"DataAccess",
".",
"page",
"that",
"returns",
"models",
"instead",
"of",
"cursor",
"objects",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L36-L40 |
249,204 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.find_model_by_id | def find_model_by_id(self, constructor, id_, *, columns=None):
"""Searches for a model by id, according to its class' primary_key_name.
If primary_key_name is a tuple, id_ must be a tuple with a matching length.
"""
return self.find_model(
constructor, get_id_constraints(constructor.primary_key_name, id_), columns=columns) | python | def find_model_by_id(self, constructor, id_, *, columns=None):
"""Searches for a model by id, according to its class' primary_key_name.
If primary_key_name is a tuple, id_ must be a tuple with a matching length.
"""
return self.find_model(
constructor, get_id_constraints(constructor.primary_key_name, id_), columns=columns) | [
"def",
"find_model_by_id",
"(",
"self",
",",
"constructor",
",",
"id_",
",",
"*",
",",
"columns",
"=",
"None",
")",
":",
"return",
"self",
".",
"find_model",
"(",
"constructor",
",",
"get_id_constraints",
"(",
"constructor",
".",
"primary_key_name",
",",
"id_",
")",
",",
"columns",
"=",
"columns",
")"
] | Searches for a model by id, according to its class' primary_key_name.
If primary_key_name is a tuple, id_ must be a tuple with a matching length. | [
"Searches",
"for",
"a",
"model",
"by",
"id",
"according",
"to",
"its",
"class",
"primary_key_name",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L42-L48 |
249,205 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.refresh_model | def refresh_model(self, model, *, overwrite=False):
"""Pulls the model's record from the database. If overwrite is True, the model values are
overwritten and returns the model, otherwise a new model instance with the newer record is
returned.
"""
new_model = self.find_model_by_id(model.__class__, model.primary_key)
if overwrite:
model.update(new_model.to_dict(use_default_excludes=False))
return model
else:
return new_model | python | def refresh_model(self, model, *, overwrite=False):
"""Pulls the model's record from the database. If overwrite is True, the model values are
overwritten and returns the model, otherwise a new model instance with the newer record is
returned.
"""
new_model = self.find_model_by_id(model.__class__, model.primary_key)
if overwrite:
model.update(new_model.to_dict(use_default_excludes=False))
return model
else:
return new_model | [
"def",
"refresh_model",
"(",
"self",
",",
"model",
",",
"*",
",",
"overwrite",
"=",
"False",
")",
":",
"new_model",
"=",
"self",
".",
"find_model_by_id",
"(",
"model",
".",
"__class__",
",",
"model",
".",
"primary_key",
")",
"if",
"overwrite",
":",
"model",
".",
"update",
"(",
"new_model",
".",
"to_dict",
"(",
"use_default_excludes",
"=",
"False",
")",
")",
"return",
"model",
"else",
":",
"return",
"new_model"
] | Pulls the model's record from the database. If overwrite is True, the model values are
overwritten and returns the model, otherwise a new model instance with the newer record is
returned. | [
"Pulls",
"the",
"model",
"s",
"record",
"from",
"the",
"database",
".",
"If",
"overwrite",
"is",
"True",
"the",
"model",
"values",
"are",
"overwritten",
"and",
"returns",
"the",
"model",
"otherwise",
"a",
"new",
"model",
"instance",
"with",
"the",
"newer",
"record",
"is",
"returned",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L50-L60 |
249,206 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.update_model | def update_model(self, model, *, include_keys=None):
"""Updates a model.
:include_keys: if given, only updates the given attributes. Otherwise, updates all non-id
attributes.
"""
id_constraints = get_model_id_constraints(model)
if include_keys is None:
include_keys = set(
model.attrs.keys()).difference(model.exclude_keys_sql).difference(id_constraints.keys())
# If include_keys was not null but was empty
if not include_keys:
return model
values = model.to_dict(include_keys=include_keys)
returnings = []
_, updated_ts = model.timestamps if model.timestamps else (None, None)
if updated_ts and updated_ts not in values:
values[updated_ts] = utc_now() if self.core.supports_timezones else local_now()
returnings.append(updated_ts)
returning = ", ".join(returnings)
cr = self.update(model.table_name, values, id_constraints, returning=returning)
if returning and self.core.supports_returning_syntax:
rec = cr.fetchone()
for idx, attr_name in enumerate(returnings):
setattr(model, attr_name, rec[idx])
return model | python | def update_model(self, model, *, include_keys=None):
"""Updates a model.
:include_keys: if given, only updates the given attributes. Otherwise, updates all non-id
attributes.
"""
id_constraints = get_model_id_constraints(model)
if include_keys is None:
include_keys = set(
model.attrs.keys()).difference(model.exclude_keys_sql).difference(id_constraints.keys())
# If include_keys was not null but was empty
if not include_keys:
return model
values = model.to_dict(include_keys=include_keys)
returnings = []
_, updated_ts = model.timestamps if model.timestamps else (None, None)
if updated_ts and updated_ts not in values:
values[updated_ts] = utc_now() if self.core.supports_timezones else local_now()
returnings.append(updated_ts)
returning = ", ".join(returnings)
cr = self.update(model.table_name, values, id_constraints, returning=returning)
if returning and self.core.supports_returning_syntax:
rec = cr.fetchone()
for idx, attr_name in enumerate(returnings):
setattr(model, attr_name, rec[idx])
return model | [
"def",
"update_model",
"(",
"self",
",",
"model",
",",
"*",
",",
"include_keys",
"=",
"None",
")",
":",
"id_constraints",
"=",
"get_model_id_constraints",
"(",
"model",
")",
"if",
"include_keys",
"is",
"None",
":",
"include_keys",
"=",
"set",
"(",
"model",
".",
"attrs",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"model",
".",
"exclude_keys_sql",
")",
".",
"difference",
"(",
"id_constraints",
".",
"keys",
"(",
")",
")",
"# If include_keys was not null but was empty",
"if",
"not",
"include_keys",
":",
"return",
"model",
"values",
"=",
"model",
".",
"to_dict",
"(",
"include_keys",
"=",
"include_keys",
")",
"returnings",
"=",
"[",
"]",
"_",
",",
"updated_ts",
"=",
"model",
".",
"timestamps",
"if",
"model",
".",
"timestamps",
"else",
"(",
"None",
",",
"None",
")",
"if",
"updated_ts",
"and",
"updated_ts",
"not",
"in",
"values",
":",
"values",
"[",
"updated_ts",
"]",
"=",
"utc_now",
"(",
")",
"if",
"self",
".",
"core",
".",
"supports_timezones",
"else",
"local_now",
"(",
")",
"returnings",
".",
"append",
"(",
"updated_ts",
")",
"returning",
"=",
"\", \"",
".",
"join",
"(",
"returnings",
")",
"cr",
"=",
"self",
".",
"update",
"(",
"model",
".",
"table_name",
",",
"values",
",",
"id_constraints",
",",
"returning",
"=",
"returning",
")",
"if",
"returning",
"and",
"self",
".",
"core",
".",
"supports_returning_syntax",
":",
"rec",
"=",
"cr",
".",
"fetchone",
"(",
")",
"for",
"idx",
",",
"attr_name",
"in",
"enumerate",
"(",
"returnings",
")",
":",
"setattr",
"(",
"model",
",",
"attr_name",
",",
"rec",
"[",
"idx",
"]",
")",
"return",
"model"
] | Updates a model.
:include_keys: if given, only updates the given attributes. Otherwise, updates all non-id
attributes. | [
"Updates",
"a",
"model",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L62-L95 |
249,207 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.insert_model | def insert_model(self, model, *, upsert=None):
"""Inserts a record for the given model.
If model's primary key is auto, the primary key will be set appropriately.
"""
pkname = model.primary_key_name
include_keys = set(model.attrs.keys()).difference(model.exclude_keys_sql)
if model.primary_key_is_auto:
if pkname in include_keys:
include_keys.remove(pkname)
else:
if isinstance(pkname, str):
include_keys.add(pkname)
else:
include_keys.update(set(pkname))
data = model.to_dict(include_keys=include_keys)
returnings = []
if model.primary_key_is_auto:
returnings.append(pkname)
if model.timestamps:
returnings.extend(ts_name for ts_name in model.timestamps if ts_name)
returning = ", ".join(returnings)
cr = self.insert(model.table_name, data, returning=returning, upsert=upsert)
if self.core.supports_returning_syntax:
if returning:
rec = cr.fetchone()
if rec:
for idx, attr_name in enumerate(returnings):
setattr(model, attr_name, rec[idx])
else:
if model.primary_key_is_auto:
setattr(model, model.primary_key_name, cr.lastrowid)
return model | python | def insert_model(self, model, *, upsert=None):
"""Inserts a record for the given model.
If model's primary key is auto, the primary key will be set appropriately.
"""
pkname = model.primary_key_name
include_keys = set(model.attrs.keys()).difference(model.exclude_keys_sql)
if model.primary_key_is_auto:
if pkname in include_keys:
include_keys.remove(pkname)
else:
if isinstance(pkname, str):
include_keys.add(pkname)
else:
include_keys.update(set(pkname))
data = model.to_dict(include_keys=include_keys)
returnings = []
if model.primary_key_is_auto:
returnings.append(pkname)
if model.timestamps:
returnings.extend(ts_name for ts_name in model.timestamps if ts_name)
returning = ", ".join(returnings)
cr = self.insert(model.table_name, data, returning=returning, upsert=upsert)
if self.core.supports_returning_syntax:
if returning:
rec = cr.fetchone()
if rec:
for idx, attr_name in enumerate(returnings):
setattr(model, attr_name, rec[idx])
else:
if model.primary_key_is_auto:
setattr(model, model.primary_key_name, cr.lastrowid)
return model | [
"def",
"insert_model",
"(",
"self",
",",
"model",
",",
"*",
",",
"upsert",
"=",
"None",
")",
":",
"pkname",
"=",
"model",
".",
"primary_key_name",
"include_keys",
"=",
"set",
"(",
"model",
".",
"attrs",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"model",
".",
"exclude_keys_sql",
")",
"if",
"model",
".",
"primary_key_is_auto",
":",
"if",
"pkname",
"in",
"include_keys",
":",
"include_keys",
".",
"remove",
"(",
"pkname",
")",
"else",
":",
"if",
"isinstance",
"(",
"pkname",
",",
"str",
")",
":",
"include_keys",
".",
"add",
"(",
"pkname",
")",
"else",
":",
"include_keys",
".",
"update",
"(",
"set",
"(",
"pkname",
")",
")",
"data",
"=",
"model",
".",
"to_dict",
"(",
"include_keys",
"=",
"include_keys",
")",
"returnings",
"=",
"[",
"]",
"if",
"model",
".",
"primary_key_is_auto",
":",
"returnings",
".",
"append",
"(",
"pkname",
")",
"if",
"model",
".",
"timestamps",
":",
"returnings",
".",
"extend",
"(",
"ts_name",
"for",
"ts_name",
"in",
"model",
".",
"timestamps",
"if",
"ts_name",
")",
"returning",
"=",
"\", \"",
".",
"join",
"(",
"returnings",
")",
"cr",
"=",
"self",
".",
"insert",
"(",
"model",
".",
"table_name",
",",
"data",
",",
"returning",
"=",
"returning",
",",
"upsert",
"=",
"upsert",
")",
"if",
"self",
".",
"core",
".",
"supports_returning_syntax",
":",
"if",
"returning",
":",
"rec",
"=",
"cr",
".",
"fetchone",
"(",
")",
"if",
"rec",
":",
"for",
"idx",
",",
"attr_name",
"in",
"enumerate",
"(",
"returnings",
")",
":",
"setattr",
"(",
"model",
",",
"attr_name",
",",
"rec",
"[",
"idx",
"]",
")",
"else",
":",
"if",
"model",
".",
"primary_key_is_auto",
":",
"setattr",
"(",
"model",
",",
"model",
".",
"primary_key_name",
",",
"cr",
".",
"lastrowid",
")",
"return",
"model"
] | Inserts a record for the given model.
If model's primary key is auto, the primary key will be set appropriately. | [
"Inserts",
"a",
"record",
"for",
"the",
"given",
"model",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L97-L135 |
249,208 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.delete_model | def delete_model(self, model_or_type, id_=None):
"""Deletes a model.
:model_or_type: if a model, delete that model. If it is a ModelBase subclass, id_ must be
specified, and the associated record is deleted.
"""
if not id_:
constraints = get_model_id_constraints(model_or_type)
else:
constraints = get_id_constraints(model_or_type.primary_key_name, id_)
self.delete(model_or_type.table_name, constraints)
return model_or_type | python | def delete_model(self, model_or_type, id_=None):
"""Deletes a model.
:model_or_type: if a model, delete that model. If it is a ModelBase subclass, id_ must be
specified, and the associated record is deleted.
"""
if not id_:
constraints = get_model_id_constraints(model_or_type)
else:
constraints = get_id_constraints(model_or_type.primary_key_name, id_)
self.delete(model_or_type.table_name, constraints)
return model_or_type | [
"def",
"delete_model",
"(",
"self",
",",
"model_or_type",
",",
"id_",
"=",
"None",
")",
":",
"if",
"not",
"id_",
":",
"constraints",
"=",
"get_model_id_constraints",
"(",
"model_or_type",
")",
"else",
":",
"constraints",
"=",
"get_id_constraints",
"(",
"model_or_type",
".",
"primary_key_name",
",",
"id_",
")",
"self",
".",
"delete",
"(",
"model_or_type",
".",
"table_name",
",",
"constraints",
")",
"return",
"model_or_type"
] | Deletes a model.
:model_or_type: if a model, delete that model. If it is a ModelBase subclass, id_ must be
specified, and the associated record is deleted. | [
"Deletes",
"a",
"model",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L137-L149 |
249,209 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.find_or_build | def find_or_build(self, constructor, props):
"""Looks for a model that matches the given dictionary constraints. If it is not found, a new
model of the given type is constructed and returned.
"""
model = self.find_model(constructor, props)
return model or constructor(**props) | python | def find_or_build(self, constructor, props):
"""Looks for a model that matches the given dictionary constraints. If it is not found, a new
model of the given type is constructed and returned.
"""
model = self.find_model(constructor, props)
return model or constructor(**props) | [
"def",
"find_or_build",
"(",
"self",
",",
"constructor",
",",
"props",
")",
":",
"model",
"=",
"self",
".",
"find_model",
"(",
"constructor",
",",
"props",
")",
"return",
"model",
"or",
"constructor",
"(",
"*",
"*",
"props",
")"
] | Looks for a model that matches the given dictionary constraints. If it is not found, a new
model of the given type is constructed and returned. | [
"Looks",
"for",
"a",
"model",
"that",
"matches",
"the",
"given",
"dictionary",
"constraints",
".",
"If",
"it",
"is",
"not",
"found",
"a",
"new",
"model",
"of",
"the",
"given",
"type",
"is",
"constructed",
"and",
"returned",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L151-L156 |
249,210 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.find_or_create | def find_or_create(self, constructor, props, *, comp=None):
"""Looks for a model taht matches the given dictionary constraints. If it is not found, a new
model of the given type is created and saved to the database, then returned.
"""
model = self.find_model(constructor, comp or props)
if model is None:
model = constructor(**props)
self.insert_model(model)
return model | python | def find_or_create(self, constructor, props, *, comp=None):
"""Looks for a model taht matches the given dictionary constraints. If it is not found, a new
model of the given type is created and saved to the database, then returned.
"""
model = self.find_model(constructor, comp or props)
if model is None:
model = constructor(**props)
self.insert_model(model)
return model | [
"def",
"find_or_create",
"(",
"self",
",",
"constructor",
",",
"props",
",",
"*",
",",
"comp",
"=",
"None",
")",
":",
"model",
"=",
"self",
".",
"find_model",
"(",
"constructor",
",",
"comp",
"or",
"props",
")",
"if",
"model",
"is",
"None",
":",
"model",
"=",
"constructor",
"(",
"*",
"*",
"props",
")",
"self",
".",
"insert_model",
"(",
"model",
")",
"return",
"model"
] | Looks for a model taht matches the given dictionary constraints. If it is not found, a new
model of the given type is created and saved to the database, then returned. | [
"Looks",
"for",
"a",
"model",
"taht",
"matches",
"the",
"given",
"dictionary",
"constraints",
".",
"If",
"it",
"is",
"not",
"found",
"a",
"new",
"model",
"of",
"the",
"given",
"type",
"is",
"created",
"and",
"saved",
"to",
"the",
"database",
"then",
"returned",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L158-L166 |
249,211 | treycucco/bidon | bidon/db/access/model_access.py | ModelAccess.find_or_upsert | def find_or_upsert(self, constructor, props, *, comp=None, return_status=False):
"""This finds or upserts a model with an auto primary key, and is a bit more flexible than
find_or_create.
First it looks for the model matching either comp, or props if comp is None.
If not found, it will try to upsert the model, doing nothing. If the returned model is new,
meaning it's primary key is not set, then the upsert was unable to create the model, meaning
there was a conflict. If there is a conflict, find model is run again, and this time it
will succeed*. Otherwise, the constructed model is returned.
*this is not entirely true. It's possible that the upsert returns with None, meaning that a
record was created between the first find and the upsert, and then deleted between the upsert
and the second find. This situation is out of the scope of this method. A possible solution
would be to repeat the find/uspert cycle until a model can be returned, but I'm going to avoid
that for simplicty for now.
:param constructor: the model constructor
:param props: the properties to construct the model with if not found
:param comp: the properties to search for the model with. If None, props is used
:param return_status: if True, a 2-tuple of (model, status) is returned, where status is what
occurred with the model. Either 'found', 'created' or 'duplicate'.
"""
model = self.find_model(constructor, comp or props)
status = _UPSERT_STATUS_FOUND
if model is None:
model = constructor(**props)
status = _UPSERT_STATUS_CREATED
self.insert_model(model, upsert=Upsert(Upsert.DO_NOTHING))
if model.is_new:
model = self.find_model(constructor, comp or props)
status = _UPSERT_STATUS_DUPLICATE
if return_status:
return (model, status)
else:
return model | python | def find_or_upsert(self, constructor, props, *, comp=None, return_status=False):
"""This finds or upserts a model with an auto primary key, and is a bit more flexible than
find_or_create.
First it looks for the model matching either comp, or props if comp is None.
If not found, it will try to upsert the model, doing nothing. If the returned model is new,
meaning it's primary key is not set, then the upsert was unable to create the model, meaning
there was a conflict. If there is a conflict, find model is run again, and this time it
will succeed*. Otherwise, the constructed model is returned.
*this is not entirely true. It's possible that the upsert returns with None, meaning that a
record was created between the first find and the upsert, and then deleted between the upsert
and the second find. This situation is out of the scope of this method. A possible solution
would be to repeat the find/uspert cycle until a model can be returned, but I'm going to avoid
that for simplicty for now.
:param constructor: the model constructor
:param props: the properties to construct the model with if not found
:param comp: the properties to search for the model with. If None, props is used
:param return_status: if True, a 2-tuple of (model, status) is returned, where status is what
occurred with the model. Either 'found', 'created' or 'duplicate'.
"""
model = self.find_model(constructor, comp or props)
status = _UPSERT_STATUS_FOUND
if model is None:
model = constructor(**props)
status = _UPSERT_STATUS_CREATED
self.insert_model(model, upsert=Upsert(Upsert.DO_NOTHING))
if model.is_new:
model = self.find_model(constructor, comp or props)
status = _UPSERT_STATUS_DUPLICATE
if return_status:
return (model, status)
else:
return model | [
"def",
"find_or_upsert",
"(",
"self",
",",
"constructor",
",",
"props",
",",
"*",
",",
"comp",
"=",
"None",
",",
"return_status",
"=",
"False",
")",
":",
"model",
"=",
"self",
".",
"find_model",
"(",
"constructor",
",",
"comp",
"or",
"props",
")",
"status",
"=",
"_UPSERT_STATUS_FOUND",
"if",
"model",
"is",
"None",
":",
"model",
"=",
"constructor",
"(",
"*",
"*",
"props",
")",
"status",
"=",
"_UPSERT_STATUS_CREATED",
"self",
".",
"insert_model",
"(",
"model",
",",
"upsert",
"=",
"Upsert",
"(",
"Upsert",
".",
"DO_NOTHING",
")",
")",
"if",
"model",
".",
"is_new",
":",
"model",
"=",
"self",
".",
"find_model",
"(",
"constructor",
",",
"comp",
"or",
"props",
")",
"status",
"=",
"_UPSERT_STATUS_DUPLICATE",
"if",
"return_status",
":",
"return",
"(",
"model",
",",
"status",
")",
"else",
":",
"return",
"model"
] | This finds or upserts a model with an auto primary key, and is a bit more flexible than
find_or_create.
First it looks for the model matching either comp, or props if comp is None.
If not found, it will try to upsert the model, doing nothing. If the returned model is new,
meaning it's primary key is not set, then the upsert was unable to create the model, meaning
there was a conflict. If there is a conflict, find model is run again, and this time it
will succeed*. Otherwise, the constructed model is returned.
*this is not entirely true. It's possible that the upsert returns with None, meaning that a
record was created between the first find and the upsert, and then deleted between the upsert
and the second find. This situation is out of the scope of this method. A possible solution
would be to repeat the find/uspert cycle until a model can be returned, but I'm going to avoid
that for simplicty for now.
:param constructor: the model constructor
:param props: the properties to construct the model with if not found
:param comp: the properties to search for the model with. If None, props is used
:param return_status: if True, a 2-tuple of (model, status) is returned, where status is what
occurred with the model. Either 'found', 'created' or 'duplicate'. | [
"This",
"finds",
"or",
"upserts",
"a",
"model",
"with",
"an",
"auto",
"primary",
"key",
"and",
"is",
"a",
"bit",
"more",
"flexible",
"than",
"find_or_create",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/model_access.py#L168-L205 |
249,212 | naphatkrit/easyci | easyci/vcs/base.py | Vcs.temp_copy | def temp_copy(self):
"""Yields a new Vcs object that represents a temporary, disposable
copy of the current repository. The copy is deleted at the end
of the context.
The following are not copied:
- ignored files
- easyci private directory (.git/eci for git)
Yields:
Vcs
"""
with contextmanagers.temp_dir() as temp_dir:
temp_root_path = os.path.join(temp_dir, 'root')
path = os.path.join(self.path, '') # adds trailing slash
check_call(['rsync', '-r', "--exclude={}".format(self.private_dir()), "--filter=dir-merge,- {}".format(
self.ignore_patterns_file()), path, temp_root_path])
copy = self.__class__(path=temp_root_path)
yield copy | python | def temp_copy(self):
"""Yields a new Vcs object that represents a temporary, disposable
copy of the current repository. The copy is deleted at the end
of the context.
The following are not copied:
- ignored files
- easyci private directory (.git/eci for git)
Yields:
Vcs
"""
with contextmanagers.temp_dir() as temp_dir:
temp_root_path = os.path.join(temp_dir, 'root')
path = os.path.join(self.path, '') # adds trailing slash
check_call(['rsync', '-r', "--exclude={}".format(self.private_dir()), "--filter=dir-merge,- {}".format(
self.ignore_patterns_file()), path, temp_root_path])
copy = self.__class__(path=temp_root_path)
yield copy | [
"def",
"temp_copy",
"(",
"self",
")",
":",
"with",
"contextmanagers",
".",
"temp_dir",
"(",
")",
"as",
"temp_dir",
":",
"temp_root_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"'root'",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"''",
")",
"# adds trailing slash",
"check_call",
"(",
"[",
"'rsync'",
",",
"'-r'",
",",
"\"--exclude={}\"",
".",
"format",
"(",
"self",
".",
"private_dir",
"(",
")",
")",
",",
"\"--filter=dir-merge,- {}\"",
".",
"format",
"(",
"self",
".",
"ignore_patterns_file",
"(",
")",
")",
",",
"path",
",",
"temp_root_path",
"]",
")",
"copy",
"=",
"self",
".",
"__class__",
"(",
"path",
"=",
"temp_root_path",
")",
"yield",
"copy"
] | Yields a new Vcs object that represents a temporary, disposable
copy of the current repository. The copy is deleted at the end
of the context.
The following are not copied:
- ignored files
- easyci private directory (.git/eci for git)
Yields:
Vcs | [
"Yields",
"a",
"new",
"Vcs",
"object",
"that",
"represents",
"a",
"temporary",
"disposable",
"copy",
"of",
"the",
"current",
"repository",
".",
"The",
"copy",
"is",
"deleted",
"at",
"the",
"end",
"of",
"the",
"context",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/vcs/base.py#L185-L203 |
249,213 | minhhoit/yacms | yacms/pages/managers.py | PageManager.published | def published(self, for_user=None, include_login_required=False):
"""
Override ``DisplayableManager.published`` to exclude
pages with ``login_required`` set to ``True``. if the
user is unauthenticated and the setting
``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``.
The extra ``include_login_required`` arg allows callers to
override the ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED``
behaviour in special cases where they want to deal with the
``login_required`` field manually, such as the case in
``PageMiddleware``.
"""
published = super(PageManager, self).published(for_user=for_user)
unauthenticated = for_user and not for_user.is_authenticated()
if (unauthenticated and not include_login_required and
not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED):
published = published.exclude(login_required=True)
return published | python | def published(self, for_user=None, include_login_required=False):
"""
Override ``DisplayableManager.published`` to exclude
pages with ``login_required`` set to ``True``. if the
user is unauthenticated and the setting
``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``.
The extra ``include_login_required`` arg allows callers to
override the ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED``
behaviour in special cases where they want to deal with the
``login_required`` field manually, such as the case in
``PageMiddleware``.
"""
published = super(PageManager, self).published(for_user=for_user)
unauthenticated = for_user and not for_user.is_authenticated()
if (unauthenticated and not include_login_required and
not settings.PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED):
published = published.exclude(login_required=True)
return published | [
"def",
"published",
"(",
"self",
",",
"for_user",
"=",
"None",
",",
"include_login_required",
"=",
"False",
")",
":",
"published",
"=",
"super",
"(",
"PageManager",
",",
"self",
")",
".",
"published",
"(",
"for_user",
"=",
"for_user",
")",
"unauthenticated",
"=",
"for_user",
"and",
"not",
"for_user",
".",
"is_authenticated",
"(",
")",
"if",
"(",
"unauthenticated",
"and",
"not",
"include_login_required",
"and",
"not",
"settings",
".",
"PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED",
")",
":",
"published",
"=",
"published",
".",
"exclude",
"(",
"login_required",
"=",
"True",
")",
"return",
"published"
] | Override ``DisplayableManager.published`` to exclude
pages with ``login_required`` set to ``True``. if the
user is unauthenticated and the setting
``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED`` is ``False``.
The extra ``include_login_required`` arg allows callers to
override the ``PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED``
behaviour in special cases where they want to deal with the
``login_required`` field manually, such as the case in
``PageMiddleware``. | [
"Override",
"DisplayableManager",
".",
"published",
"to",
"exclude",
"pages",
"with",
"login_required",
"set",
"to",
"True",
".",
"if",
"the",
"user",
"is",
"unauthenticated",
"and",
"the",
"setting",
"PAGES_PUBLISHED_INCLUDE_LOGIN_REQUIRED",
"is",
"False",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/managers.py#L11-L29 |
249,214 | stevemarple/python-atomiccreate | atomiccreate/__init__.py | atomic_symlink | def atomic_symlink(src, dst):
"""Create or update a symbolic link atomically.
This function is similar to :py:func:`os.symlink` but will update a symlink atomically."""
dst_dir = os.path.dirname(dst)
tmp = None
max_tries = getattr(os, 'TMP_MAX', 10000)
try:
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for n in range(max_tries):
try:
# mktemp is described as being unsafe. That is not true in this case since symlink is an
# atomic operation at the file system level; if some other processes creates a file with
# 'our' name then symlink will fail.
tmp = tempfile.mktemp(dir=dst_dir)
os.symlink(src, tmp)
logger.debug('created symlink %s', tmp)
except OSError as e:
if e.errno == errno.EEXIST:
continue # Someone else grabbed the temporary name first
else:
raise
logger.debug('renaming %s to %s', tmp, dst)
os.rename(tmp, dst)
return
except:
if tmp and os.path.exists(tmp):
os.remove(tmp)
raise
raise IOError(errno.EEXIST, 'No usable temporary file name found') | python | def atomic_symlink(src, dst):
"""Create or update a symbolic link atomically.
This function is similar to :py:func:`os.symlink` but will update a symlink atomically."""
dst_dir = os.path.dirname(dst)
tmp = None
max_tries = getattr(os, 'TMP_MAX', 10000)
try:
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for n in range(max_tries):
try:
# mktemp is described as being unsafe. That is not true in this case since symlink is an
# atomic operation at the file system level; if some other processes creates a file with
# 'our' name then symlink will fail.
tmp = tempfile.mktemp(dir=dst_dir)
os.symlink(src, tmp)
logger.debug('created symlink %s', tmp)
except OSError as e:
if e.errno == errno.EEXIST:
continue # Someone else grabbed the temporary name first
else:
raise
logger.debug('renaming %s to %s', tmp, dst)
os.rename(tmp, dst)
return
except:
if tmp and os.path.exists(tmp):
os.remove(tmp)
raise
raise IOError(errno.EEXIST, 'No usable temporary file name found') | [
"def",
"atomic_symlink",
"(",
"src",
",",
"dst",
")",
":",
"dst_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dst",
")",
"tmp",
"=",
"None",
"max_tries",
"=",
"getattr",
"(",
"os",
",",
"'TMP_MAX'",
",",
"10000",
")",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"dst_dir",
")",
"for",
"n",
"in",
"range",
"(",
"max_tries",
")",
":",
"try",
":",
"# mktemp is described as being unsafe. That is not true in this case since symlink is an",
"# atomic operation at the file system level; if some other processes creates a file with",
"# 'our' name then symlink will fail.",
"tmp",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"dst_dir",
")",
"os",
".",
"symlink",
"(",
"src",
",",
"tmp",
")",
"logger",
".",
"debug",
"(",
"'created symlink %s'",
",",
"tmp",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"continue",
"# Someone else grabbed the temporary name first",
"else",
":",
"raise",
"logger",
".",
"debug",
"(",
"'renaming %s to %s'",
",",
"tmp",
",",
"dst",
")",
"os",
".",
"rename",
"(",
"tmp",
",",
"dst",
")",
"return",
"except",
":",
"if",
"tmp",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"tmp",
")",
":",
"os",
".",
"remove",
"(",
"tmp",
")",
"raise",
"raise",
"IOError",
"(",
"errno",
".",
"EEXIST",
",",
"'No usable temporary file name found'",
")"
] | Create or update a symbolic link atomically.
This function is similar to :py:func:`os.symlink` but will update a symlink atomically. | [
"Create",
"or",
"update",
"a",
"symbolic",
"link",
"atomically",
"."
] | 33bbbe8ce706dbd5f89ef3e4e29609d51e5fb39a | https://github.com/stevemarple/python-atomiccreate/blob/33bbbe8ce706dbd5f89ef3e4e29609d51e5fb39a/atomiccreate/__init__.py#L114-L146 |
249,215 | msuozzo/Aduro | main.py | run | def run(): #pylint: disable=too-many-locals
"""Execute the command loop
"""
store = EventStore(STORE_PATH)
with open(CREDENTIAL_PATH, 'r') as cred_file:
creds = json.load(cred_file)
uname, pword = creds['uname'], creds['pword']
mgr = KindleProgressMgr(store, uname, pword)
print 'Detecting updates to Kindle progress:'
events = mgr.detect_events()
if events is None:
print 'Failed to retrieve Kindle progress updates'
return
elif not events:
print ' No updates detected'
else:
for event in events:
print ' ' + str(event)
print
print 'Finished updating.'
print 'Mark new books as \'reading\' or old books as \'read\'? (y/N)'
if safe_raw_input('> ') == 'y':
_change_state_prompt(mgr)
mgr.commit_events() | python | def run(): #pylint: disable=too-many-locals
"""Execute the command loop
"""
store = EventStore(STORE_PATH)
with open(CREDENTIAL_PATH, 'r') as cred_file:
creds = json.load(cred_file)
uname, pword = creds['uname'], creds['pword']
mgr = KindleProgressMgr(store, uname, pword)
print 'Detecting updates to Kindle progress:'
events = mgr.detect_events()
if events is None:
print 'Failed to retrieve Kindle progress updates'
return
elif not events:
print ' No updates detected'
else:
for event in events:
print ' ' + str(event)
print
print 'Finished updating.'
print 'Mark new books as \'reading\' or old books as \'read\'? (y/N)'
if safe_raw_input('> ') == 'y':
_change_state_prompt(mgr)
mgr.commit_events() | [
"def",
"run",
"(",
")",
":",
"#pylint: disable=too-many-locals",
"store",
"=",
"EventStore",
"(",
"STORE_PATH",
")",
"with",
"open",
"(",
"CREDENTIAL_PATH",
",",
"'r'",
")",
"as",
"cred_file",
":",
"creds",
"=",
"json",
".",
"load",
"(",
"cred_file",
")",
"uname",
",",
"pword",
"=",
"creds",
"[",
"'uname'",
"]",
",",
"creds",
"[",
"'pword'",
"]",
"mgr",
"=",
"KindleProgressMgr",
"(",
"store",
",",
"uname",
",",
"pword",
")",
"print",
"'Detecting updates to Kindle progress:'",
"events",
"=",
"mgr",
".",
"detect_events",
"(",
")",
"if",
"events",
"is",
"None",
":",
"print",
"'Failed to retrieve Kindle progress updates'",
"return",
"elif",
"not",
"events",
":",
"print",
"' No updates detected'",
"else",
":",
"for",
"event",
"in",
"events",
":",
"print",
"' '",
"+",
"str",
"(",
"event",
")",
"print",
"print",
"'Finished updating.'",
"print",
"'Mark new books as \\'reading\\' or old books as \\'read\\'? (y/N)'",
"if",
"safe_raw_input",
"(",
"'> '",
")",
"==",
"'y'",
":",
"_change_state_prompt",
"(",
"mgr",
")",
"mgr",
".",
"commit_events",
"(",
")"
] | Execute the command loop | [
"Execute",
"the",
"command",
"loop"
] | 338eeb1deeff30c198e721b660ae4daca3660911 | https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/main.py#L28-L53 |
249,216 | msuozzo/Aduro | main.py | _change_state_prompt | def _change_state_prompt(mgr):
"""Runs a prompt to change the state of books.
Registers `Event`s with `mgr` as they are requested.
Args:
mgr: A `KindleProgressMgr` object with the `books` and `progress`
fields populated.
"""
cmd = ''
book_range = range(1, len(mgr.books) + 1)
ind_to_book = dict(zip(book_range, mgr.books))
get_book = lambda cmd_str: ind_to_book[int(cmd_str.split()[1])]
while cmd != 'q':
print 'Books:'
for i in book_range:
print '\t%d: %s' % (i, ind_to_book[i])
print 'Commands:'
print '| start {#} | Start reading book with index {#}'
print '| finish {#} | Finish reading book with index {#}'
print '| q | Quit'
cmd = safe_raw_input('> ')
if cmd is None or cmd == 'q':
break
elif cmd.startswith('start '):
book = get_book(cmd)
initial_progress = mgr.progress[book.asin].locs[1]
event = SetReadingEvent(book.asin, initial_progress)
elif cmd.startswith('finish '):
event = SetFinishedEvent(get_book(cmd).asin)
else:
print 'Invalid command'
event = None
if event is not None:
print
print 'REGISTERED EVENT:'
print ' ' + str(event)
mgr.register_events((event))
print | python | def _change_state_prompt(mgr):
"""Runs a prompt to change the state of books.
Registers `Event`s with `mgr` as they are requested.
Args:
mgr: A `KindleProgressMgr` object with the `books` and `progress`
fields populated.
"""
cmd = ''
book_range = range(1, len(mgr.books) + 1)
ind_to_book = dict(zip(book_range, mgr.books))
get_book = lambda cmd_str: ind_to_book[int(cmd_str.split()[1])]
while cmd != 'q':
print 'Books:'
for i in book_range:
print '\t%d: %s' % (i, ind_to_book[i])
print 'Commands:'
print '| start {#} | Start reading book with index {#}'
print '| finish {#} | Finish reading book with index {#}'
print '| q | Quit'
cmd = safe_raw_input('> ')
if cmd is None or cmd == 'q':
break
elif cmd.startswith('start '):
book = get_book(cmd)
initial_progress = mgr.progress[book.asin].locs[1]
event = SetReadingEvent(book.asin, initial_progress)
elif cmd.startswith('finish '):
event = SetFinishedEvent(get_book(cmd).asin)
else:
print 'Invalid command'
event = None
if event is not None:
print
print 'REGISTERED EVENT:'
print ' ' + str(event)
mgr.register_events((event))
print | [
"def",
"_change_state_prompt",
"(",
"mgr",
")",
":",
"cmd",
"=",
"''",
"book_range",
"=",
"range",
"(",
"1",
",",
"len",
"(",
"mgr",
".",
"books",
")",
"+",
"1",
")",
"ind_to_book",
"=",
"dict",
"(",
"zip",
"(",
"book_range",
",",
"mgr",
".",
"books",
")",
")",
"get_book",
"=",
"lambda",
"cmd_str",
":",
"ind_to_book",
"[",
"int",
"(",
"cmd_str",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"]",
"while",
"cmd",
"!=",
"'q'",
":",
"print",
"'Books:'",
"for",
"i",
"in",
"book_range",
":",
"print",
"'\\t%d: %s'",
"%",
"(",
"i",
",",
"ind_to_book",
"[",
"i",
"]",
")",
"print",
"'Commands:'",
"print",
"'| start {#} | Start reading book with index {#}'",
"print",
"'| finish {#} | Finish reading book with index {#}'",
"print",
"'| q | Quit'",
"cmd",
"=",
"safe_raw_input",
"(",
"'> '",
")",
"if",
"cmd",
"is",
"None",
"or",
"cmd",
"==",
"'q'",
":",
"break",
"elif",
"cmd",
".",
"startswith",
"(",
"'start '",
")",
":",
"book",
"=",
"get_book",
"(",
"cmd",
")",
"initial_progress",
"=",
"mgr",
".",
"progress",
"[",
"book",
".",
"asin",
"]",
".",
"locs",
"[",
"1",
"]",
"event",
"=",
"SetReadingEvent",
"(",
"book",
".",
"asin",
",",
"initial_progress",
")",
"elif",
"cmd",
".",
"startswith",
"(",
"'finish '",
")",
":",
"event",
"=",
"SetFinishedEvent",
"(",
"get_book",
"(",
"cmd",
")",
".",
"asin",
")",
"else",
":",
"print",
"'Invalid command'",
"event",
"=",
"None",
"if",
"event",
"is",
"not",
"None",
":",
"print",
"print",
"'REGISTERED EVENT:'",
"print",
"' '",
"+",
"str",
"(",
"event",
")",
"mgr",
".",
"register_events",
"(",
"(",
"event",
")",
")",
"print"
] | Runs a prompt to change the state of books.
Registers `Event`s with `mgr` as they are requested.
Args:
mgr: A `KindleProgressMgr` object with the `books` and `progress`
fields populated. | [
"Runs",
"a",
"prompt",
"to",
"change",
"the",
"state",
"of",
"books",
"."
] | 338eeb1deeff30c198e721b660ae4daca3660911 | https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/main.py#L56-L94 |
249,217 | emlazzarin/acrylic | acrylic/ExcelRW.py | UnicodeReader.change_sheet | def change_sheet(self, sheet_name_or_num):
"""
Calling this method changes the sheet in anticipation for the
next time you create an iterator.
If you change the active sheet while iterating on a UnicodeReader
instance, it will continue to iterate correctly until completion.
The next time you iterate through reader, it will begin all over
again at whichever sheet you most recently changed to.
"""
if isinstance(sheet_name_or_num, int):
self._sheet = self.__wb[self.__wb.sheetnames[sheet_name_or_num]]
elif isinstance(sheet_name_or_num, basestring):
self._sheet = self.__wb[sheet_name_or_num]
else:
reason = "Must enter either sheet name or sheet number."
raise Exception(reason) | python | def change_sheet(self, sheet_name_or_num):
"""
Calling this method changes the sheet in anticipation for the
next time you create an iterator.
If you change the active sheet while iterating on a UnicodeReader
instance, it will continue to iterate correctly until completion.
The next time you iterate through reader, it will begin all over
again at whichever sheet you most recently changed to.
"""
if isinstance(sheet_name_or_num, int):
self._sheet = self.__wb[self.__wb.sheetnames[sheet_name_or_num]]
elif isinstance(sheet_name_or_num, basestring):
self._sheet = self.__wb[sheet_name_or_num]
else:
reason = "Must enter either sheet name or sheet number."
raise Exception(reason) | [
"def",
"change_sheet",
"(",
"self",
",",
"sheet_name_or_num",
")",
":",
"if",
"isinstance",
"(",
"sheet_name_or_num",
",",
"int",
")",
":",
"self",
".",
"_sheet",
"=",
"self",
".",
"__wb",
"[",
"self",
".",
"__wb",
".",
"sheetnames",
"[",
"sheet_name_or_num",
"]",
"]",
"elif",
"isinstance",
"(",
"sheet_name_or_num",
",",
"basestring",
")",
":",
"self",
".",
"_sheet",
"=",
"self",
".",
"__wb",
"[",
"sheet_name_or_num",
"]",
"else",
":",
"reason",
"=",
"\"Must enter either sheet name or sheet number.\"",
"raise",
"Exception",
"(",
"reason",
")"
] | Calling this method changes the sheet in anticipation for the
next time you create an iterator.
If you change the active sheet while iterating on a UnicodeReader
instance, it will continue to iterate correctly until completion.
The next time you iterate through reader, it will begin all over
again at whichever sheet you most recently changed to. | [
"Calling",
"this",
"method",
"changes",
"the",
"sheet",
"in",
"anticipation",
"for",
"the",
"next",
"time",
"you",
"create",
"an",
"iterator",
"."
] | 08c6702d73b9660ead1024653f4fa016f6340e46 | https://github.com/emlazzarin/acrylic/blob/08c6702d73b9660ead1024653f4fa016f6340e46/acrylic/ExcelRW.py#L27-L43 |
249,218 | contains-io/containment | containment/builder.py | CommandLineInterface._os_install | def _os_install(self, package_file):
"""
take in a dict return a string of docker build RUN directives
one RUN per package type
one package type per JSON key
"""
packages = " ".join(json.load(package_file.open()))
if packages:
for packager in self.pkg_install_cmds:
if packager in self.context.externalbasis:
installer = self.pkg_install_cmds[packager]
return f"RUN {installer} {packages}"
else:
return "" | python | def _os_install(self, package_file):
"""
take in a dict return a string of docker build RUN directives
one RUN per package type
one package type per JSON key
"""
packages = " ".join(json.load(package_file.open()))
if packages:
for packager in self.pkg_install_cmds:
if packager in self.context.externalbasis:
installer = self.pkg_install_cmds[packager]
return f"RUN {installer} {packages}"
else:
return "" | [
"def",
"_os_install",
"(",
"self",
",",
"package_file",
")",
":",
"packages",
"=",
"\" \"",
".",
"join",
"(",
"json",
".",
"load",
"(",
"package_file",
".",
"open",
"(",
")",
")",
")",
"if",
"packages",
":",
"for",
"packager",
"in",
"self",
".",
"pkg_install_cmds",
":",
"if",
"packager",
"in",
"self",
".",
"context",
".",
"externalbasis",
":",
"installer",
"=",
"self",
".",
"pkg_install_cmds",
"[",
"packager",
"]",
"return",
"f\"RUN {installer} {packages}\"",
"else",
":",
"return",
"\"\""
] | take in a dict return a string of docker build RUN directives
one RUN per package type
one package type per JSON key | [
"take",
"in",
"a",
"dict",
"return",
"a",
"string",
"of",
"docker",
"build",
"RUN",
"directives",
"one",
"RUN",
"per",
"package",
"type",
"one",
"package",
"type",
"per",
"JSON",
"key"
] | 4f7e2c2338e0ca7c107a7b3a9913bb5e6e07245f | https://github.com/contains-io/containment/blob/4f7e2c2338e0ca7c107a7b3a9913bb5e6e07245f/containment/builder.py#L65-L78 |
249,219 | anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient.connect | async def connect(self):
"""
Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return anything.
"""
if self.connected or self.is_connecting:
return
self._is_connecting = True
try:
logger.info("Connecting to RabbitMQ...")
self._transport, self._protocol = await aioamqp.connect(**self._connection_parameters)
logger.info("Getting channel...")
self._channel = await self._protocol.channel()
if self._global_qos is not None:
logger.info("Setting prefetch count on connection (%s)", self._global_qos)
await self._channel.basic_qos(0, self._global_qos, 1)
logger.info("Connecting to exchange '%s (%s)'", self._exchange_name, self._exchange_type)
await self._channel.exchange(self._exchange_name, self._exchange_type)
except (aioamqp.AmqpClosedConnection, Exception):
logger.error("Error initializing RabbitMQ connection", exc_info=True)
self._is_connecting = False
raise exceptions.StreamConnectionError
self._is_connecting = False | python | async def connect(self):
"""
Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return anything.
"""
if self.connected or self.is_connecting:
return
self._is_connecting = True
try:
logger.info("Connecting to RabbitMQ...")
self._transport, self._protocol = await aioamqp.connect(**self._connection_parameters)
logger.info("Getting channel...")
self._channel = await self._protocol.channel()
if self._global_qos is not None:
logger.info("Setting prefetch count on connection (%s)", self._global_qos)
await self._channel.basic_qos(0, self._global_qos, 1)
logger.info("Connecting to exchange '%s (%s)'", self._exchange_name, self._exchange_type)
await self._channel.exchange(self._exchange_name, self._exchange_type)
except (aioamqp.AmqpClosedConnection, Exception):
logger.error("Error initializing RabbitMQ connection", exc_info=True)
self._is_connecting = False
raise exceptions.StreamConnectionError
self._is_connecting = False | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"connected",
"or",
"self",
".",
"is_connecting",
":",
"return",
"self",
".",
"_is_connecting",
"=",
"True",
"try",
":",
"logger",
".",
"info",
"(",
"\"Connecting to RabbitMQ...\"",
")",
"self",
".",
"_transport",
",",
"self",
".",
"_protocol",
"=",
"await",
"aioamqp",
".",
"connect",
"(",
"*",
"*",
"self",
".",
"_connection_parameters",
")",
"logger",
".",
"info",
"(",
"\"Getting channel...\"",
")",
"self",
".",
"_channel",
"=",
"await",
"self",
".",
"_protocol",
".",
"channel",
"(",
")",
"if",
"self",
".",
"_global_qos",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"\"Setting prefetch count on connection (%s)\"",
",",
"self",
".",
"_global_qos",
")",
"await",
"self",
".",
"_channel",
".",
"basic_qos",
"(",
"0",
",",
"self",
".",
"_global_qos",
",",
"1",
")",
"logger",
".",
"info",
"(",
"\"Connecting to exchange '%s (%s)'\"",
",",
"self",
".",
"_exchange_name",
",",
"self",
".",
"_exchange_type",
")",
"await",
"self",
".",
"_channel",
".",
"exchange",
"(",
"self",
".",
"_exchange_name",
",",
"self",
".",
"_exchange_type",
")",
"except",
"(",
"aioamqp",
".",
"AmqpClosedConnection",
",",
"Exception",
")",
":",
"logger",
".",
"error",
"(",
"\"Error initializing RabbitMQ connection\"",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"_is_connecting",
"=",
"False",
"raise",
"exceptions",
".",
"StreamConnectionError",
"self",
".",
"_is_connecting",
"=",
"False"
] | Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return anything. | [
"Create",
"new",
"asynchronous",
"connection",
"to",
"the",
"RabbitMQ",
"instance",
".",
"This",
"will",
"connect",
"declare",
"exchange",
"and",
"bind",
"itself",
"to",
"the",
"configured",
"queue",
"."
] | 5117ec797a38eb82d955241d20547d125efe80f3 | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L87-L119 |
249,220 | anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient.consume_queue | async def consume_queue(self, subscriber: AbstractSubscriber) -> None:
"""
Subscribe to the queue consuming.
:param subscriber:
:return:
"""
queue_name = subscriber.name
topics = subscriber.requested_topics
if queue_name in self._known_queues:
raise exceptions.ConsumerError("Queue '%s' already being consumed" % queue_name)
await self._declare_queue(queue_name)
# TODO: There is a lot of room to improvement here. Figure out routing done the right way
for key in topics:
self._routing.setdefault(key, set())
if subscriber in self._routing[key]:
logger.warning("Subscriber '%s' already receiving routing_key '%s'", subscriber, key)
break
await self._bind_key_to_queue(key, queue_name)
self._routing[key].add(subscriber)
logger.info("Consuming queue '%s'", queue_name)
await asyncio.wait_for(
self._channel.basic_consume(callback=self._on_message, queue_name=queue_name),
timeout=10
)
self._add_to_known_queue(queue_name) | python | async def consume_queue(self, subscriber: AbstractSubscriber) -> None:
"""
Subscribe to the queue consuming.
:param subscriber:
:return:
"""
queue_name = subscriber.name
topics = subscriber.requested_topics
if queue_name in self._known_queues:
raise exceptions.ConsumerError("Queue '%s' already being consumed" % queue_name)
await self._declare_queue(queue_name)
# TODO: There is a lot of room to improvement here. Figure out routing done the right way
for key in topics:
self._routing.setdefault(key, set())
if subscriber in self._routing[key]:
logger.warning("Subscriber '%s' already receiving routing_key '%s'", subscriber, key)
break
await self._bind_key_to_queue(key, queue_name)
self._routing[key].add(subscriber)
logger.info("Consuming queue '%s'", queue_name)
await asyncio.wait_for(
self._channel.basic_consume(callback=self._on_message, queue_name=queue_name),
timeout=10
)
self._add_to_known_queue(queue_name) | [
"async",
"def",
"consume_queue",
"(",
"self",
",",
"subscriber",
":",
"AbstractSubscriber",
")",
"->",
"None",
":",
"queue_name",
"=",
"subscriber",
".",
"name",
"topics",
"=",
"subscriber",
".",
"requested_topics",
"if",
"queue_name",
"in",
"self",
".",
"_known_queues",
":",
"raise",
"exceptions",
".",
"ConsumerError",
"(",
"\"Queue '%s' already being consumed\"",
"%",
"queue_name",
")",
"await",
"self",
".",
"_declare_queue",
"(",
"queue_name",
")",
"# TODO: There is a lot of room to improvement here. Figure out routing done the right way",
"for",
"key",
"in",
"topics",
":",
"self",
".",
"_routing",
".",
"setdefault",
"(",
"key",
",",
"set",
"(",
")",
")",
"if",
"subscriber",
"in",
"self",
".",
"_routing",
"[",
"key",
"]",
":",
"logger",
".",
"warning",
"(",
"\"Subscriber '%s' already receiving routing_key '%s'\"",
",",
"subscriber",
",",
"key",
")",
"break",
"await",
"self",
".",
"_bind_key_to_queue",
"(",
"key",
",",
"queue_name",
")",
"self",
".",
"_routing",
"[",
"key",
"]",
".",
"add",
"(",
"subscriber",
")",
"logger",
".",
"info",
"(",
"\"Consuming queue '%s'\"",
",",
"queue_name",
")",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_channel",
".",
"basic_consume",
"(",
"callback",
"=",
"self",
".",
"_on_message",
",",
"queue_name",
"=",
"queue_name",
")",
",",
"timeout",
"=",
"10",
")",
"self",
".",
"_add_to_known_queue",
"(",
"queue_name",
")"
] | Subscribe to the queue consuming.
:param subscriber:
:return: | [
"Subscribe",
"to",
"the",
"queue",
"consuming",
"."
] | 5117ec797a38eb82d955241d20547d125efe80f3 | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L140-L171 |
249,221 | anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient._bind_key_to_queue | async def _bind_key_to_queue(self, routing_key: AnyStr, queue_name: AnyStr) -> None:
"""
Bind to queue with specified routing key.
:param routing_key: Routing key to bind with.
:param queue_name: Name of the queue
:return: Does not return anything
"""
logger.info("Binding key='%s'", routing_key)
result = await self._channel.queue_bind(
exchange_name=self._exchange_name,
queue_name=queue_name,
routing_key=routing_key,
)
return result | python | async def _bind_key_to_queue(self, routing_key: AnyStr, queue_name: AnyStr) -> None:
"""
Bind to queue with specified routing key.
:param routing_key: Routing key to bind with.
:param queue_name: Name of the queue
:return: Does not return anything
"""
logger.info("Binding key='%s'", routing_key)
result = await self._channel.queue_bind(
exchange_name=self._exchange_name,
queue_name=queue_name,
routing_key=routing_key,
)
return result | [
"async",
"def",
"_bind_key_to_queue",
"(",
"self",
",",
"routing_key",
":",
"AnyStr",
",",
"queue_name",
":",
"AnyStr",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"Binding key='%s'\"",
",",
"routing_key",
")",
"result",
"=",
"await",
"self",
".",
"_channel",
".",
"queue_bind",
"(",
"exchange_name",
"=",
"self",
".",
"_exchange_name",
",",
"queue_name",
"=",
"queue_name",
",",
"routing_key",
"=",
"routing_key",
",",
")",
"return",
"result"
] | Bind to queue with specified routing key.
:param routing_key: Routing key to bind with.
:param queue_name: Name of the queue
:return: Does not return anything | [
"Bind",
"to",
"queue",
"with",
"specified",
"routing",
"key",
"."
] | 5117ec797a38eb82d955241d20547d125efe80f3 | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L179-L194 |
249,222 | anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient._on_message | async def _on_message(self, channel, body, envelope, properties) -> None:
"""
Fires up when message is received by this consumer.
:param channel: Channel, through which message is received
:param body: Body of the message (serialized).
:param envelope: Envelope object with message meta
:type envelope: aioamqp.Envelope
:param properties: Properties of the message
:return: Coroutine object with result of message handling operation
"""
subscribers = self._get_subscribers(envelope.routing_key)
if not subscribers:
logger.debug("No route for message with key '%s'", envelope.routing_key)
return
body = self._serializer.deserialize(body)
for subscriber in subscribers:
# Check later if ensure_future can be applied here
await subscriber.on_message(body, envelope.routing_key)
await self._channel.basic_client_ack(envelope.delivery_tag) | python | async def _on_message(self, channel, body, envelope, properties) -> None:
"""
Fires up when message is received by this consumer.
:param channel: Channel, through which message is received
:param body: Body of the message (serialized).
:param envelope: Envelope object with message meta
:type envelope: aioamqp.Envelope
:param properties: Properties of the message
:return: Coroutine object with result of message handling operation
"""
subscribers = self._get_subscribers(envelope.routing_key)
if not subscribers:
logger.debug("No route for message with key '%s'", envelope.routing_key)
return
body = self._serializer.deserialize(body)
for subscriber in subscribers:
# Check later if ensure_future can be applied here
await subscriber.on_message(body, envelope.routing_key)
await self._channel.basic_client_ack(envelope.delivery_tag) | [
"async",
"def",
"_on_message",
"(",
"self",
",",
"channel",
",",
"body",
",",
"envelope",
",",
"properties",
")",
"->",
"None",
":",
"subscribers",
"=",
"self",
".",
"_get_subscribers",
"(",
"envelope",
".",
"routing_key",
")",
"if",
"not",
"subscribers",
":",
"logger",
".",
"debug",
"(",
"\"No route for message with key '%s'\"",
",",
"envelope",
".",
"routing_key",
")",
"return",
"body",
"=",
"self",
".",
"_serializer",
".",
"deserialize",
"(",
"body",
")",
"for",
"subscriber",
"in",
"subscribers",
":",
"# Check later if ensure_future can be applied here",
"await",
"subscriber",
".",
"on_message",
"(",
"body",
",",
"envelope",
".",
"routing_key",
")",
"await",
"self",
".",
"_channel",
".",
"basic_client_ack",
"(",
"envelope",
".",
"delivery_tag",
")"
] | Fires up when message is received by this consumer.
:param channel: Channel, through which message is received
:param body: Body of the message (serialized).
:param envelope: Envelope object with message meta
:type envelope: aioamqp.Envelope
:param properties: Properties of the message
:return: Coroutine object with result of message handling operation | [
"Fires",
"up",
"when",
"message",
"is",
"received",
"by",
"this",
"consumer",
"."
] | 5117ec797a38eb82d955241d20547d125efe80f3 | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L196-L219 |
249,223 | bertrandvidal/parse_this | parse_this/__init__.py | parse_this | def parse_this(func, types, args=None, delimiter_chars=":"):
"""Create an ArgParser for the given function converting the command line
arguments according to the list of types.
Args:
func: the function for which the command line arguments to be parsed
types: a list of types - as accepted by argparse - that will be used to
convert the command line arguments
args: a list of arguments to be parsed if None sys.argv is used
delimiter_chars: characters used to separate the parameters from their
help message in the docstring. Defaults to ':'
"""
_LOG.debug("Creating parser for %s", func.__name__)
(func_args, dummy_1, dummy_2, defaults) = getargspec(func)
types, func_args = _check_types(func.__name__, types, func_args, defaults)
args_and_defaults = _get_args_and_defaults(func_args, defaults)
parser = _get_arg_parser(func, types, args_and_defaults, delimiter_chars)
arguments = parser.parse_args(_get_args_to_parse(args, sys.argv))
return _call(func, func_args, arguments) | python | def parse_this(func, types, args=None, delimiter_chars=":"):
"""Create an ArgParser for the given function converting the command line
arguments according to the list of types.
Args:
func: the function for which the command line arguments to be parsed
types: a list of types - as accepted by argparse - that will be used to
convert the command line arguments
args: a list of arguments to be parsed if None sys.argv is used
delimiter_chars: characters used to separate the parameters from their
help message in the docstring. Defaults to ':'
"""
_LOG.debug("Creating parser for %s", func.__name__)
(func_args, dummy_1, dummy_2, defaults) = getargspec(func)
types, func_args = _check_types(func.__name__, types, func_args, defaults)
args_and_defaults = _get_args_and_defaults(func_args, defaults)
parser = _get_arg_parser(func, types, args_and_defaults, delimiter_chars)
arguments = parser.parse_args(_get_args_to_parse(args, sys.argv))
return _call(func, func_args, arguments) | [
"def",
"parse_this",
"(",
"func",
",",
"types",
",",
"args",
"=",
"None",
",",
"delimiter_chars",
"=",
"\":\"",
")",
":",
"_LOG",
".",
"debug",
"(",
"\"Creating parser for %s\"",
",",
"func",
".",
"__name__",
")",
"(",
"func_args",
",",
"dummy_1",
",",
"dummy_2",
",",
"defaults",
")",
"=",
"getargspec",
"(",
"func",
")",
"types",
",",
"func_args",
"=",
"_check_types",
"(",
"func",
".",
"__name__",
",",
"types",
",",
"func_args",
",",
"defaults",
")",
"args_and_defaults",
"=",
"_get_args_and_defaults",
"(",
"func_args",
",",
"defaults",
")",
"parser",
"=",
"_get_arg_parser",
"(",
"func",
",",
"types",
",",
"args_and_defaults",
",",
"delimiter_chars",
")",
"arguments",
"=",
"parser",
".",
"parse_args",
"(",
"_get_args_to_parse",
"(",
"args",
",",
"sys",
".",
"argv",
")",
")",
"return",
"_call",
"(",
"func",
",",
"func_args",
",",
"arguments",
")"
] | Create an ArgParser for the given function converting the command line
arguments according to the list of types.
Args:
func: the function for which the command line arguments to be parsed
types: a list of types - as accepted by argparse - that will be used to
convert the command line arguments
args: a list of arguments to be parsed if None sys.argv is used
delimiter_chars: characters used to separate the parameters from their
help message in the docstring. Defaults to ':' | [
"Create",
"an",
"ArgParser",
"for",
"the",
"given",
"function",
"converting",
"the",
"command",
"line",
"arguments",
"according",
"to",
"the",
"list",
"of",
"types",
"."
] | aa2e3737f19642300ef1ca65cae21c90049718a2 | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L19-L37 |
249,224 | bertrandvidal/parse_this | parse_this/__init__.py | parse_class._add_sub_parsers | def _add_sub_parsers(self, top_level_parser, methods_to_parse, class_name):
"""Add all the sub-parsers to the top_level_parser.
Args:
top_level_parser: the top level parser
methods_to_parse: dict of method name pointing to their associated
argument parser
class_name: name of the decorated class
Returns:
a dict of registered name of the parser i.e. sub command name
pointing to the method real name
"""
description = "Accessible methods of {}".format(class_name)
sub_parsers = top_level_parser.add_subparsers(description=description,
dest="method")
# Holds the mapping between the name registered for the parser
# and the method real name. It is useful in the 'inner_call'
# method retrieve the real method
parser_to_method = {}
for method_name, parser in methods_to_parse.items():
# We use the name provided in 'create_parser` or the name of the
# decorated method
parser_name = parser.get_name() or method_name
# Make the method name compatible for the argument parsing
if parser_name.startswith("_"):
if not self._parse_private:
# We skip private methods if the caller asked not to
# parse them
continue
# 'Private' methods are exposed without their leading or
# trailing '_'s. Also works for 'special' methods.
parser_name = parser_name.strip("_")
parser_name = parser_name.replace("_", "-")
parser_to_method[parser_name] = method_name
sub_parsers.add_parser(parser_name, parents=[parser],
add_help=False,
description=parser.description)
return parser_to_method | python | def _add_sub_parsers(self, top_level_parser, methods_to_parse, class_name):
"""Add all the sub-parsers to the top_level_parser.
Args:
top_level_parser: the top level parser
methods_to_parse: dict of method name pointing to their associated
argument parser
class_name: name of the decorated class
Returns:
a dict of registered name of the parser i.e. sub command name
pointing to the method real name
"""
description = "Accessible methods of {}".format(class_name)
sub_parsers = top_level_parser.add_subparsers(description=description,
dest="method")
# Holds the mapping between the name registered for the parser
# and the method real name. It is useful in the 'inner_call'
# method retrieve the real method
parser_to_method = {}
for method_name, parser in methods_to_parse.items():
# We use the name provided in 'create_parser` or the name of the
# decorated method
parser_name = parser.get_name() or method_name
# Make the method name compatible for the argument parsing
if parser_name.startswith("_"):
if not self._parse_private:
# We skip private methods if the caller asked not to
# parse them
continue
# 'Private' methods are exposed without their leading or
# trailing '_'s. Also works for 'special' methods.
parser_name = parser_name.strip("_")
parser_name = parser_name.replace("_", "-")
parser_to_method[parser_name] = method_name
sub_parsers.add_parser(parser_name, parents=[parser],
add_help=False,
description=parser.description)
return parser_to_method | [
"def",
"_add_sub_parsers",
"(",
"self",
",",
"top_level_parser",
",",
"methods_to_parse",
",",
"class_name",
")",
":",
"description",
"=",
"\"Accessible methods of {}\"",
".",
"format",
"(",
"class_name",
")",
"sub_parsers",
"=",
"top_level_parser",
".",
"add_subparsers",
"(",
"description",
"=",
"description",
",",
"dest",
"=",
"\"method\"",
")",
"# Holds the mapping between the name registered for the parser",
"# and the method real name. It is useful in the 'inner_call'",
"# method retrieve the real method",
"parser_to_method",
"=",
"{",
"}",
"for",
"method_name",
",",
"parser",
"in",
"methods_to_parse",
".",
"items",
"(",
")",
":",
"# We use the name provided in 'create_parser` or the name of the",
"# decorated method",
"parser_name",
"=",
"parser",
".",
"get_name",
"(",
")",
"or",
"method_name",
"# Make the method name compatible for the argument parsing",
"if",
"parser_name",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"if",
"not",
"self",
".",
"_parse_private",
":",
"# We skip private methods if the caller asked not to",
"# parse them",
"continue",
"# 'Private' methods are exposed without their leading or",
"# trailing '_'s. Also works for 'special' methods.",
"parser_name",
"=",
"parser_name",
".",
"strip",
"(",
"\"_\"",
")",
"parser_name",
"=",
"parser_name",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
"parser_to_method",
"[",
"parser_name",
"]",
"=",
"method_name",
"sub_parsers",
".",
"add_parser",
"(",
"parser_name",
",",
"parents",
"=",
"[",
"parser",
"]",
",",
"add_help",
"=",
"False",
",",
"description",
"=",
"parser",
".",
"description",
")",
"return",
"parser_to_method"
] | Add all the sub-parsers to the top_level_parser.
Args:
top_level_parser: the top level parser
methods_to_parse: dict of method name pointing to their associated
argument parser
class_name: name of the decorated class
Returns:
a dict of registered name of the parser i.e. sub command name
pointing to the method real name | [
"Add",
"all",
"the",
"sub",
"-",
"parsers",
"to",
"the",
"top_level_parser",
"."
] | aa2e3737f19642300ef1ca65cae21c90049718a2 | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L119-L157 |
249,225 | bertrandvidal/parse_this | parse_this/__init__.py | parse_class._set_class_parser | def _set_class_parser(self, init_parser, methods_to_parse, cls):
"""Creates the complete argument parser for the decorated class.
Args:
init_parser: argument parser for the __init__ method or None
methods_to_parse: dict of method name pointing to their associated
argument parser
cls: the class we are decorating
Returns:
The decorated class with an added attribute 'parser'
"""
top_level_parents = [init_parser] if init_parser else []
description = self._description or cls.__doc__
top_level_parser = argparse.ArgumentParser(description=description,
parents=top_level_parents,
add_help=False,
conflict_handler="resolve")
top_level_parser.add_argument("-h", "--help", action=FullHelpAction,
help="Display this help message")
parser_to_method = self._add_sub_parsers(top_level_parser,
methods_to_parse,
cls.__name__)
# Update the dict with the __init__ method so we can instantiate
# the decorated class
if init_parser:
parser_to_method["__init__"] = "__init__"
top_level_parser.call = self._get_parser_call_method(parser_to_method)
cls.parser = top_level_parser | python | def _set_class_parser(self, init_parser, methods_to_parse, cls):
"""Creates the complete argument parser for the decorated class.
Args:
init_parser: argument parser for the __init__ method or None
methods_to_parse: dict of method name pointing to their associated
argument parser
cls: the class we are decorating
Returns:
The decorated class with an added attribute 'parser'
"""
top_level_parents = [init_parser] if init_parser else []
description = self._description or cls.__doc__
top_level_parser = argparse.ArgumentParser(description=description,
parents=top_level_parents,
add_help=False,
conflict_handler="resolve")
top_level_parser.add_argument("-h", "--help", action=FullHelpAction,
help="Display this help message")
parser_to_method = self._add_sub_parsers(top_level_parser,
methods_to_parse,
cls.__name__)
# Update the dict with the __init__ method so we can instantiate
# the decorated class
if init_parser:
parser_to_method["__init__"] = "__init__"
top_level_parser.call = self._get_parser_call_method(parser_to_method)
cls.parser = top_level_parser | [
"def",
"_set_class_parser",
"(",
"self",
",",
"init_parser",
",",
"methods_to_parse",
",",
"cls",
")",
":",
"top_level_parents",
"=",
"[",
"init_parser",
"]",
"if",
"init_parser",
"else",
"[",
"]",
"description",
"=",
"self",
".",
"_description",
"or",
"cls",
".",
"__doc__",
"top_level_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"parents",
"=",
"top_level_parents",
",",
"add_help",
"=",
"False",
",",
"conflict_handler",
"=",
"\"resolve\"",
")",
"top_level_parser",
".",
"add_argument",
"(",
"\"-h\"",
",",
"\"--help\"",
",",
"action",
"=",
"FullHelpAction",
",",
"help",
"=",
"\"Display this help message\"",
")",
"parser_to_method",
"=",
"self",
".",
"_add_sub_parsers",
"(",
"top_level_parser",
",",
"methods_to_parse",
",",
"cls",
".",
"__name__",
")",
"# Update the dict with the __init__ method so we can instantiate",
"# the decorated class",
"if",
"init_parser",
":",
"parser_to_method",
"[",
"\"__init__\"",
"]",
"=",
"\"__init__\"",
"top_level_parser",
".",
"call",
"=",
"self",
".",
"_get_parser_call_method",
"(",
"parser_to_method",
")",
"cls",
".",
"parser",
"=",
"top_level_parser"
] | Creates the complete argument parser for the decorated class.
Args:
init_parser: argument parser for the __init__ method or None
methods_to_parse: dict of method name pointing to their associated
argument parser
cls: the class we are decorating
Returns:
The decorated class with an added attribute 'parser' | [
"Creates",
"the",
"complete",
"argument",
"parser",
"for",
"the",
"decorated",
"class",
"."
] | aa2e3737f19642300ef1ca65cae21c90049718a2 | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L159-L187 |
249,226 | bertrandvidal/parse_this | parse_this/__init__.py | parse_class._get_parser_call_method | def _get_parser_call_method(self, parser_to_method):
"""Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to
"""
def inner_call(args=None, instance=None):
"""Allows to call the method invoked from the command line or
provided argument.
Args:
args: list of arguments to parse, defaults to command line
arguments
instance: an instance of the decorated class. If instance is
None, the default, and __init__ is decorated the object will be
instantiated on the fly from the command line arguments
"""
parser = self._cls.parser
namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))
if instance is None:
# If the __init__ method is not part of the method to
# decorate we cannot instantiate the class
if "__init__" not in parser_to_method:
raise ParseThisError(("'__init__' method is not decorated. "
"Please provide an instance to "
"'{}.parser.call' or decorate the "
"'__init___' method with "
"'create_parser'"
.format(self._cls.__name__)))
# We instantiate the class from the command line arguments
instance = _call_method_from_namespace(self._cls, "__init__",
namespace)
method_name = parser_to_method[namespace.method]
return _call_method_from_namespace(instance, method_name, namespace)
return inner_call | python | def _get_parser_call_method(self, parser_to_method):
"""Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to
"""
def inner_call(args=None, instance=None):
"""Allows to call the method invoked from the command line or
provided argument.
Args:
args: list of arguments to parse, defaults to command line
arguments
instance: an instance of the decorated class. If instance is
None, the default, and __init__ is decorated the object will be
instantiated on the fly from the command line arguments
"""
parser = self._cls.parser
namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))
if instance is None:
# If the __init__ method is not part of the method to
# decorate we cannot instantiate the class
if "__init__" not in parser_to_method:
raise ParseThisError(("'__init__' method is not decorated. "
"Please provide an instance to "
"'{}.parser.call' or decorate the "
"'__init___' method with "
"'create_parser'"
.format(self._cls.__name__)))
# We instantiate the class from the command line arguments
instance = _call_method_from_namespace(self._cls, "__init__",
namespace)
method_name = parser_to_method[namespace.method]
return _call_method_from_namespace(instance, method_name, namespace)
return inner_call | [
"def",
"_get_parser_call_method",
"(",
"self",
",",
"parser_to_method",
")",
":",
"def",
"inner_call",
"(",
"args",
"=",
"None",
",",
"instance",
"=",
"None",
")",
":",
"\"\"\"Allows to call the method invoked from the command line or\n provided argument.\n\n Args:\n args: list of arguments to parse, defaults to command line\n arguments\n instance: an instance of the decorated class. If instance is\n None, the default, and __init__ is decorated the object will be\n instantiated on the fly from the command line arguments\n \"\"\"",
"parser",
"=",
"self",
".",
"_cls",
".",
"parser",
"namespace",
"=",
"parser",
".",
"parse_args",
"(",
"_get_args_to_parse",
"(",
"args",
",",
"sys",
".",
"argv",
")",
")",
"if",
"instance",
"is",
"None",
":",
"# If the __init__ method is not part of the method to",
"# decorate we cannot instantiate the class",
"if",
"\"__init__\"",
"not",
"in",
"parser_to_method",
":",
"raise",
"ParseThisError",
"(",
"(",
"\"'__init__' method is not decorated. \"",
"\"Please provide an instance to \"",
"\"'{}.parser.call' or decorate the \"",
"\"'__init___' method with \"",
"\"'create_parser'\"",
".",
"format",
"(",
"self",
".",
"_cls",
".",
"__name__",
")",
")",
")",
"# We instantiate the class from the command line arguments",
"instance",
"=",
"_call_method_from_namespace",
"(",
"self",
".",
"_cls",
",",
"\"__init__\"",
",",
"namespace",
")",
"method_name",
"=",
"parser_to_method",
"[",
"namespace",
".",
"method",
"]",
"return",
"_call_method_from_namespace",
"(",
"instance",
",",
"method_name",
",",
"namespace",
")",
"return",
"inner_call"
] | Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to | [
"Return",
"the",
"parser",
"special",
"method",
"call",
"that",
"handles",
"sub",
"-",
"command",
"calling",
"."
] | aa2e3737f19642300ef1ca65cae21c90049718a2 | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/__init__.py#L189-L225 |
249,227 | tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_lcltpt.py | gp_lcltpt | def gp_lcltpt():
""" example plot to display linecolors, linetypes and pointtypes
.. image:: pics/gp_lcltpt.png
:width: 450 px
"""
inDir, outDir = getWorkDirs()
nSets = len(default_colors)
make_plot(
data = [
np.array([ [0,i,0,0,0], [1,i,0,0,0] ])
for i in xrange(nSets)
],
properties = [
'with linespoints lw 4 lc %s lt %d pt %d' % (col, i, i)
for i, col in enumerate(default_colors)
],
titles = [''] * nSets, yr = [-1, 51],
name = os.path.join(outDir, 'gp_lcltpt'),
ylabel = 'linecolor / linetype / pointtype', xlabel = '',
)
return 'done' | python | def gp_lcltpt():
""" example plot to display linecolors, linetypes and pointtypes
.. image:: pics/gp_lcltpt.png
:width: 450 px
"""
inDir, outDir = getWorkDirs()
nSets = len(default_colors)
make_plot(
data = [
np.array([ [0,i,0,0,0], [1,i,0,0,0] ])
for i in xrange(nSets)
],
properties = [
'with linespoints lw 4 lc %s lt %d pt %d' % (col, i, i)
for i, col in enumerate(default_colors)
],
titles = [''] * nSets, yr = [-1, 51],
name = os.path.join(outDir, 'gp_lcltpt'),
ylabel = 'linecolor / linetype / pointtype', xlabel = '',
)
return 'done' | [
"def",
"gp_lcltpt",
"(",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"nSets",
"=",
"len",
"(",
"default_colors",
")",
"make_plot",
"(",
"data",
"=",
"[",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"i",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"1",
",",
"i",
",",
"0",
",",
"0",
",",
"0",
"]",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"nSets",
")",
"]",
",",
"properties",
"=",
"[",
"'with linespoints lw 4 lc %s lt %d pt %d'",
"%",
"(",
"col",
",",
"i",
",",
"i",
")",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"default_colors",
")",
"]",
",",
"titles",
"=",
"[",
"''",
"]",
"*",
"nSets",
",",
"yr",
"=",
"[",
"-",
"1",
",",
"51",
"]",
",",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outDir",
",",
"'gp_lcltpt'",
")",
",",
"ylabel",
"=",
"'linecolor / linetype / pointtype'",
",",
"xlabel",
"=",
"''",
",",
")",
"return",
"'done'"
] | example plot to display linecolors, linetypes and pointtypes
.. image:: pics/gp_lcltpt.png
:width: 450 px | [
"example",
"plot",
"to",
"display",
"linecolors",
"linetypes",
"and",
"pointtypes"
] | e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2 | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_lcltpt.py#L7-L28 |
249,228 | pjanis/funtool | funtool/api.py | run_analyses | def run_analyses(prepared_analyses=None,log_dir=default_log_dir):
"""
If all defaults are ok, this should be the only function needed to run the analyses.
"""
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
for analysis in prepared_analyses:
state_collection= funtool.analysis.run_analysis(analysis, state_collection, log_dir)
return state_collection | python | def run_analyses(prepared_analyses=None,log_dir=default_log_dir):
"""
If all defaults are ok, this should be the only function needed to run the analyses.
"""
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
for analysis in prepared_analyses:
state_collection= funtool.analysis.run_analysis(analysis, state_collection, log_dir)
return state_collection | [
"def",
"run_analyses",
"(",
"prepared_analyses",
"=",
"None",
",",
"log_dir",
"=",
"default_log_dir",
")",
":",
"if",
"prepared_analyses",
"==",
"None",
":",
"prepared_analyses",
"=",
"prepare_analyses",
"(",
")",
"state_collection",
"=",
"funtool",
".",
"state_collection",
".",
"StateCollection",
"(",
"[",
"]",
",",
"{",
"}",
")",
"for",
"analysis",
"in",
"prepared_analyses",
":",
"state_collection",
"=",
"funtool",
".",
"analysis",
".",
"run_analysis",
"(",
"analysis",
",",
"state_collection",
",",
"log_dir",
")",
"return",
"state_collection"
] | If all defaults are ok, this should be the only function needed to run the analyses. | [
"If",
"all",
"defaults",
"are",
"ok",
"this",
"should",
"be",
"the",
"only",
"function",
"needed",
"to",
"run",
"the",
"analyses",
"."
] | 231851238f0a62bc3682d8fa937db9053378c53d | https://github.com/pjanis/funtool/blob/231851238f0a62bc3682d8fa937db9053378c53d/funtool/api.py#L98-L107 |
249,229 | pjanis/funtool | funtool/api.py | run_analysis | def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir):
"""
Runs just the named analysis. Otherwise just like run_analyses
"""
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
for analysis in prepared_analyses:
if analysis.name == named_analysis:
state_collection= funtool.analysis.run_analysis(analysis, state_collection, log_dir)
return state_collection | python | def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir):
"""
Runs just the named analysis. Otherwise just like run_analyses
"""
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
for analysis in prepared_analyses:
if analysis.name == named_analysis:
state_collection= funtool.analysis.run_analysis(analysis, state_collection, log_dir)
return state_collection | [
"def",
"run_analysis",
"(",
"named_analysis",
",",
"prepared_analyses",
"=",
"None",
",",
"log_dir",
"=",
"default_log_dir",
")",
":",
"if",
"prepared_analyses",
"==",
"None",
":",
"prepared_analyses",
"=",
"prepare_analyses",
"(",
")",
"state_collection",
"=",
"funtool",
".",
"state_collection",
".",
"StateCollection",
"(",
"[",
"]",
",",
"{",
"}",
")",
"for",
"analysis",
"in",
"prepared_analyses",
":",
"if",
"analysis",
".",
"name",
"==",
"named_analysis",
":",
"state_collection",
"=",
"funtool",
".",
"analysis",
".",
"run_analysis",
"(",
"analysis",
",",
"state_collection",
",",
"log_dir",
")",
"return",
"state_collection"
] | Runs just the named analysis. Otherwise just like run_analyses | [
"Runs",
"just",
"the",
"named",
"analysis",
".",
"Otherwise",
"just",
"like",
"run_analyses"
] | 231851238f0a62bc3682d8fa937db9053378c53d | https://github.com/pjanis/funtool/blob/231851238f0a62bc3682d8fa937db9053378c53d/funtool/api.py#L109-L119 |
249,230 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/poller.py | AsyncPoller.poll | def poll(self):
""" Poll the job status.
Returns the changes in this iteration."""
self.runner.module_name = 'async_status'
self.runner.module_args = "jid=%s" % self.jid
self.runner.pattern = "*"
self.runner.background = 0
self.runner.inventory.restrict_to(self.hosts_to_poll)
results = self.runner.run()
self.runner.inventory.lift_restriction()
hosts = []
poll_results = { 'contacted': {}, 'dark': {}, 'polled': {}}
for (host, res) in results['contacted'].iteritems():
if res.get('started',False):
hosts.append(host)
poll_results['polled'][host] = res
else:
self.results['contacted'][host] = res
poll_results['contacted'][host] = res
if 'failed' in res:
self.runner.callbacks.on_async_failed(host, res, self.jid)
else:
self.runner.callbacks.on_async_ok(host, res, self.jid)
for (host, res) in results['dark'].iteritems():
self.results['dark'][host] = res
poll_results['dark'][host] = res
self.runner.callbacks.on_async_failed(host, res, self.jid)
self.hosts_to_poll = hosts
if len(hosts)==0:
self.completed = True
return poll_results | python | def poll(self):
""" Poll the job status.
Returns the changes in this iteration."""
self.runner.module_name = 'async_status'
self.runner.module_args = "jid=%s" % self.jid
self.runner.pattern = "*"
self.runner.background = 0
self.runner.inventory.restrict_to(self.hosts_to_poll)
results = self.runner.run()
self.runner.inventory.lift_restriction()
hosts = []
poll_results = { 'contacted': {}, 'dark': {}, 'polled': {}}
for (host, res) in results['contacted'].iteritems():
if res.get('started',False):
hosts.append(host)
poll_results['polled'][host] = res
else:
self.results['contacted'][host] = res
poll_results['contacted'][host] = res
if 'failed' in res:
self.runner.callbacks.on_async_failed(host, res, self.jid)
else:
self.runner.callbacks.on_async_ok(host, res, self.jid)
for (host, res) in results['dark'].iteritems():
self.results['dark'][host] = res
poll_results['dark'][host] = res
self.runner.callbacks.on_async_failed(host, res, self.jid)
self.hosts_to_poll = hosts
if len(hosts)==0:
self.completed = True
return poll_results | [
"def",
"poll",
"(",
"self",
")",
":",
"self",
".",
"runner",
".",
"module_name",
"=",
"'async_status'",
"self",
".",
"runner",
".",
"module_args",
"=",
"\"jid=%s\"",
"%",
"self",
".",
"jid",
"self",
".",
"runner",
".",
"pattern",
"=",
"\"*\"",
"self",
".",
"runner",
".",
"background",
"=",
"0",
"self",
".",
"runner",
".",
"inventory",
".",
"restrict_to",
"(",
"self",
".",
"hosts_to_poll",
")",
"results",
"=",
"self",
".",
"runner",
".",
"run",
"(",
")",
"self",
".",
"runner",
".",
"inventory",
".",
"lift_restriction",
"(",
")",
"hosts",
"=",
"[",
"]",
"poll_results",
"=",
"{",
"'contacted'",
":",
"{",
"}",
",",
"'dark'",
":",
"{",
"}",
",",
"'polled'",
":",
"{",
"}",
"}",
"for",
"(",
"host",
",",
"res",
")",
"in",
"results",
"[",
"'contacted'",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"res",
".",
"get",
"(",
"'started'",
",",
"False",
")",
":",
"hosts",
".",
"append",
"(",
"host",
")",
"poll_results",
"[",
"'polled'",
"]",
"[",
"host",
"]",
"=",
"res",
"else",
":",
"self",
".",
"results",
"[",
"'contacted'",
"]",
"[",
"host",
"]",
"=",
"res",
"poll_results",
"[",
"'contacted'",
"]",
"[",
"host",
"]",
"=",
"res",
"if",
"'failed'",
"in",
"res",
":",
"self",
".",
"runner",
".",
"callbacks",
".",
"on_async_failed",
"(",
"host",
",",
"res",
",",
"self",
".",
"jid",
")",
"else",
":",
"self",
".",
"runner",
".",
"callbacks",
".",
"on_async_ok",
"(",
"host",
",",
"res",
",",
"self",
".",
"jid",
")",
"for",
"(",
"host",
",",
"res",
")",
"in",
"results",
"[",
"'dark'",
"]",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"results",
"[",
"'dark'",
"]",
"[",
"host",
"]",
"=",
"res",
"poll_results",
"[",
"'dark'",
"]",
"[",
"host",
"]",
"=",
"res",
"self",
".",
"runner",
".",
"callbacks",
".",
"on_async_failed",
"(",
"host",
",",
"res",
",",
"self",
".",
"jid",
")",
"self",
".",
"hosts_to_poll",
"=",
"hosts",
"if",
"len",
"(",
"hosts",
")",
"==",
"0",
":",
"self",
".",
"completed",
"=",
"True",
"return",
"poll_results"
] | Poll the job status.
Returns the changes in this iteration. | [
"Poll",
"the",
"job",
"status",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/poller.py#L54-L89 |
249,231 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/poller.py | AsyncPoller.wait | def wait(self, seconds, poll_interval):
""" Wait a certain time for job completion, check status every poll_interval. """
# jid is None when all hosts were skipped
if self.jid is None:
return self.results
clock = seconds - poll_interval
while (clock >= 0 and not self.completed):
time.sleep(poll_interval)
poll_results = self.poll()
for (host, res) in poll_results['polled'].iteritems():
if res.get('started'):
self.runner.callbacks.on_async_poll(host, res, self.jid, clock)
clock = clock - poll_interval
return self.results | python | def wait(self, seconds, poll_interval):
""" Wait a certain time for job completion, check status every poll_interval. """
# jid is None when all hosts were skipped
if self.jid is None:
return self.results
clock = seconds - poll_interval
while (clock >= 0 and not self.completed):
time.sleep(poll_interval)
poll_results = self.poll()
for (host, res) in poll_results['polled'].iteritems():
if res.get('started'):
self.runner.callbacks.on_async_poll(host, res, self.jid, clock)
clock = clock - poll_interval
return self.results | [
"def",
"wait",
"(",
"self",
",",
"seconds",
",",
"poll_interval",
")",
":",
"# jid is None when all hosts were skipped",
"if",
"self",
".",
"jid",
"is",
"None",
":",
"return",
"self",
".",
"results",
"clock",
"=",
"seconds",
"-",
"poll_interval",
"while",
"(",
"clock",
">=",
"0",
"and",
"not",
"self",
".",
"completed",
")",
":",
"time",
".",
"sleep",
"(",
"poll_interval",
")",
"poll_results",
"=",
"self",
".",
"poll",
"(",
")",
"for",
"(",
"host",
",",
"res",
")",
"in",
"poll_results",
"[",
"'polled'",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"res",
".",
"get",
"(",
"'started'",
")",
":",
"self",
".",
"runner",
".",
"callbacks",
".",
"on_async_poll",
"(",
"host",
",",
"res",
",",
"self",
".",
"jid",
",",
"clock",
")",
"clock",
"=",
"clock",
"-",
"poll_interval",
"return",
"self",
".",
"results"
] | Wait a certain time for job completion, check status every poll_interval. | [
"Wait",
"a",
"certain",
"time",
"for",
"job",
"completion",
"check",
"status",
"every",
"poll_interval",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/poller.py#L91-L109 |
249,232 | minhhoit/yacms | yacms/core/forms.py | get_edit_form | def get_edit_form(obj, field_names, data=None, files=None):
"""
Returns the in-line editing form for editing a single model field.
"""
# Map these form fields to their types defined in the forms app so
# we can make use of their custom widgets.
from yacms.forms import fields
widget_overrides = {
forms.DateField: fields.DATE,
forms.DateTimeField: fields.DATE_TIME,
forms.EmailField: fields.EMAIL,
}
class EditForm(forms.ModelForm):
"""
In-line editing form for editing a single model field.
"""
app = forms.CharField(widget=forms.HiddenInput)
model = forms.CharField(widget=forms.HiddenInput)
id = forms.CharField(widget=forms.HiddenInput)
fields = forms.CharField(widget=forms.HiddenInput)
class Meta:
model = obj.__class__
fields = field_names.split(",")
def __init__(self, *args, **kwargs):
super(EditForm, self).__init__(*args, **kwargs)
self.uuid = str(uuid4())
for f in self.fields.keys():
field_class = self.fields[f].__class__
try:
widget = fields.WIDGETS[widget_overrides[field_class]]
except KeyError:
pass
else:
self.fields[f].widget = widget()
css_class = self.fields[f].widget.attrs.get("class", "")
css_class += " " + field_class.__name__.lower()
self.fields[f].widget.attrs["class"] = css_class
self.fields[f].widget.attrs["id"] = "%s-%s" % (f, self.uuid)
if settings.FORMS_USE_HTML5 and self.fields[f].required:
self.fields[f].widget.attrs["required"] = ""
initial = {"app": obj._meta.app_label, "id": obj.id,
"fields": field_names, "model": obj._meta.object_name.lower()}
return EditForm(instance=obj, initial=initial, data=data, files=files) | python | def get_edit_form(obj, field_names, data=None, files=None):
"""
Returns the in-line editing form for editing a single model field.
"""
# Map these form fields to their types defined in the forms app so
# we can make use of their custom widgets.
from yacms.forms import fields
widget_overrides = {
forms.DateField: fields.DATE,
forms.DateTimeField: fields.DATE_TIME,
forms.EmailField: fields.EMAIL,
}
class EditForm(forms.ModelForm):
"""
In-line editing form for editing a single model field.
"""
app = forms.CharField(widget=forms.HiddenInput)
model = forms.CharField(widget=forms.HiddenInput)
id = forms.CharField(widget=forms.HiddenInput)
fields = forms.CharField(widget=forms.HiddenInput)
class Meta:
model = obj.__class__
fields = field_names.split(",")
def __init__(self, *args, **kwargs):
super(EditForm, self).__init__(*args, **kwargs)
self.uuid = str(uuid4())
for f in self.fields.keys():
field_class = self.fields[f].__class__
try:
widget = fields.WIDGETS[widget_overrides[field_class]]
except KeyError:
pass
else:
self.fields[f].widget = widget()
css_class = self.fields[f].widget.attrs.get("class", "")
css_class += " " + field_class.__name__.lower()
self.fields[f].widget.attrs["class"] = css_class
self.fields[f].widget.attrs["id"] = "%s-%s" % (f, self.uuid)
if settings.FORMS_USE_HTML5 and self.fields[f].required:
self.fields[f].widget.attrs["required"] = ""
initial = {"app": obj._meta.app_label, "id": obj.id,
"fields": field_names, "model": obj._meta.object_name.lower()}
return EditForm(instance=obj, initial=initial, data=data, files=files) | [
"def",
"get_edit_form",
"(",
"obj",
",",
"field_names",
",",
"data",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"# Map these form fields to their types defined in the forms app so",
"# we can make use of their custom widgets.",
"from",
"yacms",
".",
"forms",
"import",
"fields",
"widget_overrides",
"=",
"{",
"forms",
".",
"DateField",
":",
"fields",
".",
"DATE",
",",
"forms",
".",
"DateTimeField",
":",
"fields",
".",
"DATE_TIME",
",",
"forms",
".",
"EmailField",
":",
"fields",
".",
"EMAIL",
",",
"}",
"class",
"EditForm",
"(",
"forms",
".",
"ModelForm",
")",
":",
"\"\"\"\n In-line editing form for editing a single model field.\n \"\"\"",
"app",
"=",
"forms",
".",
"CharField",
"(",
"widget",
"=",
"forms",
".",
"HiddenInput",
")",
"model",
"=",
"forms",
".",
"CharField",
"(",
"widget",
"=",
"forms",
".",
"HiddenInput",
")",
"id",
"=",
"forms",
".",
"CharField",
"(",
"widget",
"=",
"forms",
".",
"HiddenInput",
")",
"fields",
"=",
"forms",
".",
"CharField",
"(",
"widget",
"=",
"forms",
".",
"HiddenInput",
")",
"class",
"Meta",
":",
"model",
"=",
"obj",
".",
"__class__",
"fields",
"=",
"field_names",
".",
"split",
"(",
"\",\"",
")",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"EditForm",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"uuid",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"for",
"f",
"in",
"self",
".",
"fields",
".",
"keys",
"(",
")",
":",
"field_class",
"=",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"__class__",
"try",
":",
"widget",
"=",
"fields",
".",
"WIDGETS",
"[",
"widget_overrides",
"[",
"field_class",
"]",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"widget",
"=",
"widget",
"(",
")",
"css_class",
"=",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"widget",
".",
"attrs",
".",
"get",
"(",
"\"class\"",
",",
"\"\"",
")",
"css_class",
"+=",
"\" \"",
"+",
"field_class",
".",
"__name__",
".",
"lower",
"(",
")",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"widget",
".",
"attrs",
"[",
"\"class\"",
"]",
"=",
"css_class",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"widget",
".",
"attrs",
"[",
"\"id\"",
"]",
"=",
"\"%s-%s\"",
"%",
"(",
"f",
",",
"self",
".",
"uuid",
")",
"if",
"settings",
".",
"FORMS_USE_HTML5",
"and",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"required",
":",
"self",
".",
"fields",
"[",
"f",
"]",
".",
"widget",
".",
"attrs",
"[",
"\"required\"",
"]",
"=",
"\"\"",
"initial",
"=",
"{",
"\"app\"",
":",
"obj",
".",
"_meta",
".",
"app_label",
",",
"\"id\"",
":",
"obj",
".",
"id",
",",
"\"fields\"",
":",
"field_names",
",",
"\"model\"",
":",
"obj",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
"}",
"return",
"EditForm",
"(",
"instance",
"=",
"obj",
",",
"initial",
"=",
"initial",
",",
"data",
"=",
"data",
",",
"files",
"=",
"files",
")"
] | Returns the in-line editing form for editing a single model field. | [
"Returns",
"the",
"in",
"-",
"line",
"editing",
"form",
"for",
"editing",
"a",
"single",
"model",
"field",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/forms.py#L107-L155 |
249,233 | polysquare/polysquare-generic-file-linter | polysquarelinter/lint_spelling_only.py | _filter_disabled_regions | def _filter_disabled_regions(contents):
"""Filter regions that are contained in back-ticks."""
contents = list(contents)
in_backticks = False
contents_len = len(contents)
index = 0
while index < contents_len:
character = contents[index]
if character == "`":
# Check to see if we should toggle the in_backticks
# mode here by looking ahead for another two characters.
if ((index + 2) < contents_len and
"".join(contents[index:index + 3]) == "```"):
in_backticks = not in_backticks
index += 3
continue
if in_backticks:
contents[index] = " "
index += 1
return "".join(contents) | python | def _filter_disabled_regions(contents):
"""Filter regions that are contained in back-ticks."""
contents = list(contents)
in_backticks = False
contents_len = len(contents)
index = 0
while index < contents_len:
character = contents[index]
if character == "`":
# Check to see if we should toggle the in_backticks
# mode here by looking ahead for another two characters.
if ((index + 2) < contents_len and
"".join(contents[index:index + 3]) == "```"):
in_backticks = not in_backticks
index += 3
continue
if in_backticks:
contents[index] = " "
index += 1
return "".join(contents) | [
"def",
"_filter_disabled_regions",
"(",
"contents",
")",
":",
"contents",
"=",
"list",
"(",
"contents",
")",
"in_backticks",
"=",
"False",
"contents_len",
"=",
"len",
"(",
"contents",
")",
"index",
"=",
"0",
"while",
"index",
"<",
"contents_len",
":",
"character",
"=",
"contents",
"[",
"index",
"]",
"if",
"character",
"==",
"\"`\"",
":",
"# Check to see if we should toggle the in_backticks",
"# mode here by looking ahead for another two characters.",
"if",
"(",
"(",
"index",
"+",
"2",
")",
"<",
"contents_len",
"and",
"\"\"",
".",
"join",
"(",
"contents",
"[",
"index",
":",
"index",
"+",
"3",
"]",
")",
"==",
"\"```\"",
")",
":",
"in_backticks",
"=",
"not",
"in_backticks",
"index",
"+=",
"3",
"continue",
"if",
"in_backticks",
":",
"contents",
"[",
"index",
"]",
"=",
"\" \"",
"index",
"+=",
"1",
"return",
"\"\"",
".",
"join",
"(",
"contents",
")"
] | Filter regions that are contained in back-ticks. | [
"Filter",
"regions",
"that",
"are",
"contained",
"in",
"back",
"-",
"ticks",
"."
] | cfc88771acd3d5551c28fa5d917bb0aeb584c4cc | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/lint_spelling_only.py#L28-L52 |
249,234 | polysquare/polysquare-generic-file-linter | polysquarelinter/lint_spelling_only.py | spellcheck | def spellcheck(contents, technical_terms=None, spellcheck_cache=None):
"""Run spellcheck on the contents of a file.
:technical_terms: is a path to a file containing a list of "technical"
terms. These may be symbols as collected from files by using
the generic linter or other such symbols. If a symbol-like term is
used within contents and it does not appear in :technical_terms: then
an error will result.
:spellcheck_cache: is a path to a directory where graph files generated
by the spellchecking engine should be stored. It is used for caching
purposes between invocations, since generating the spellchecking
graph is an expensive operation which can take a few seconds to complete.
"""
contents = spelling.filter_nonspellcheckable_tokens(contents)
contents = _filter_disabled_regions(contents)
lines = contents.splitlines(True)
user_words, valid_words = valid_words_dictionary.create(spellcheck_cache)
technical_words = technical_words_dictionary.create(technical_terms,
spellcheck_cache)
return sorted([e for e in spellcheck_region(lines,
valid_words,
technical_words,
user_words)]) | python | def spellcheck(contents, technical_terms=None, spellcheck_cache=None):
"""Run spellcheck on the contents of a file.
:technical_terms: is a path to a file containing a list of "technical"
terms. These may be symbols as collected from files by using
the generic linter or other such symbols. If a symbol-like term is
used within contents and it does not appear in :technical_terms: then
an error will result.
:spellcheck_cache: is a path to a directory where graph files generated
by the spellchecking engine should be stored. It is used for caching
purposes between invocations, since generating the spellchecking
graph is an expensive operation which can take a few seconds to complete.
"""
contents = spelling.filter_nonspellcheckable_tokens(contents)
contents = _filter_disabled_regions(contents)
lines = contents.splitlines(True)
user_words, valid_words = valid_words_dictionary.create(spellcheck_cache)
technical_words = technical_words_dictionary.create(technical_terms,
spellcheck_cache)
return sorted([e for e in spellcheck_region(lines,
valid_words,
technical_words,
user_words)]) | [
"def",
"spellcheck",
"(",
"contents",
",",
"technical_terms",
"=",
"None",
",",
"spellcheck_cache",
"=",
"None",
")",
":",
"contents",
"=",
"spelling",
".",
"filter_nonspellcheckable_tokens",
"(",
"contents",
")",
"contents",
"=",
"_filter_disabled_regions",
"(",
"contents",
")",
"lines",
"=",
"contents",
".",
"splitlines",
"(",
"True",
")",
"user_words",
",",
"valid_words",
"=",
"valid_words_dictionary",
".",
"create",
"(",
"spellcheck_cache",
")",
"technical_words",
"=",
"technical_words_dictionary",
".",
"create",
"(",
"technical_terms",
",",
"spellcheck_cache",
")",
"return",
"sorted",
"(",
"[",
"e",
"for",
"e",
"in",
"spellcheck_region",
"(",
"lines",
",",
"valid_words",
",",
"technical_words",
",",
"user_words",
")",
"]",
")"
] | Run spellcheck on the contents of a file.
:technical_terms: is a path to a file containing a list of "technical"
terms. These may be symbols as collected from files by using
the generic linter or other such symbols. If a symbol-like term is
used within contents and it does not appear in :technical_terms: then
an error will result.
:spellcheck_cache: is a path to a directory where graph files generated
by the spellchecking engine should be stored. It is used for caching
purposes between invocations, since generating the spellchecking
graph is an expensive operation which can take a few seconds to complete. | [
"Run",
"spellcheck",
"on",
"the",
"contents",
"of",
"a",
"file",
"."
] | cfc88771acd3d5551c28fa5d917bb0aeb584c4cc | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/lint_spelling_only.py#L55-L79 |
249,235 | polysquare/polysquare-generic-file-linter | polysquarelinter/lint_spelling_only.py | _report_spelling_error | def _report_spelling_error(error, file_path):
"""Report a spelling error."""
line = error.line_offset + 1
code = "file/spelling_error"
description = _SPELLCHECK_MESSAGES[error.error_type].format(error.word)
if error.suggestions is not None:
description = (description +
", perhaps you meant: " +
", ".join(error.suggestions))
sys.stdout.write("{0}:{1} [{2}] {3}\n".format(file_path,
line,
code,
description)) | python | def _report_spelling_error(error, file_path):
"""Report a spelling error."""
line = error.line_offset + 1
code = "file/spelling_error"
description = _SPELLCHECK_MESSAGES[error.error_type].format(error.word)
if error.suggestions is not None:
description = (description +
", perhaps you meant: " +
", ".join(error.suggestions))
sys.stdout.write("{0}:{1} [{2}] {3}\n".format(file_path,
line,
code,
description)) | [
"def",
"_report_spelling_error",
"(",
"error",
",",
"file_path",
")",
":",
"line",
"=",
"error",
".",
"line_offset",
"+",
"1",
"code",
"=",
"\"file/spelling_error\"",
"description",
"=",
"_SPELLCHECK_MESSAGES",
"[",
"error",
".",
"error_type",
"]",
".",
"format",
"(",
"error",
".",
"word",
")",
"if",
"error",
".",
"suggestions",
"is",
"not",
"None",
":",
"description",
"=",
"(",
"description",
"+",
"\", perhaps you meant: \"",
"+",
"\", \"",
".",
"join",
"(",
"error",
".",
"suggestions",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"{0}:{1} [{2}] {3}\\n\"",
".",
"format",
"(",
"file_path",
",",
"line",
",",
"code",
",",
"description",
")",
")"
] | Report a spelling error. | [
"Report",
"a",
"spelling",
"error",
"."
] | cfc88771acd3d5551c28fa5d917bb0aeb584c4cc | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/lint_spelling_only.py#L115-L128 |
249,236 | polysquare/polysquare-generic-file-linter | polysquarelinter/lint_spelling_only.py | main | def main(arguments=None): # suppress(unused-function)
"""Entry point for the spellcheck linter."""
dictionary_path = os.path.abspath("DICTIONARY")
result = _parse_arguments(arguments)
num_errors = 0
for found_filename in result.files:
file_path = os.path.abspath(found_filename)
with io.open(file_path, "r+", encoding="utf-8") as found_file:
jobstamps_dependencies = [file_path]
if os.path.exists(dictionary_path):
jobstamps_dependencies.append(dictionary_path)
if (result.technical_terms and
os.path.exists(result.technical_terms)):
jobstamps_dependencies.append(result.technical_terms)
kwargs = {
"jobstamps_dependencies": jobstamps_dependencies,
"jobstamps_cache_output_directory": result.stamp_file_path,
}
errors = jobstamp.run(spellcheck,
found_file.read(),
result.technical_terms,
result.spellcheck_cache,
**kwargs)
for error in errors:
_report_spelling_error(error, file_path)
num_errors += len(errors)
return num_errors | python | def main(arguments=None): # suppress(unused-function)
"""Entry point for the spellcheck linter."""
dictionary_path = os.path.abspath("DICTIONARY")
result = _parse_arguments(arguments)
num_errors = 0
for found_filename in result.files:
file_path = os.path.abspath(found_filename)
with io.open(file_path, "r+", encoding="utf-8") as found_file:
jobstamps_dependencies = [file_path]
if os.path.exists(dictionary_path):
jobstamps_dependencies.append(dictionary_path)
if (result.technical_terms and
os.path.exists(result.technical_terms)):
jobstamps_dependencies.append(result.technical_terms)
kwargs = {
"jobstamps_dependencies": jobstamps_dependencies,
"jobstamps_cache_output_directory": result.stamp_file_path,
}
errors = jobstamp.run(spellcheck,
found_file.read(),
result.technical_terms,
result.spellcheck_cache,
**kwargs)
for error in errors:
_report_spelling_error(error, file_path)
num_errors += len(errors)
return num_errors | [
"def",
"main",
"(",
"arguments",
"=",
"None",
")",
":",
"# suppress(unused-function)",
"dictionary_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"\"DICTIONARY\"",
")",
"result",
"=",
"_parse_arguments",
"(",
"arguments",
")",
"num_errors",
"=",
"0",
"for",
"found_filename",
"in",
"result",
".",
"files",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"found_filename",
")",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"\"r+\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"found_file",
":",
"jobstamps_dependencies",
"=",
"[",
"file_path",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dictionary_path",
")",
":",
"jobstamps_dependencies",
".",
"append",
"(",
"dictionary_path",
")",
"if",
"(",
"result",
".",
"technical_terms",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"result",
".",
"technical_terms",
")",
")",
":",
"jobstamps_dependencies",
".",
"append",
"(",
"result",
".",
"technical_terms",
")",
"kwargs",
"=",
"{",
"\"jobstamps_dependencies\"",
":",
"jobstamps_dependencies",
",",
"\"jobstamps_cache_output_directory\"",
":",
"result",
".",
"stamp_file_path",
",",
"}",
"errors",
"=",
"jobstamp",
".",
"run",
"(",
"spellcheck",
",",
"found_file",
".",
"read",
"(",
")",
",",
"result",
".",
"technical_terms",
",",
"result",
".",
"spellcheck_cache",
",",
"*",
"*",
"kwargs",
")",
"for",
"error",
"in",
"errors",
":",
"_report_spelling_error",
"(",
"error",
",",
"file_path",
")",
"num_errors",
"+=",
"len",
"(",
"errors",
")",
"return",
"num_errors"
] | Entry point for the spellcheck linter. | [
"Entry",
"point",
"for",
"the",
"spellcheck",
"linter",
"."
] | cfc88771acd3d5551c28fa5d917bb0aeb584c4cc | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/lint_spelling_only.py#L131-L165 |
249,237 | sirrice/scorpionsql | scorpionsql/errfunc.py | AggErrFunc.recover | def recover(self, state):
"recompute the actual value, then compare it against the truth"
newval = self.f.recover(state)
return self.errtype(self.value, newval) | python | def recover(self, state):
"recompute the actual value, then compare it against the truth"
newval = self.f.recover(state)
return self.errtype(self.value, newval) | [
"def",
"recover",
"(",
"self",
",",
"state",
")",
":",
"newval",
"=",
"self",
".",
"f",
".",
"recover",
"(",
"state",
")",
"return",
"self",
".",
"errtype",
"(",
"self",
".",
"value",
",",
"newval",
")"
] | recompute the actual value, then compare it against the truth | [
"recompute",
"the",
"actual",
"value",
"then",
"compare",
"it",
"against",
"the",
"truth"
] | baa05b745fae5df3171244c3e32160bd36c99e86 | https://github.com/sirrice/scorpionsql/blob/baa05b745fae5df3171244c3e32160bd36c99e86/scorpionsql/errfunc.py#L182-L185 |
249,238 | xtrementl/focus | focus/version.py | compare_version | def compare_version(value):
""" Determines if the provided version value compares with program version.
`value`
Version comparison string (e.g. ==1.0, <=1.0, >1.1)
Supported operators:
<, <=, ==, >, >=
"""
# extract parts from value
import re
res = re.match(r'(<|<=|==|>|>=)(\d{1,2}\.\d{1,2}(\.\d{1,2})?)$',
str(value).strip())
if not res:
return False
operator, value, _ = res.groups()
# break into pieces
value = tuple(int(x) for x in str(value).split('.'))
if len(value) < 3:
value += (0,)
version = __version_info__
if operator in ('<', '<='):
if version < value:
return True
if operator != '<=':
return False
elif operator in ('>=', '>'):
if version > value:
return True
if operator != '>=':
return False
return value == version | python | def compare_version(value):
""" Determines if the provided version value compares with program version.
`value`
Version comparison string (e.g. ==1.0, <=1.0, >1.1)
Supported operators:
<, <=, ==, >, >=
"""
# extract parts from value
import re
res = re.match(r'(<|<=|==|>|>=)(\d{1,2}\.\d{1,2}(\.\d{1,2})?)$',
str(value).strip())
if not res:
return False
operator, value, _ = res.groups()
# break into pieces
value = tuple(int(x) for x in str(value).split('.'))
if len(value) < 3:
value += (0,)
version = __version_info__
if operator in ('<', '<='):
if version < value:
return True
if operator != '<=':
return False
elif operator in ('>=', '>'):
if version > value:
return True
if operator != '>=':
return False
return value == version | [
"def",
"compare_version",
"(",
"value",
")",
":",
"# extract parts from value",
"import",
"re",
"res",
"=",
"re",
".",
"match",
"(",
"r'(<|<=|==|>|>=)(\\d{1,2}\\.\\d{1,2}(\\.\\d{1,2})?)$'",
",",
"str",
"(",
"value",
")",
".",
"strip",
"(",
")",
")",
"if",
"not",
"res",
":",
"return",
"False",
"operator",
",",
"value",
",",
"_",
"=",
"res",
".",
"groups",
"(",
")",
"# break into pieces",
"value",
"=",
"tuple",
"(",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"str",
"(",
"value",
")",
".",
"split",
"(",
"'.'",
")",
")",
"if",
"len",
"(",
"value",
")",
"<",
"3",
":",
"value",
"+=",
"(",
"0",
",",
")",
"version",
"=",
"__version_info__",
"if",
"operator",
"in",
"(",
"'<'",
",",
"'<='",
")",
":",
"if",
"version",
"<",
"value",
":",
"return",
"True",
"if",
"operator",
"!=",
"'<='",
":",
"return",
"False",
"elif",
"operator",
"in",
"(",
"'>='",
",",
"'>'",
")",
":",
"if",
"version",
">",
"value",
":",
"return",
"True",
"if",
"operator",
"!=",
"'>='",
":",
"return",
"False",
"return",
"value",
"==",
"version"
] | Determines if the provided version value compares with program version.
`value`
Version comparison string (e.g. ==1.0, <=1.0, >1.1)
Supported operators:
<, <=, ==, >, >= | [
"Determines",
"if",
"the",
"provided",
"version",
"value",
"compares",
"with",
"program",
"version",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/version.py#L8-L46 |
249,239 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/__init__.py | get_all_publications | def get_all_publications(return_namedtuples=True):
"""
Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
Returns:
list: List of :class:`.Publication` structures converted to namedtuple.
"""
sources = [
ben_cz.get_publications,
grada_cz.get_publications,
cpress_cz.get_publications,
zonerpress_cz.get_publications,
]
# get data from all scrappers
publications = []
for source in sources:
publications.extend(
filters.filter_publications(source())
)
# convert to namedtuples
if return_namedtuples:
publications = map(lambda x: x.to_namedtuple(), publications)
return publications | python | def get_all_publications(return_namedtuples=True):
"""
Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
Returns:
list: List of :class:`.Publication` structures converted to namedtuple.
"""
sources = [
ben_cz.get_publications,
grada_cz.get_publications,
cpress_cz.get_publications,
zonerpress_cz.get_publications,
]
# get data from all scrappers
publications = []
for source in sources:
publications.extend(
filters.filter_publications(source())
)
# convert to namedtuples
if return_namedtuples:
publications = map(lambda x: x.to_namedtuple(), publications)
return publications | [
"def",
"get_all_publications",
"(",
"return_namedtuples",
"=",
"True",
")",
":",
"sources",
"=",
"[",
"ben_cz",
".",
"get_publications",
",",
"grada_cz",
".",
"get_publications",
",",
"cpress_cz",
".",
"get_publications",
",",
"zonerpress_cz",
".",
"get_publications",
",",
"]",
"# get data from all scrappers",
"publications",
"=",
"[",
"]",
"for",
"source",
"in",
"sources",
":",
"publications",
".",
"extend",
"(",
"filters",
".",
"filter_publications",
"(",
"source",
"(",
")",
")",
")",
"# convert to namedtuples",
"if",
"return_namedtuples",
":",
"publications",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"to_namedtuple",
"(",
")",
",",
"publications",
")",
"return",
"publications"
] | Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
Returns:
list: List of :class:`.Publication` structures converted to namedtuple. | [
"Get",
"list",
"publications",
"from",
"all",
"available",
"source",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/__init__.py#L16-L46 |
249,240 | treycucco/bidon | bidon/spreadsheet/open_document.py | OpenDocumentWorksheet.parse_cell | def parse_cell(self, cell, coords, cell_mode=CellMode.cooked):
"""Parses a cell according to its cell.value_type."""
# pylint: disable=too-many-return-statements
if cell_mode == CellMode.cooked:
if cell.covered or cell.value_type is None or cell.value is None:
return None
vtype = cell.value_type
if vtype == 'string':
return cell.value
if vtype == 'float' or vtype == 'percentage' or vtype == 'currency':
return cell.value
if vtype == 'boolean':
return cell.value
if vtype == 'date':
date_tuple = tuple([int(i) if i is not None else 0 \
for i in _DATE_REGEX.match(cell.value).groups()])
return self.tuple_to_datetime(date_tuple)
if vtype == 'time':
hour, minute, second = _TIME_REGEX.match(cell.value).groups()
# TODO: This kills off the microseconds
date_tuple = (0, 0, 0, int(hour), int(minute), round(float(second)))
return self.tuple_to_datetime(date_tuple)
raise ValueError("Unhandled cell type: {0}".format(vtype))
else:
return cell | python | def parse_cell(self, cell, coords, cell_mode=CellMode.cooked):
"""Parses a cell according to its cell.value_type."""
# pylint: disable=too-many-return-statements
if cell_mode == CellMode.cooked:
if cell.covered or cell.value_type is None or cell.value is None:
return None
vtype = cell.value_type
if vtype == 'string':
return cell.value
if vtype == 'float' or vtype == 'percentage' or vtype == 'currency':
return cell.value
if vtype == 'boolean':
return cell.value
if vtype == 'date':
date_tuple = tuple([int(i) if i is not None else 0 \
for i in _DATE_REGEX.match(cell.value).groups()])
return self.tuple_to_datetime(date_tuple)
if vtype == 'time':
hour, minute, second = _TIME_REGEX.match(cell.value).groups()
# TODO: This kills off the microseconds
date_tuple = (0, 0, 0, int(hour), int(minute), round(float(second)))
return self.tuple_to_datetime(date_tuple)
raise ValueError("Unhandled cell type: {0}".format(vtype))
else:
return cell | [
"def",
"parse_cell",
"(",
"self",
",",
"cell",
",",
"coords",
",",
"cell_mode",
"=",
"CellMode",
".",
"cooked",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"cell_mode",
"==",
"CellMode",
".",
"cooked",
":",
"if",
"cell",
".",
"covered",
"or",
"cell",
".",
"value_type",
"is",
"None",
"or",
"cell",
".",
"value",
"is",
"None",
":",
"return",
"None",
"vtype",
"=",
"cell",
".",
"value_type",
"if",
"vtype",
"==",
"'string'",
":",
"return",
"cell",
".",
"value",
"if",
"vtype",
"==",
"'float'",
"or",
"vtype",
"==",
"'percentage'",
"or",
"vtype",
"==",
"'currency'",
":",
"return",
"cell",
".",
"value",
"if",
"vtype",
"==",
"'boolean'",
":",
"return",
"cell",
".",
"value",
"if",
"vtype",
"==",
"'date'",
":",
"date_tuple",
"=",
"tuple",
"(",
"[",
"int",
"(",
"i",
")",
"if",
"i",
"is",
"not",
"None",
"else",
"0",
"for",
"i",
"in",
"_DATE_REGEX",
".",
"match",
"(",
"cell",
".",
"value",
")",
".",
"groups",
"(",
")",
"]",
")",
"return",
"self",
".",
"tuple_to_datetime",
"(",
"date_tuple",
")",
"if",
"vtype",
"==",
"'time'",
":",
"hour",
",",
"minute",
",",
"second",
"=",
"_TIME_REGEX",
".",
"match",
"(",
"cell",
".",
"value",
")",
".",
"groups",
"(",
")",
"# TODO: This kills off the microseconds",
"date_tuple",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"int",
"(",
"hour",
")",
",",
"int",
"(",
"minute",
")",
",",
"round",
"(",
"float",
"(",
"second",
")",
")",
")",
"return",
"self",
".",
"tuple_to_datetime",
"(",
"date_tuple",
")",
"raise",
"ValueError",
"(",
"\"Unhandled cell type: {0}\"",
".",
"format",
"(",
"vtype",
")",
")",
"else",
":",
"return",
"cell"
] | Parses a cell according to its cell.value_type. | [
"Parses",
"a",
"cell",
"according",
"to",
"its",
"cell",
".",
"value_type",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/open_document.py#L28-L59 |
249,241 | treycucco/bidon | bidon/spreadsheet/open_document.py | OpenDocumentWorksheet.get_row | def get_row(self, row_index):
"""Returns the row at row_index."""
if self._raw_rows is None:
self._raw_rows = list(self.raw_sheet.rows())
return self._raw_rows[row_index] | python | def get_row(self, row_index):
"""Returns the row at row_index."""
if self._raw_rows is None:
self._raw_rows = list(self.raw_sheet.rows())
return self._raw_rows[row_index] | [
"def",
"get_row",
"(",
"self",
",",
"row_index",
")",
":",
"if",
"self",
".",
"_raw_rows",
"is",
"None",
":",
"self",
".",
"_raw_rows",
"=",
"list",
"(",
"self",
".",
"raw_sheet",
".",
"rows",
"(",
")",
")",
"return",
"self",
".",
"_raw_rows",
"[",
"row_index",
"]"
] | Returns the row at row_index. | [
"Returns",
"the",
"row",
"at",
"row_index",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/open_document.py#L61-L65 |
249,242 | slarse/pdfebc-core | pdfebc_core/config_utils.py | create_config | def create_config(sections, section_contents):
"""Create a config file from the provided sections and key value pairs.
Args:
sections (List[str]): A list of section keys.
key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as
the list of sections. That is to say, if there are two sections, there should be two
dicts.
Returns:
configparser.ConfigParser: A ConfigParser.
Raises:
ValueError
"""
sections_length, section_contents_length = len(sections), len(section_contents)
if sections_length != section_contents_length:
raise ValueError("Mismatch between argument lengths.\n"
"len(sections) = {}\n"
"len(section_contents) = {}"
.format(sections_length, section_contents_length))
config = configparser.ConfigParser()
for section, section_content in zip(sections, section_contents):
config[section] = section_content
return config | python | def create_config(sections, section_contents):
"""Create a config file from the provided sections and key value pairs.
Args:
sections (List[str]): A list of section keys.
key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as
the list of sections. That is to say, if there are two sections, there should be two
dicts.
Returns:
configparser.ConfigParser: A ConfigParser.
Raises:
ValueError
"""
sections_length, section_contents_length = len(sections), len(section_contents)
if sections_length != section_contents_length:
raise ValueError("Mismatch between argument lengths.\n"
"len(sections) = {}\n"
"len(section_contents) = {}"
.format(sections_length, section_contents_length))
config = configparser.ConfigParser()
for section, section_content in zip(sections, section_contents):
config[section] = section_content
return config | [
"def",
"create_config",
"(",
"sections",
",",
"section_contents",
")",
":",
"sections_length",
",",
"section_contents_length",
"=",
"len",
"(",
"sections",
")",
",",
"len",
"(",
"section_contents",
")",
"if",
"sections_length",
"!=",
"section_contents_length",
":",
"raise",
"ValueError",
"(",
"\"Mismatch between argument lengths.\\n\"",
"\"len(sections) = {}\\n\"",
"\"len(section_contents) = {}\"",
".",
"format",
"(",
"sections_length",
",",
"section_contents_length",
")",
")",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"for",
"section",
",",
"section_content",
"in",
"zip",
"(",
"sections",
",",
"section_contents",
")",
":",
"config",
"[",
"section",
"]",
"=",
"section_content",
"return",
"config"
] | Create a config file from the provided sections and key value pairs.
Args:
sections (List[str]): A list of section keys.
key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as
the list of sections. That is to say, if there are two sections, there should be two
dicts.
Returns:
configparser.ConfigParser: A ConfigParser.
Raises:
ValueError | [
"Create",
"a",
"config",
"file",
"from",
"the",
"provided",
"sections",
"and",
"key",
"value",
"pairs",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L56-L78 |
249,243 | slarse/pdfebc-core | pdfebc_core/config_utils.py | write_config | def write_config(config, config_path=CONFIG_PATH):
"""Write the config to the output path.
Creates the necessary directories if they aren't there.
Args:
config (configparser.ConfigParser): A ConfigParser.
"""
if not os.path.exists(config_path):
os.makedirs(os.path.dirname(config_path))
with open(config_path, 'w', encoding='utf-8') as f:
config.write(f) | python | def write_config(config, config_path=CONFIG_PATH):
"""Write the config to the output path.
Creates the necessary directories if they aren't there.
Args:
config (configparser.ConfigParser): A ConfigParser.
"""
if not os.path.exists(config_path):
os.makedirs(os.path.dirname(config_path))
with open(config_path, 'w', encoding='utf-8') as f:
config.write(f) | [
"def",
"write_config",
"(",
"config",
",",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_path",
")",
")",
"with",
"open",
"(",
"config_path",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"config",
".",
"write",
"(",
"f",
")"
] | Write the config to the output path.
Creates the necessary directories if they aren't there.
Args:
config (configparser.ConfigParser): A ConfigParser. | [
"Write",
"the",
"config",
"to",
"the",
"output",
"path",
".",
"Creates",
"the",
"necessary",
"directories",
"if",
"they",
"aren",
"t",
"there",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L80-L90 |
249,244 | slarse/pdfebc-core | pdfebc_core/config_utils.py | read_config | def read_config(config_path=CONFIG_PATH):
"""Read the config information from the config file.
Args:
config_path (str): Relative path to the email config file.
Returns:
defaultdict: A defaultdict with the config information.
Raises:
IOError
"""
if not os.path.isfile(config_path):
raise IOError("No config file found at %s" % config_path)
config_parser = configparser.ConfigParser()
config_parser.read(config_path)
config = _config_parser_to_defaultdict(config_parser)
return config | python | def read_config(config_path=CONFIG_PATH):
"""Read the config information from the config file.
Args:
config_path (str): Relative path to the email config file.
Returns:
defaultdict: A defaultdict with the config information.
Raises:
IOError
"""
if not os.path.isfile(config_path):
raise IOError("No config file found at %s" % config_path)
config_parser = configparser.ConfigParser()
config_parser.read(config_path)
config = _config_parser_to_defaultdict(config_parser)
return config | [
"def",
"read_config",
"(",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"raise",
"IOError",
"(",
"\"No config file found at %s\"",
"%",
"config_path",
")",
"config_parser",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config_parser",
".",
"read",
"(",
"config_path",
")",
"config",
"=",
"_config_parser_to_defaultdict",
"(",
"config_parser",
")",
"return",
"config"
] | Read the config information from the config file.
Args:
config_path (str): Relative path to the email config file.
Returns:
defaultdict: A defaultdict with the config information.
Raises:
IOError | [
"Read",
"the",
"config",
"information",
"from",
"the",
"config",
"file",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L92-L107 |
249,245 | slarse/pdfebc-core | pdfebc_core/config_utils.py | check_config | def check_config(config):
"""Check that all sections of the config contain the keys that they should.
Args:
config (defaultdict): A defaultdict.
Raises:
ConfigurationError
"""
for section, expected_section_keys in SECTION_KEYS.items():
section_content = config.get(section)
if not section_content:
raise ConfigurationError("Config file badly formed! Section {} is missing."
.format(section))
elif not _section_is_healthy(section_content, expected_section_keys):
raise ConfigurationError("The {} section of the configuration file is badly formed!"
.format(section)) | python | def check_config(config):
"""Check that all sections of the config contain the keys that they should.
Args:
config (defaultdict): A defaultdict.
Raises:
ConfigurationError
"""
for section, expected_section_keys in SECTION_KEYS.items():
section_content = config.get(section)
if not section_content:
raise ConfigurationError("Config file badly formed! Section {} is missing."
.format(section))
elif not _section_is_healthy(section_content, expected_section_keys):
raise ConfigurationError("The {} section of the configuration file is badly formed!"
.format(section)) | [
"def",
"check_config",
"(",
"config",
")",
":",
"for",
"section",
",",
"expected_section_keys",
"in",
"SECTION_KEYS",
".",
"items",
"(",
")",
":",
"section_content",
"=",
"config",
".",
"get",
"(",
"section",
")",
"if",
"not",
"section_content",
":",
"raise",
"ConfigurationError",
"(",
"\"Config file badly formed! Section {} is missing.\"",
".",
"format",
"(",
"section",
")",
")",
"elif",
"not",
"_section_is_healthy",
"(",
"section_content",
",",
"expected_section_keys",
")",
":",
"raise",
"ConfigurationError",
"(",
"\"The {} section of the configuration file is badly formed!\"",
".",
"format",
"(",
"section",
")",
")"
] | Check that all sections of the config contain the keys that they should.
Args:
config (defaultdict): A defaultdict.
Raises:
ConfigurationError | [
"Check",
"that",
"all",
"sections",
"of",
"the",
"config",
"contain",
"the",
"keys",
"that",
"they",
"should",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L109-L124 |
249,246 | slarse/pdfebc-core | pdfebc_core/config_utils.py | run_config_diagnostics | def run_config_diagnostics(config_path=CONFIG_PATH):
"""Run diagnostics on the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing
sections and a dict that maps each section to the entries that have either missing or empty
options.
"""
config = read_config(config_path)
missing_sections = set()
malformed_entries = defaultdict(set)
for section, expected_section_keys in SECTION_KEYS.items():
section_content = config.get(section)
if not section_content:
missing_sections.add(section)
else:
for option in expected_section_keys:
option_value = section_content.get(option)
if not option_value:
malformed_entries[section].add(option)
return config_path, missing_sections, malformed_entries | python | def run_config_diagnostics(config_path=CONFIG_PATH):
"""Run diagnostics on the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing
sections and a dict that maps each section to the entries that have either missing or empty
options.
"""
config = read_config(config_path)
missing_sections = set()
malformed_entries = defaultdict(set)
for section, expected_section_keys in SECTION_KEYS.items():
section_content = config.get(section)
if not section_content:
missing_sections.add(section)
else:
for option in expected_section_keys:
option_value = section_content.get(option)
if not option_value:
malformed_entries[section].add(option)
return config_path, missing_sections, malformed_entries | [
"def",
"run_config_diagnostics",
"(",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"config",
"=",
"read_config",
"(",
"config_path",
")",
"missing_sections",
"=",
"set",
"(",
")",
"malformed_entries",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"section",
",",
"expected_section_keys",
"in",
"SECTION_KEYS",
".",
"items",
"(",
")",
":",
"section_content",
"=",
"config",
".",
"get",
"(",
"section",
")",
"if",
"not",
"section_content",
":",
"missing_sections",
".",
"add",
"(",
"section",
")",
"else",
":",
"for",
"option",
"in",
"expected_section_keys",
":",
"option_value",
"=",
"section_content",
".",
"get",
"(",
"option",
")",
"if",
"not",
"option_value",
":",
"malformed_entries",
"[",
"section",
"]",
".",
"add",
"(",
"option",
")",
"return",
"config_path",
",",
"missing_sections",
",",
"malformed_entries"
] | Run diagnostics on the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing
sections and a dict that maps each section to the entries that have either missing or empty
options. | [
"Run",
"diagnostics",
"on",
"the",
"configuration",
"file",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L126-L148 |
249,247 | slarse/pdfebc-core | pdfebc_core/config_utils.py | get_attribute_from_config | def get_attribute_from_config(config, section, attribute):
"""Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError
"""
section = config.get(section)
if section:
option = section.get(attribute)
if option:
return option
raise ConfigurationError("Config file badly formed!\n"
"Failed to get attribute '{}' from section '{}'!"
.format(attribute, section)) | python | def get_attribute_from_config(config, section, attribute):
"""Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError
"""
section = config.get(section)
if section:
option = section.get(attribute)
if option:
return option
raise ConfigurationError("Config file badly formed!\n"
"Failed to get attribute '{}' from section '{}'!"
.format(attribute, section)) | [
"def",
"get_attribute_from_config",
"(",
"config",
",",
"section",
",",
"attribute",
")",
":",
"section",
"=",
"config",
".",
"get",
"(",
"section",
")",
"if",
"section",
":",
"option",
"=",
"section",
".",
"get",
"(",
"attribute",
")",
"if",
"option",
":",
"return",
"option",
"raise",
"ConfigurationError",
"(",
"\"Config file badly formed!\\n\"",
"\"Failed to get attribute '{}' from section '{}'!\"",
".",
"format",
"(",
"attribute",
",",
"section",
")",
")"
] | Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError | [
"Try",
"to",
"parse",
"an",
"attribute",
"of",
"the",
"config",
"file",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L150-L169 |
249,248 | slarse/pdfebc-core | pdfebc_core/config_utils.py | valid_config_exists | def valid_config_exists(config_path=CONFIG_PATH):
"""Verify that a valid config file exists.
Args:
config_path (str): Path to the config file.
Returns:
boolean: True if there is a valid config file, false if not.
"""
if os.path.isfile(config_path):
try:
config = read_config(config_path)
check_config(config)
except (ConfigurationError, IOError):
return False
else:
return False
return True | python | def valid_config_exists(config_path=CONFIG_PATH):
"""Verify that a valid config file exists.
Args:
config_path (str): Path to the config file.
Returns:
boolean: True if there is a valid config file, false if not.
"""
if os.path.isfile(config_path):
try:
config = read_config(config_path)
check_config(config)
except (ConfigurationError, IOError):
return False
else:
return False
return True | [
"def",
"valid_config_exists",
"(",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"try",
":",
"config",
"=",
"read_config",
"(",
"config_path",
")",
"check_config",
"(",
"config",
")",
"except",
"(",
"ConfigurationError",
",",
"IOError",
")",
":",
"return",
"False",
"else",
":",
"return",
"False",
"return",
"True"
] | Verify that a valid config file exists.
Args:
config_path (str): Path to the config file.
Returns:
boolean: True if there is a valid config file, false if not. | [
"Verify",
"that",
"a",
"valid",
"config",
"file",
"exists",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L171-L188 |
249,249 | slarse/pdfebc-core | pdfebc_core/config_utils.py | config_to_string | def config_to_string(config):
"""Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
"""
output = []
for section, section_content in config.items():
output.append("[{}]".format(section))
for option, option_value in section_content.items():
output.append("{} = {}".format(option, option_value))
return "\n".join(output) | python | def config_to_string(config):
"""Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
"""
output = []
for section, section_content in config.items():
output.append("[{}]".format(section))
for option, option_value in section_content.items():
output.append("{} = {}".format(option, option_value))
return "\n".join(output) | [
"def",
"config_to_string",
"(",
"config",
")",
":",
"output",
"=",
"[",
"]",
"for",
"section",
",",
"section_content",
"in",
"config",
".",
"items",
"(",
")",
":",
"output",
".",
"append",
"(",
"\"[{}]\"",
".",
"format",
"(",
"section",
")",
")",
"for",
"option",
",",
"option_value",
"in",
"section_content",
".",
"items",
"(",
")",
":",
"output",
".",
"append",
"(",
"\"{} = {}\"",
".",
"format",
"(",
"option",
",",
"option_value",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"output",
")"
] | Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config. | [
"Nice",
"output",
"string",
"for",
"the",
"config",
"which",
"is",
"a",
"nested",
"defaultdict",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L190-L203 |
249,250 | slarse/pdfebc-core | pdfebc_core/config_utils.py | _config_parser_to_defaultdict | def _config_parser_to_defaultdict(config_parser):
"""Convert a ConfigParser to a defaultdict.
Args:
config_parser (ConfigParser): A ConfigParser.
"""
config = defaultdict(defaultdict)
for section, section_content in config_parser.items():
if section != 'DEFAULT':
for option, option_value in section_content.items():
config[section][option] = option_value
return config | python | def _config_parser_to_defaultdict(config_parser):
"""Convert a ConfigParser to a defaultdict.
Args:
config_parser (ConfigParser): A ConfigParser.
"""
config = defaultdict(defaultdict)
for section, section_content in config_parser.items():
if section != 'DEFAULT':
for option, option_value in section_content.items():
config[section][option] = option_value
return config | [
"def",
"_config_parser_to_defaultdict",
"(",
"config_parser",
")",
":",
"config",
"=",
"defaultdict",
"(",
"defaultdict",
")",
"for",
"section",
",",
"section_content",
"in",
"config_parser",
".",
"items",
"(",
")",
":",
"if",
"section",
"!=",
"'DEFAULT'",
":",
"for",
"option",
",",
"option_value",
"in",
"section_content",
".",
"items",
"(",
")",
":",
"config",
"[",
"section",
"]",
"[",
"option",
"]",
"=",
"option_value",
"return",
"config"
] | Convert a ConfigParser to a defaultdict.
Args:
config_parser (ConfigParser): A ConfigParser. | [
"Convert",
"a",
"ConfigParser",
"to",
"a",
"defaultdict",
"."
] | fc40857bc42365b7434714333e37d7a3487603a0 | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L205-L216 |
249,251 | cfobel/ipython-helpers | ipython_helpers/notebook.py | Session.start | def start(self, *args, **kwargs):
'''
Launch IPython notebook server in background process.
Arguments and keyword arguments are passed on to `Popen` call.
By default, notebook server is launched using current working directory
as the notebook directory.
'''
if 'stderr' in kwargs:
raise ValueError('`stderr` must not be specified, since it must be'
' monitored to determine which port the notebook '
'server is running on.')
args_ = ('%s' % sys.executable, '-m', 'IPython', 'notebook') + self.args
args_ = args_ + tuple(args)
self.process = Popen(args_, stderr=PIPE, **kwargs)
self._notebook_dir = os.getcwd()
# Determine which port the notebook is running on.
cre_address = re.compile(r'The \w+ Notebook is running at: '
r'(?P<address>https?://.*?:'
r'(?P<port>\d+)[^\r]*/)\r?$')
cre_notebook_dir = re.compile(r'Serving notebooks from local '
r'directory:\s+(?P<notebook_dir>[^\r]*)\r?$')
match = None
self.stderr_lines = []
while not self.process.poll() and match is None:
stderr_line = self.process.stderr.readline()
self.stderr_lines.append(stderr_line)
match = cre_address.search(stderr_line)
dir_match = cre_notebook_dir.search(stderr_line)
if dir_match:
self._notebook_dir = dir_match.group('notebook_dir')
if match:
# Notebook was started successfully.
self.address = match.group('address')
self.port = int(match.group('port'))
else:
raise IOError(''.join(self.stderr_lines)) | python | def start(self, *args, **kwargs):
'''
Launch IPython notebook server in background process.
Arguments and keyword arguments are passed on to `Popen` call.
By default, notebook server is launched using current working directory
as the notebook directory.
'''
if 'stderr' in kwargs:
raise ValueError('`stderr` must not be specified, since it must be'
' monitored to determine which port the notebook '
'server is running on.')
args_ = ('%s' % sys.executable, '-m', 'IPython', 'notebook') + self.args
args_ = args_ + tuple(args)
self.process = Popen(args_, stderr=PIPE, **kwargs)
self._notebook_dir = os.getcwd()
# Determine which port the notebook is running on.
cre_address = re.compile(r'The \w+ Notebook is running at: '
r'(?P<address>https?://.*?:'
r'(?P<port>\d+)[^\r]*/)\r?$')
cre_notebook_dir = re.compile(r'Serving notebooks from local '
r'directory:\s+(?P<notebook_dir>[^\r]*)\r?$')
match = None
self.stderr_lines = []
while not self.process.poll() and match is None:
stderr_line = self.process.stderr.readline()
self.stderr_lines.append(stderr_line)
match = cre_address.search(stderr_line)
dir_match = cre_notebook_dir.search(stderr_line)
if dir_match:
self._notebook_dir = dir_match.group('notebook_dir')
if match:
# Notebook was started successfully.
self.address = match.group('address')
self.port = int(match.group('port'))
else:
raise IOError(''.join(self.stderr_lines)) | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'stderr'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'`stderr` must not be specified, since it must be'",
"' monitored to determine which port the notebook '",
"'server is running on.'",
")",
"args_",
"=",
"(",
"'%s'",
"%",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'IPython'",
",",
"'notebook'",
")",
"+",
"self",
".",
"args",
"args_",
"=",
"args_",
"+",
"tuple",
"(",
"args",
")",
"self",
".",
"process",
"=",
"Popen",
"(",
"args_",
",",
"stderr",
"=",
"PIPE",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_notebook_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"# Determine which port the notebook is running on.",
"cre_address",
"=",
"re",
".",
"compile",
"(",
"r'The \\w+ Notebook is running at: '",
"r'(?P<address>https?://.*?:'",
"r'(?P<port>\\d+)[^\\r]*/)\\r?$'",
")",
"cre_notebook_dir",
"=",
"re",
".",
"compile",
"(",
"r'Serving notebooks from local '",
"r'directory:\\s+(?P<notebook_dir>[^\\r]*)\\r?$'",
")",
"match",
"=",
"None",
"self",
".",
"stderr_lines",
"=",
"[",
"]",
"while",
"not",
"self",
".",
"process",
".",
"poll",
"(",
")",
"and",
"match",
"is",
"None",
":",
"stderr_line",
"=",
"self",
".",
"process",
".",
"stderr",
".",
"readline",
"(",
")",
"self",
".",
"stderr_lines",
".",
"append",
"(",
"stderr_line",
")",
"match",
"=",
"cre_address",
".",
"search",
"(",
"stderr_line",
")",
"dir_match",
"=",
"cre_notebook_dir",
".",
"search",
"(",
"stderr_line",
")",
"if",
"dir_match",
":",
"self",
".",
"_notebook_dir",
"=",
"dir_match",
".",
"group",
"(",
"'notebook_dir'",
")",
"if",
"match",
":",
"# Notebook was started successfully.",
"self",
".",
"address",
"=",
"match",
".",
"group",
"(",
"'address'",
")",
"self",
".",
"port",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"'port'",
")",
")",
"else",
":",
"raise",
"IOError",
"(",
"''",
".",
"join",
"(",
"self",
".",
"stderr_lines",
")",
")"
] | Launch IPython notebook server in background process.
Arguments and keyword arguments are passed on to `Popen` call.
By default, notebook server is launched using current working directory
as the notebook directory. | [
"Launch",
"IPython",
"notebook",
"server",
"in",
"background",
"process",
"."
] | 8bc15ed68df96115b84202b5ca23a6ce048d5daf | https://github.com/cfobel/ipython-helpers/blob/8bc15ed68df96115b84202b5ca23a6ce048d5daf/ipython_helpers/notebook.py#L46-L86 |
249,252 | cfobel/ipython-helpers | ipython_helpers/notebook.py | Session.open | def open(self, filename=None):
'''
Open a browser tab with the notebook path specified relative to the
notebook directory.
If no filename is specified, open the root of the notebook server.
'''
if filename is None:
address = self.address + 'tree'
else:
notebook_path = self.resource_filename(filename)
if not notebook_path.isfile():
raise IOError('Notebook path not found: %s' % notebook_path)
else:
address = '%snotebooks/%s' % (self.address, filename)
webbrowser.open_new_tab(address) | python | def open(self, filename=None):
'''
Open a browser tab with the notebook path specified relative to the
notebook directory.
If no filename is specified, open the root of the notebook server.
'''
if filename is None:
address = self.address + 'tree'
else:
notebook_path = self.resource_filename(filename)
if not notebook_path.isfile():
raise IOError('Notebook path not found: %s' % notebook_path)
else:
address = '%snotebooks/%s' % (self.address, filename)
webbrowser.open_new_tab(address) | [
"def",
"open",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"address",
"=",
"self",
".",
"address",
"+",
"'tree'",
"else",
":",
"notebook_path",
"=",
"self",
".",
"resource_filename",
"(",
"filename",
")",
"if",
"not",
"notebook_path",
".",
"isfile",
"(",
")",
":",
"raise",
"IOError",
"(",
"'Notebook path not found: %s'",
"%",
"notebook_path",
")",
"else",
":",
"address",
"=",
"'%snotebooks/%s'",
"%",
"(",
"self",
".",
"address",
",",
"filename",
")",
"webbrowser",
".",
"open_new_tab",
"(",
"address",
")"
] | Open a browser tab with the notebook path specified relative to the
notebook directory.
If no filename is specified, open the root of the notebook server. | [
"Open",
"a",
"browser",
"tab",
"with",
"the",
"notebook",
"path",
"specified",
"relative",
"to",
"the",
"notebook",
"directory",
"."
] | 8bc15ed68df96115b84202b5ca23a6ce048d5daf | https://github.com/cfobel/ipython-helpers/blob/8bc15ed68df96115b84202b5ca23a6ce048d5daf/ipython_helpers/notebook.py#L115-L130 |
249,253 | cfobel/ipython-helpers | ipython_helpers/notebook.py | SessionManager.get_session | def get_session(self, notebook_dir=None, no_browser=True, **kwargs):
'''
Return handle to IPython session for specified notebook directory.
If an IPython notebook session has already been launched for the
notebook directory, reuse it. Otherwise, launch a new IPython notebook
session.
By default, notebook session is launched using current working
directory as the notebook directory.
Arguments
---------
- `notebook_dir`: Directory to start IPython notebook session in.
- `no_browser`: Do not launch new browser tab.
'''
if notebook_dir in self.sessions and self.sessions[notebook_dir].is_alive():
# Notebook process is already running for notebook directory,
session = self.sessions[notebook_dir]
if 'daemon' in kwargs:
# Override `daemon` setting of existing session.
session.daemon = kwargs['daemon']
if not no_browser:
session.open()
else:
# Notebook process is not running for notebook directory, so
# start new IPython notebook process.
# Use default `daemon` setting for manager if no specified.
daemon = kwargs.pop('daemon', self.daemon)
if no_browser:
kwargs['no_browser'] = None
if notebook_dir is not None:
kwargs['notebook_dir'] = notebook_dir
session = Session(daemon=daemon, **kwargs)
session.start()
self.sessions[str(session.notebook_dir)] = session
return session | python | def get_session(self, notebook_dir=None, no_browser=True, **kwargs):
'''
Return handle to IPython session for specified notebook directory.
If an IPython notebook session has already been launched for the
notebook directory, reuse it. Otherwise, launch a new IPython notebook
session.
By default, notebook session is launched using current working
directory as the notebook directory.
Arguments
---------
- `notebook_dir`: Directory to start IPython notebook session in.
- `no_browser`: Do not launch new browser tab.
'''
if notebook_dir in self.sessions and self.sessions[notebook_dir].is_alive():
# Notebook process is already running for notebook directory,
session = self.sessions[notebook_dir]
if 'daemon' in kwargs:
# Override `daemon` setting of existing session.
session.daemon = kwargs['daemon']
if not no_browser:
session.open()
else:
# Notebook process is not running for notebook directory, so
# start new IPython notebook process.
# Use default `daemon` setting for manager if no specified.
daemon = kwargs.pop('daemon', self.daemon)
if no_browser:
kwargs['no_browser'] = None
if notebook_dir is not None:
kwargs['notebook_dir'] = notebook_dir
session = Session(daemon=daemon, **kwargs)
session.start()
self.sessions[str(session.notebook_dir)] = session
return session | [
"def",
"get_session",
"(",
"self",
",",
"notebook_dir",
"=",
"None",
",",
"no_browser",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"notebook_dir",
"in",
"self",
".",
"sessions",
"and",
"self",
".",
"sessions",
"[",
"notebook_dir",
"]",
".",
"is_alive",
"(",
")",
":",
"# Notebook process is already running for notebook directory,",
"session",
"=",
"self",
".",
"sessions",
"[",
"notebook_dir",
"]",
"if",
"'daemon'",
"in",
"kwargs",
":",
"# Override `daemon` setting of existing session.",
"session",
".",
"daemon",
"=",
"kwargs",
"[",
"'daemon'",
"]",
"if",
"not",
"no_browser",
":",
"session",
".",
"open",
"(",
")",
"else",
":",
"# Notebook process is not running for notebook directory, so",
"# start new IPython notebook process.",
"# Use default `daemon` setting for manager if no specified.",
"daemon",
"=",
"kwargs",
".",
"pop",
"(",
"'daemon'",
",",
"self",
".",
"daemon",
")",
"if",
"no_browser",
":",
"kwargs",
"[",
"'no_browser'",
"]",
"=",
"None",
"if",
"notebook_dir",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'notebook_dir'",
"]",
"=",
"notebook_dir",
"session",
"=",
"Session",
"(",
"daemon",
"=",
"daemon",
",",
"*",
"*",
"kwargs",
")",
"session",
".",
"start",
"(",
")",
"self",
".",
"sessions",
"[",
"str",
"(",
"session",
".",
"notebook_dir",
")",
"]",
"=",
"session",
"return",
"session"
] | Return handle to IPython session for specified notebook directory.
If an IPython notebook session has already been launched for the
notebook directory, reuse it. Otherwise, launch a new IPython notebook
session.
By default, notebook session is launched using current working
directory as the notebook directory.
Arguments
---------
- `notebook_dir`: Directory to start IPython notebook session in.
- `no_browser`: Do not launch new browser tab. | [
"Return",
"handle",
"to",
"IPython",
"session",
"for",
"specified",
"notebook",
"directory",
"."
] | 8bc15ed68df96115b84202b5ca23a6ce048d5daf | https://github.com/cfobel/ipython-helpers/blob/8bc15ed68df96115b84202b5ca23a6ce048d5daf/ipython_helpers/notebook.py#L223-L261 |
249,254 | jtpaasch/simplygithub | simplygithub/internals/blobs.py | get_blob | def get_blob(profile, sha):
"""Fetch a blob.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
sha
The SHA of the blob to fetch.
Returns:
A dict with data about the blob.
"""
resource = "/blobs/" + sha
data = api.get_request(profile, resource)
return prepare(data) | python | def get_blob(profile, sha):
"""Fetch a blob.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
sha
The SHA of the blob to fetch.
Returns:
A dict with data about the blob.
"""
resource = "/blobs/" + sha
data = api.get_request(profile, resource)
return prepare(data) | [
"def",
"get_blob",
"(",
"profile",
",",
"sha",
")",
":",
"resource",
"=",
"\"/blobs/\"",
"+",
"sha",
"data",
"=",
"api",
".",
"get_request",
"(",
"profile",
",",
"resource",
")",
"return",
"prepare",
"(",
"data",
")"
] | Fetch a blob.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
sha
The SHA of the blob to fetch.
Returns:
A dict with data about the blob. | [
"Fetch",
"a",
"blob",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/blobs.py#L16-L35 |
249,255 | jtpaasch/simplygithub | simplygithub/internals/blobs.py | create_blob | def create_blob(profile, content):
"""Create a blob.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
content
The (UTF-8 encoded) content to create in the blob.
Returns:
A dict with data about the newly created blob.
"""
resource = "/blobs"
payload = {"content": content}
data = api.post_request(profile, resource, payload)
return data | python | def create_blob(profile, content):
"""Create a blob.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
content
The (UTF-8 encoded) content to create in the blob.
Returns:
A dict with data about the newly created blob.
"""
resource = "/blobs"
payload = {"content": content}
data = api.post_request(profile, resource, payload)
return data | [
"def",
"create_blob",
"(",
"profile",
",",
"content",
")",
":",
"resource",
"=",
"\"/blobs\"",
"payload",
"=",
"{",
"\"content\"",
":",
"content",
"}",
"data",
"=",
"api",
".",
"post_request",
"(",
"profile",
",",
"resource",
",",
"payload",
")",
"return",
"data"
] | Create a blob.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
content
The (UTF-8 encoded) content to create in the blob.
Returns:
A dict with data about the newly created blob. | [
"Create",
"a",
"blob",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/internals/blobs.py#L38-L58 |
249,256 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.copy | def copy(self):
"""
Copy constructor for Sequence objects.
"""
return Sequence(self.name, self.sequenceData, self.start, self.end,
self.strand, self.remaining, self.meta_data,
self.mutableString) | python | def copy(self):
"""
Copy constructor for Sequence objects.
"""
return Sequence(self.name, self.sequenceData, self.start, self.end,
self.strand, self.remaining, self.meta_data,
self.mutableString) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"Sequence",
"(",
"self",
".",
"name",
",",
"self",
".",
"sequenceData",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"strand",
",",
"self",
".",
"remaining",
",",
"self",
".",
"meta_data",
",",
"self",
".",
"mutableString",
")"
] | Copy constructor for Sequence objects. | [
"Copy",
"constructor",
"for",
"Sequence",
"objects",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L127-L133 |
249,257 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.effective_len | def effective_len(self):
"""
Get the length of the sequence if N's are disregarded.
"""
if self._effective_len is None:
self._effective_len = len([nuc for nuc in self.sequenceData
if nuc != "N" and nuc != "n"])
return self._effective_len | python | def effective_len(self):
"""
Get the length of the sequence if N's are disregarded.
"""
if self._effective_len is None:
self._effective_len = len([nuc for nuc in self.sequenceData
if nuc != "N" and nuc != "n"])
return self._effective_len | [
"def",
"effective_len",
"(",
"self",
")",
":",
"if",
"self",
".",
"_effective_len",
"is",
"None",
":",
"self",
".",
"_effective_len",
"=",
"len",
"(",
"[",
"nuc",
"for",
"nuc",
"in",
"self",
".",
"sequenceData",
"if",
"nuc",
"!=",
"\"N\"",
"and",
"nuc",
"!=",
"\"n\"",
"]",
")",
"return",
"self",
".",
"_effective_len"
] | Get the length of the sequence if N's are disregarded. | [
"Get",
"the",
"length",
"of",
"the",
"sequence",
"if",
"N",
"s",
"are",
"disregarded",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L174-L181 |
249,258 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.percentNuc | def percentNuc(self, nuc):
"""
return the percentage of the sequence which is equal to the passed nuc.
:param nuc: the nucleotide to compute percentage composition for. There
is no check to make sure this is a valid nucleotide.
:return: the percentage of the sequence that is <nuc>
"""
count = reduce(lambda x, y: x + 1 if y == nuc else x, self.sequenceData, 0)
return count / float(len(self.sequenceData)) | python | def percentNuc(self, nuc):
"""
return the percentage of the sequence which is equal to the passed nuc.
:param nuc: the nucleotide to compute percentage composition for. There
is no check to make sure this is a valid nucleotide.
:return: the percentage of the sequence that is <nuc>
"""
count = reduce(lambda x, y: x + 1 if y == nuc else x, self.sequenceData, 0)
return count / float(len(self.sequenceData)) | [
"def",
"percentNuc",
"(",
"self",
",",
"nuc",
")",
":",
"count",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"1",
"if",
"y",
"==",
"nuc",
"else",
"x",
",",
"self",
".",
"sequenceData",
",",
"0",
")",
"return",
"count",
"/",
"float",
"(",
"len",
"(",
"self",
".",
"sequenceData",
")",
")"
] | return the percentage of the sequence which is equal to the passed nuc.
:param nuc: the nucleotide to compute percentage composition for. There
is no check to make sure this is a valid nucleotide.
:return: the percentage of the sequence that is <nuc> | [
"return",
"the",
"percentage",
"of",
"the",
"sequence",
"which",
"is",
"equal",
"to",
"the",
"passed",
"nuc",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L292-L301 |
249,259 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.reverseComplement | def reverseComplement(self, isRNA=None):
"""
Reverse complement this sequence in-place.
:param isRNA: if True, treat this sequence as RNA. If False, treat it as
DNA. If None (default), inspect the sequence and make a
guess as to whether it is RNA or DNA.
"""
isRNA_l = self.isRNA() if isRNA is None else isRNA
tmp = ""
for n in self.sequenceData:
if isRNA_l:
tmp += RNA_COMPLEMENTS[n]
else:
tmp += DNA_COMPLEMENTS[n]
self.sequenceData = tmp[::-1] | python | def reverseComplement(self, isRNA=None):
"""
Reverse complement this sequence in-place.
:param isRNA: if True, treat this sequence as RNA. If False, treat it as
DNA. If None (default), inspect the sequence and make a
guess as to whether it is RNA or DNA.
"""
isRNA_l = self.isRNA() if isRNA is None else isRNA
tmp = ""
for n in self.sequenceData:
if isRNA_l:
tmp += RNA_COMPLEMENTS[n]
else:
tmp += DNA_COMPLEMENTS[n]
self.sequenceData = tmp[::-1] | [
"def",
"reverseComplement",
"(",
"self",
",",
"isRNA",
"=",
"None",
")",
":",
"isRNA_l",
"=",
"self",
".",
"isRNA",
"(",
")",
"if",
"isRNA",
"is",
"None",
"else",
"isRNA",
"tmp",
"=",
"\"\"",
"for",
"n",
"in",
"self",
".",
"sequenceData",
":",
"if",
"isRNA_l",
":",
"tmp",
"+=",
"RNA_COMPLEMENTS",
"[",
"n",
"]",
"else",
":",
"tmp",
"+=",
"DNA_COMPLEMENTS",
"[",
"n",
"]",
"self",
".",
"sequenceData",
"=",
"tmp",
"[",
":",
":",
"-",
"1",
"]"
] | Reverse complement this sequence in-place.
:param isRNA: if True, treat this sequence as RNA. If False, treat it as
DNA. If None (default), inspect the sequence and make a
guess as to whether it is RNA or DNA. | [
"Reverse",
"complement",
"this",
"sequence",
"in",
"-",
"place",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L323-L339 |
249,260 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.maskRegion | def maskRegion(self, region):
"""
Replace nucleotides in this sequence in the regions given by Ns
:param region: any object with .start and .end attributes. Co-ords are
zero based and inclusive of both end points. Any other
attributes (e.g. chrom.) are ignored.
:raise SequenceError: if region specifies nucleotides not present in
this sequence
"""
if region.start < 0 or region.end < 0 or \
region.start > len(self) or region.end > len(self):
raise SequenceError("cannot mask region " + str(region.start) + " to " +
str(region.end) + " in " + self.name + ". " +
"Region specifies nucleotides not present in " +
"this read. Valid range would have been 0 -- " +
str(len(self)))
if self.mutableString:
for i in range(region.start, region.end + 1):
self.sequenceData[i] = 'N'
else:
self.sequenceData = "".join([self.sequenceData[:region.start],
("N" * (region.end - region.start + 1)),
self.sequenceData[region.end + 1:]]) | python | def maskRegion(self, region):
"""
Replace nucleotides in this sequence in the regions given by Ns
:param region: any object with .start and .end attributes. Co-ords are
zero based and inclusive of both end points. Any other
attributes (e.g. chrom.) are ignored.
:raise SequenceError: if region specifies nucleotides not present in
this sequence
"""
if region.start < 0 or region.end < 0 or \
region.start > len(self) or region.end > len(self):
raise SequenceError("cannot mask region " + str(region.start) + " to " +
str(region.end) + " in " + self.name + ". " +
"Region specifies nucleotides not present in " +
"this read. Valid range would have been 0 -- " +
str(len(self)))
if self.mutableString:
for i in range(region.start, region.end + 1):
self.sequenceData[i] = 'N'
else:
self.sequenceData = "".join([self.sequenceData[:region.start],
("N" * (region.end - region.start + 1)),
self.sequenceData[region.end + 1:]]) | [
"def",
"maskRegion",
"(",
"self",
",",
"region",
")",
":",
"if",
"region",
".",
"start",
"<",
"0",
"or",
"region",
".",
"end",
"<",
"0",
"or",
"region",
".",
"start",
">",
"len",
"(",
"self",
")",
"or",
"region",
".",
"end",
">",
"len",
"(",
"self",
")",
":",
"raise",
"SequenceError",
"(",
"\"cannot mask region \"",
"+",
"str",
"(",
"region",
".",
"start",
")",
"+",
"\" to \"",
"+",
"str",
"(",
"region",
".",
"end",
")",
"+",
"\" in \"",
"+",
"self",
".",
"name",
"+",
"\". \"",
"+",
"\"Region specifies nucleotides not present in \"",
"+",
"\"this read. Valid range would have been 0 -- \"",
"+",
"str",
"(",
"len",
"(",
"self",
")",
")",
")",
"if",
"self",
".",
"mutableString",
":",
"for",
"i",
"in",
"range",
"(",
"region",
".",
"start",
",",
"region",
".",
"end",
"+",
"1",
")",
":",
"self",
".",
"sequenceData",
"[",
"i",
"]",
"=",
"'N'",
"else",
":",
"self",
".",
"sequenceData",
"=",
"\"\"",
".",
"join",
"(",
"[",
"self",
".",
"sequenceData",
"[",
":",
"region",
".",
"start",
"]",
",",
"(",
"\"N\"",
"*",
"(",
"region",
".",
"end",
"-",
"region",
".",
"start",
"+",
"1",
")",
")",
",",
"self",
".",
"sequenceData",
"[",
"region",
".",
"end",
"+",
"1",
":",
"]",
"]",
")"
] | Replace nucleotides in this sequence in the regions given by Ns
:param region: any object with .start and .end attributes. Co-ords are
zero based and inclusive of both end points. Any other
attributes (e.g. chrom.) are ignored.
:raise SequenceError: if region specifies nucleotides not present in
this sequence | [
"Replace",
"nucleotides",
"in",
"this",
"sequence",
"in",
"the",
"regions",
"given",
"by",
"Ns"
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L384-L408 |
249,261 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.maskRegions | def maskRegions(self, regions, verbose=False):
"""
Mask the given regions in this sequence with Ns.
:param region: iterable of regions to mask. Each region can be any object
with .start and .end attributes. Co-ords are zero based
and inclusive of both end points. Any other attributes
(e.g. chrom.) are ignored.
:param verbose: print status messages to stderr if True
"""
if verbose:
pind = ProgressIndicator(totalToDo=len(regions),
messagePrefix="completed",
messageSuffix="of masking regions in " +
self.name)
for region in regions:
self.maskRegion(region)
if verbose:
pind.done += 1
pind.showProgress() | python | def maskRegions(self, regions, verbose=False):
"""
Mask the given regions in this sequence with Ns.
:param region: iterable of regions to mask. Each region can be any object
with .start and .end attributes. Co-ords are zero based
and inclusive of both end points. Any other attributes
(e.g. chrom.) are ignored.
:param verbose: print status messages to stderr if True
"""
if verbose:
pind = ProgressIndicator(totalToDo=len(regions),
messagePrefix="completed",
messageSuffix="of masking regions in " +
self.name)
for region in regions:
self.maskRegion(region)
if verbose:
pind.done += 1
pind.showProgress() | [
"def",
"maskRegions",
"(",
"self",
",",
"regions",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"pind",
"=",
"ProgressIndicator",
"(",
"totalToDo",
"=",
"len",
"(",
"regions",
")",
",",
"messagePrefix",
"=",
"\"completed\"",
",",
"messageSuffix",
"=",
"\"of masking regions in \"",
"+",
"self",
".",
"name",
")",
"for",
"region",
"in",
"regions",
":",
"self",
".",
"maskRegion",
"(",
"region",
")",
"if",
"verbose",
":",
"pind",
".",
"done",
"+=",
"1",
"pind",
".",
"showProgress",
"(",
")"
] | Mask the given regions in this sequence with Ns.
:param region: iterable of regions to mask. Each region can be any object
with .start and .end attributes. Co-ords are zero based
and inclusive of both end points. Any other attributes
(e.g. chrom.) are ignored.
:param verbose: print status messages to stderr if True | [
"Mask",
"the",
"given",
"regions",
"in",
"this",
"sequence",
"with",
"Ns",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L410-L429 |
249,262 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.split | def split(self, point=None):
"""
Split this sequence into two halves and return them. The original
sequence remains unmodified.
:param point: defines the split point, if None then the centre is used
:return: two Sequence objects -- one for each side
"""
if point is None:
point = len(self) / 2
r1 = Sequence(self.name + ".1", self.sequenceData[:point])
r2 = Sequence(self.name + ".2", self.sequenceData[point:])
return r1, r2 | python | def split(self, point=None):
"""
Split this sequence into two halves and return them. The original
sequence remains unmodified.
:param point: defines the split point, if None then the centre is used
:return: two Sequence objects -- one for each side
"""
if point is None:
point = len(self) / 2
r1 = Sequence(self.name + ".1", self.sequenceData[:point])
r2 = Sequence(self.name + ".2", self.sequenceData[point:])
return r1, r2 | [
"def",
"split",
"(",
"self",
",",
"point",
"=",
"None",
")",
":",
"if",
"point",
"is",
"None",
":",
"point",
"=",
"len",
"(",
"self",
")",
"/",
"2",
"r1",
"=",
"Sequence",
"(",
"self",
".",
"name",
"+",
"\".1\"",
",",
"self",
".",
"sequenceData",
"[",
":",
"point",
"]",
")",
"r2",
"=",
"Sequence",
"(",
"self",
".",
"name",
"+",
"\".2\"",
",",
"self",
".",
"sequenceData",
"[",
"point",
":",
"]",
")",
"return",
"r1",
",",
"r2"
] | Split this sequence into two halves and return them. The original
sequence remains unmodified.
:param point: defines the split point, if None then the centre is used
:return: two Sequence objects -- one for each side | [
"Split",
"this",
"sequence",
"into",
"two",
"halves",
"and",
"return",
"them",
".",
"The",
"original",
"sequence",
"remains",
"unmodified",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L468-L482 |
249,263 | pjuren/pyokit | src/pyokit/datastruct/sequence.py | Sequence.maskMatch | def maskMatch(self, mask):
"""
Determine whether this sequence matches the given mask.
:param mask: string to match against. Ns in the mask are considered to
match anything in the sequence -- all other chars must
match exactly.
:return: True if the mask matches at all places, otherwise false
"""
if len(mask) > len(self.sequenceData):
return False
lim = len(mask)
for i in range(0, lim):
if mask[i] == "N" or mask[i] == "n":
continue
if mask[i] != self.sequenceData[i]:
return False
return True | python | def maskMatch(self, mask):
"""
Determine whether this sequence matches the given mask.
:param mask: string to match against. Ns in the mask are considered to
match anything in the sequence -- all other chars must
match exactly.
:return: True if the mask matches at all places, otherwise false
"""
if len(mask) > len(self.sequenceData):
return False
lim = len(mask)
for i in range(0, lim):
if mask[i] == "N" or mask[i] == "n":
continue
if mask[i] != self.sequenceData[i]:
return False
return True | [
"def",
"maskMatch",
"(",
"self",
",",
"mask",
")",
":",
"if",
"len",
"(",
"mask",
")",
">",
"len",
"(",
"self",
".",
"sequenceData",
")",
":",
"return",
"False",
"lim",
"=",
"len",
"(",
"mask",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"lim",
")",
":",
"if",
"mask",
"[",
"i",
"]",
"==",
"\"N\"",
"or",
"mask",
"[",
"i",
"]",
"==",
"\"n\"",
":",
"continue",
"if",
"mask",
"[",
"i",
"]",
"!=",
"self",
".",
"sequenceData",
"[",
"i",
"]",
":",
"return",
"False",
"return",
"True"
] | Determine whether this sequence matches the given mask.
:param mask: string to match against. Ns in the mask are considered to
match anything in the sequence -- all other chars must
match exactly.
:return: True if the mask matches at all places, otherwise false | [
"Determine",
"whether",
"this",
"sequence",
"matches",
"the",
"given",
"mask",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L548-L565 |
249,264 | nws-cip/zenconf | zenconf/merged_config.py | walk_recursive | def walk_recursive(f, data):
"""
Recursively apply a function to all dicts in a nested dictionary
:param f: Function to apply
:param data: Dictionary (possibly nested) to recursively apply
function to
:return:
"""
results = {}
if isinstance(data, list):
return [walk_recursive(f, d) for d in data]
elif isinstance(data, dict):
results = funcy.walk_keys(f, data)
for k, v in data.iteritems():
if isinstance(v, dict):
results[f(k)] = walk_recursive(f, v)
elif isinstance(v, list):
results[f(k)] = [walk_recursive(f, d) for d in v]
else:
return f(data)
return results | python | def walk_recursive(f, data):
"""
Recursively apply a function to all dicts in a nested dictionary
:param f: Function to apply
:param data: Dictionary (possibly nested) to recursively apply
function to
:return:
"""
results = {}
if isinstance(data, list):
return [walk_recursive(f, d) for d in data]
elif isinstance(data, dict):
results = funcy.walk_keys(f, data)
for k, v in data.iteritems():
if isinstance(v, dict):
results[f(k)] = walk_recursive(f, v)
elif isinstance(v, list):
results[f(k)] = [walk_recursive(f, d) for d in v]
else:
return f(data)
return results | [
"def",
"walk_recursive",
"(",
"f",
",",
"data",
")",
":",
"results",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"[",
"walk_recursive",
"(",
"f",
",",
"d",
")",
"for",
"d",
"in",
"data",
"]",
"elif",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"results",
"=",
"funcy",
".",
"walk_keys",
"(",
"f",
",",
"data",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"results",
"[",
"f",
"(",
"k",
")",
"]",
"=",
"walk_recursive",
"(",
"f",
",",
"v",
")",
"elif",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"results",
"[",
"f",
"(",
"k",
")",
"]",
"=",
"[",
"walk_recursive",
"(",
"f",
",",
"d",
")",
"for",
"d",
"in",
"v",
"]",
"else",
":",
"return",
"f",
"(",
"data",
")",
"return",
"results"
] | Recursively apply a function to all dicts in a nested dictionary
:param f: Function to apply
:param data: Dictionary (possibly nested) to recursively apply
function to
:return: | [
"Recursively",
"apply",
"a",
"function",
"to",
"all",
"dicts",
"in",
"a",
"nested",
"dictionary"
] | fc96706468c0741fb1b54b2eeb9f9225737e3e36 | https://github.com/nws-cip/zenconf/blob/fc96706468c0741fb1b54b2eeb9f9225737e3e36/zenconf/merged_config.py#L47-L70 |
249,265 | nws-cip/zenconf | zenconf/merged_config.py | MergedConfig.add | def add(self, config, strip_app_name=False, filter_by_app_name=False,
key_normalisation_func=default_key_normalisation_func):
"""
Add a dict of config data. Values from later dicts will take precedence
over those added earlier, so the order data is added matters.
Note: Double underscores can be used to indicate dict key name
boundaries. i.e. if we have a dict like:
{
'logging': {
'level': INFO
...
}
}
we could pass an environment variable LOGGING__LEVEL=DEBUG to override
the log level.
Note: Key names will be normalised by recursively applying the
key_normalisation_func function. By default this will:
1) Convert keys to lowercase
2) Replace hyphens with underscores
3) Strip leading underscores
This allows key names from different sources (e.g. CLI args, env vars,
etc.) to be able to override each other.
:param config dict: config data
:param strip_app_name boolean: If True, the configured app_name will
stripped from the start of top-level input keys if present.
:param filter_by_app_name boolean: If True, keys that don't begin with
the app name will be discarded.
:return:
"""
config = walk_recursive(key_normalisation_func, OrderedDict(config))
if filter_by_app_name:
config = funcy.compact(funcy.select_keys(
lambda k: k.startswith(self._app_name), config))
if strip_app_name:
strip_app_name_regex = re.compile("^%s" % self._app_name)
config = funcy.walk_keys(
lambda k: re.sub(strip_app_name_regex, '', k), config)
self._sources.append(config)
return self | python | def add(self, config, strip_app_name=False, filter_by_app_name=False,
key_normalisation_func=default_key_normalisation_func):
"""
Add a dict of config data. Values from later dicts will take precedence
over those added earlier, so the order data is added matters.
Note: Double underscores can be used to indicate dict key name
boundaries. i.e. if we have a dict like:
{
'logging': {
'level': INFO
...
}
}
we could pass an environment variable LOGGING__LEVEL=DEBUG to override
the log level.
Note: Key names will be normalised by recursively applying the
key_normalisation_func function. By default this will:
1) Convert keys to lowercase
2) Replace hyphens with underscores
3) Strip leading underscores
This allows key names from different sources (e.g. CLI args, env vars,
etc.) to be able to override each other.
:param config dict: config data
:param strip_app_name boolean: If True, the configured app_name will
stripped from the start of top-level input keys if present.
:param filter_by_app_name boolean: If True, keys that don't begin with
the app name will be discarded.
:return:
"""
config = walk_recursive(key_normalisation_func, OrderedDict(config))
if filter_by_app_name:
config = funcy.compact(funcy.select_keys(
lambda k: k.startswith(self._app_name), config))
if strip_app_name:
strip_app_name_regex = re.compile("^%s" % self._app_name)
config = funcy.walk_keys(
lambda k: re.sub(strip_app_name_regex, '', k), config)
self._sources.append(config)
return self | [
"def",
"add",
"(",
"self",
",",
"config",
",",
"strip_app_name",
"=",
"False",
",",
"filter_by_app_name",
"=",
"False",
",",
"key_normalisation_func",
"=",
"default_key_normalisation_func",
")",
":",
"config",
"=",
"walk_recursive",
"(",
"key_normalisation_func",
",",
"OrderedDict",
"(",
"config",
")",
")",
"if",
"filter_by_app_name",
":",
"config",
"=",
"funcy",
".",
"compact",
"(",
"funcy",
".",
"select_keys",
"(",
"lambda",
"k",
":",
"k",
".",
"startswith",
"(",
"self",
".",
"_app_name",
")",
",",
"config",
")",
")",
"if",
"strip_app_name",
":",
"strip_app_name_regex",
"=",
"re",
".",
"compile",
"(",
"\"^%s\"",
"%",
"self",
".",
"_app_name",
")",
"config",
"=",
"funcy",
".",
"walk_keys",
"(",
"lambda",
"k",
":",
"re",
".",
"sub",
"(",
"strip_app_name_regex",
",",
"''",
",",
"k",
")",
",",
"config",
")",
"self",
".",
"_sources",
".",
"append",
"(",
"config",
")",
"return",
"self"
] | Add a dict of config data. Values from later dicts will take precedence
over those added earlier, so the order data is added matters.
Note: Double underscores can be used to indicate dict key name
boundaries. i.e. if we have a dict like:
{
'logging': {
'level': INFO
...
}
}
we could pass an environment variable LOGGING__LEVEL=DEBUG to override
the log level.
Note: Key names will be normalised by recursively applying the
key_normalisation_func function. By default this will:
1) Convert keys to lowercase
2) Replace hyphens with underscores
3) Strip leading underscores
This allows key names from different sources (e.g. CLI args, env vars,
etc.) to be able to override each other.
:param config dict: config data
:param strip_app_name boolean: If True, the configured app_name will
stripped from the start of top-level input keys if present.
:param filter_by_app_name boolean: If True, keys that don't begin with
the app name will be discarded.
:return: | [
"Add",
"a",
"dict",
"of",
"config",
"data",
".",
"Values",
"from",
"later",
"dicts",
"will",
"take",
"precedence",
"over",
"those",
"added",
"earlier",
"so",
"the",
"order",
"data",
"is",
"added",
"matters",
"."
] | fc96706468c0741fb1b54b2eeb9f9225737e3e36 | https://github.com/nws-cip/zenconf/blob/fc96706468c0741fb1b54b2eeb9f9225737e3e36/zenconf/merged_config.py#L160-L209 |
249,266 | flo-compbio/gopca-server | gpserver/config.py | GSConfig.set_param | def set_param(self, name, value):
"""Set a GO-PCA Server parameter.
Parameters
----------
name: str
The parameter name.
value: ?
The parameter value.
"""
if name not in self.param_names:
raise ValueError('No GO-PCA Server parameter named "%s"!' %(param))
self.__params[name] = value | python | def set_param(self, name, value):
"""Set a GO-PCA Server parameter.
Parameters
----------
name: str
The parameter name.
value: ?
The parameter value.
"""
if name not in self.param_names:
raise ValueError('No GO-PCA Server parameter named "%s"!' %(param))
self.__params[name] = value | [
"def",
"set_param",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"param_names",
":",
"raise",
"ValueError",
"(",
"'No GO-PCA Server parameter named \"%s\"!'",
"%",
"(",
"param",
")",
")",
"self",
".",
"__params",
"[",
"name",
"]",
"=",
"value"
] | Set a GO-PCA Server parameter.
Parameters
----------
name: str
The parameter name.
value: ?
The parameter value. | [
"Set",
"a",
"GO",
"-",
"PCA",
"Server",
"parameter",
"."
] | 4fe396b12c39c0f156ce3bc4538cade54c9d7ffe | https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/config.py#L147-L159 |
249,267 | flo-compbio/gopca-server | gpserver/config.py | GSConfig.set_params | def set_params(self, params):
"""Sets multiple GO-PCA Server parameters using a dictionary.
Parameters
----------
params: dict
Dictionary containing the parameter values.
Returns
-------
None
"""
for k,v in params.iteritems():
self.set_param(k,v) | python | def set_params(self, params):
"""Sets multiple GO-PCA Server parameters using a dictionary.
Parameters
----------
params: dict
Dictionary containing the parameter values.
Returns
-------
None
"""
for k,v in params.iteritems():
self.set_param(k,v) | [
"def",
"set_params",
"(",
"self",
",",
"params",
")",
":",
"for",
"k",
",",
"v",
"in",
"params",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"set_param",
"(",
"k",
",",
"v",
")"
] | Sets multiple GO-PCA Server parameters using a dictionary.
Parameters
----------
params: dict
Dictionary containing the parameter values.
Returns
-------
None | [
"Sets",
"multiple",
"GO",
"-",
"PCA",
"Server",
"parameters",
"using",
"a",
"dictionary",
"."
] | 4fe396b12c39c0f156ce3bc4538cade54c9d7ffe | https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/config.py#L161-L174 |
249,268 | flo-compbio/gopca-server | gpserver/config.py | GSConfig.reset_params | def reset_params(self):
"""Reset all parameters to their default values."""
self.__params = dict([p, None] for p in self.param_names)
self.set_params(self.param_defaults) | python | def reset_params(self):
"""Reset all parameters to their default values."""
self.__params = dict([p, None] for p in self.param_names)
self.set_params(self.param_defaults) | [
"def",
"reset_params",
"(",
"self",
")",
":",
"self",
".",
"__params",
"=",
"dict",
"(",
"[",
"p",
",",
"None",
"]",
"for",
"p",
"in",
"self",
".",
"param_names",
")",
"self",
".",
"set_params",
"(",
"self",
".",
"param_defaults",
")"
] | Reset all parameters to their default values. | [
"Reset",
"all",
"parameters",
"to",
"their",
"default",
"values",
"."
] | 4fe396b12c39c0f156ce3bc4538cade54c9d7ffe | https://github.com/flo-compbio/gopca-server/blob/4fe396b12c39c0f156ce3bc4538cade54c9d7ffe/gpserver/config.py#L176-L179 |
249,269 | rocktavious/waybill | waybill/cli.py | waybill.create | def create(cli, command, docker_id):
"""Creates waybill shims from a given command name and docker image"""
content = waybill_template.format(command=command,
docker_id=docker_id)
waybill_dir = cli.get_waybill_dir()
waybill_filename = os.path.join(waybill_dir, command + '.waybill')
with open(waybill_filename, 'wb') as filehandle:
filehandle.write(content)
cli.log.info('Created waybill {0}'.format(waybill_filename)) | python | def create(cli, command, docker_id):
"""Creates waybill shims from a given command name and docker image"""
content = waybill_template.format(command=command,
docker_id=docker_id)
waybill_dir = cli.get_waybill_dir()
waybill_filename = os.path.join(waybill_dir, command + '.waybill')
with open(waybill_filename, 'wb') as filehandle:
filehandle.write(content)
cli.log.info('Created waybill {0}'.format(waybill_filename)) | [
"def",
"create",
"(",
"cli",
",",
"command",
",",
"docker_id",
")",
":",
"content",
"=",
"waybill_template",
".",
"format",
"(",
"command",
"=",
"command",
",",
"docker_id",
"=",
"docker_id",
")",
"waybill_dir",
"=",
"cli",
".",
"get_waybill_dir",
"(",
")",
"waybill_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"waybill_dir",
",",
"command",
"+",
"'.waybill'",
")",
"with",
"open",
"(",
"waybill_filename",
",",
"'wb'",
")",
"as",
"filehandle",
":",
"filehandle",
".",
"write",
"(",
"content",
")",
"cli",
".",
"log",
".",
"info",
"(",
"'Created waybill {0}'",
".",
"format",
"(",
"waybill_filename",
")",
")"
] | Creates waybill shims from a given command name and docker image | [
"Creates",
"waybill",
"shims",
"from",
"a",
"given",
"command",
"name",
"and",
"docker",
"image"
] | 62630f3ab67d6f253f09fbcde6fa7386acf9c2e8 | https://github.com/rocktavious/waybill/blob/62630f3ab67d6f253f09fbcde6fa7386acf9c2e8/waybill/cli.py#L57-L65 |
249,270 | rocktavious/waybill | waybill/cli.py | waybill.load | def load(cli, yaml_filename):
"""Creates waybill shims from a given yaml file definiations"""
"""Expected Definition:
- name: NAME
docker_id: IMAGE
- name: NAME
docker_id: IMAGE
"""
with open(yaml_filename, 'rb') as filehandle:
for waybill in yaml.load(filehandle.read()):
cli.create(waybill.name,
waybill.docker_id) | python | def load(cli, yaml_filename):
"""Creates waybill shims from a given yaml file definiations"""
"""Expected Definition:
- name: NAME
docker_id: IMAGE
- name: NAME
docker_id: IMAGE
"""
with open(yaml_filename, 'rb') as filehandle:
for waybill in yaml.load(filehandle.read()):
cli.create(waybill.name,
waybill.docker_id) | [
"def",
"load",
"(",
"cli",
",",
"yaml_filename",
")",
":",
"\"\"\"Expected Definition:\n - name: NAME\n docker_id: IMAGE\n - name: NAME\n docker_id: IMAGE\n \"\"\"",
"with",
"open",
"(",
"yaml_filename",
",",
"'rb'",
")",
"as",
"filehandle",
":",
"for",
"waybill",
"in",
"yaml",
".",
"load",
"(",
"filehandle",
".",
"read",
"(",
")",
")",
":",
"cli",
".",
"create",
"(",
"waybill",
".",
"name",
",",
"waybill",
".",
"docker_id",
")"
] | Creates waybill shims from a given yaml file definiations | [
"Creates",
"waybill",
"shims",
"from",
"a",
"given",
"yaml",
"file",
"definiations"
] | 62630f3ab67d6f253f09fbcde6fa7386acf9c2e8 | https://github.com/rocktavious/waybill/blob/62630f3ab67d6f253f09fbcde6fa7386acf9c2e8/waybill/cli.py#L68-L79 |
249,271 | rocktavious/waybill | waybill/cli.py | waybill.shellinit | def shellinit(cli):
"""Implements the waybill shims in the active shell"""
output = 'eval echo "Initializing Waybills"'
if which('docker') is None:
raise ValueError("Unable to find program 'docker'. Please make sure it is installed and setup properly")
for waybill in cli.get_waybills():
output += ' && source {0}'.format(waybill)
return output | python | def shellinit(cli):
"""Implements the waybill shims in the active shell"""
output = 'eval echo "Initializing Waybills"'
if which('docker') is None:
raise ValueError("Unable to find program 'docker'. Please make sure it is installed and setup properly")
for waybill in cli.get_waybills():
output += ' && source {0}'.format(waybill)
return output | [
"def",
"shellinit",
"(",
"cli",
")",
":",
"output",
"=",
"'eval echo \"Initializing Waybills\"'",
"if",
"which",
"(",
"'docker'",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to find program 'docker'. Please make sure it is installed and setup properly\"",
")",
"for",
"waybill",
"in",
"cli",
".",
"get_waybills",
"(",
")",
":",
"output",
"+=",
"' && source {0}'",
".",
"format",
"(",
"waybill",
")",
"return",
"output"
] | Implements the waybill shims in the active shell | [
"Implements",
"the",
"waybill",
"shims",
"in",
"the",
"active",
"shell"
] | 62630f3ab67d6f253f09fbcde6fa7386acf9c2e8 | https://github.com/rocktavious/waybill/blob/62630f3ab67d6f253f09fbcde6fa7386acf9c2e8/waybill/cli.py#L94-L101 |
249,272 | henrysher/kotocore | kotocore/connection.py | ConnectionDetails.service_data | def service_data(self):
"""
Returns all introspected service data.
If the data has been previously accessed, a memoized version of the
data is returned.
:returns: A dict of introspected service data
:rtype: dict
"""
# Lean on the cache first.
if self._loaded_service_data is not None:
return self._loaded_service_data
# We don't have a cache. Build it.
self._loaded_service_data = self._introspect_service(
# We care about the ``botocore.session`` here, not the
# ``kotocore.session``.
self.session.core_session,
self.service_name
)
# Clear out the API version, just in case.
self._api_version = None
return self._loaded_service_data | python | def service_data(self):
"""
Returns all introspected service data.
If the data has been previously accessed, a memoized version of the
data is returned.
:returns: A dict of introspected service data
:rtype: dict
"""
# Lean on the cache first.
if self._loaded_service_data is not None:
return self._loaded_service_data
# We don't have a cache. Build it.
self._loaded_service_data = self._introspect_service(
# We care about the ``botocore.session`` here, not the
# ``kotocore.session``.
self.session.core_session,
self.service_name
)
# Clear out the API version, just in case.
self._api_version = None
return self._loaded_service_data | [
"def",
"service_data",
"(",
"self",
")",
":",
"# Lean on the cache first.",
"if",
"self",
".",
"_loaded_service_data",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_loaded_service_data",
"# We don't have a cache. Build it.",
"self",
".",
"_loaded_service_data",
"=",
"self",
".",
"_introspect_service",
"(",
"# We care about the ``botocore.session`` here, not the",
"# ``kotocore.session``.",
"self",
".",
"session",
".",
"core_session",
",",
"self",
".",
"service_name",
")",
"# Clear out the API version, just in case.",
"self",
".",
"_api_version",
"=",
"None",
"return",
"self",
".",
"_loaded_service_data"
] | Returns all introspected service data.
If the data has been previously accessed, a memoized version of the
data is returned.
:returns: A dict of introspected service data
:rtype: dict | [
"Returns",
"all",
"introspected",
"service",
"data",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/connection.py#L42-L65 |
249,273 | henrysher/kotocore | kotocore/connection.py | ConnectionDetails.api_version | def api_version(self):
"""
Returns API version introspected from the service data.
If the data has been previously accessed, a memoized version of the
API version is returned.
:returns: The service's version
:rtype: string
"""
# Lean on the cache first.
if self._api_version is not None:
return self._api_version
# We don't have a cache. Build it.
self._api_version = self._introspect_api_version(
self.session.core_session,
self.service_name
)
return self._api_version | python | def api_version(self):
"""
Returns API version introspected from the service data.
If the data has been previously accessed, a memoized version of the
API version is returned.
:returns: The service's version
:rtype: string
"""
# Lean on the cache first.
if self._api_version is not None:
return self._api_version
# We don't have a cache. Build it.
self._api_version = self._introspect_api_version(
self.session.core_session,
self.service_name
)
return self._api_version | [
"def",
"api_version",
"(",
"self",
")",
":",
"# Lean on the cache first.",
"if",
"self",
".",
"_api_version",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_api_version",
"# We don't have a cache. Build it.",
"self",
".",
"_api_version",
"=",
"self",
".",
"_introspect_api_version",
"(",
"self",
".",
"session",
".",
"core_session",
",",
"self",
".",
"service_name",
")",
"return",
"self",
".",
"_api_version"
] | Returns API version introspected from the service data.
If the data has been previously accessed, a memoized version of the
API version is returned.
:returns: The service's version
:rtype: string | [
"Returns",
"API",
"version",
"introspected",
"from",
"the",
"service",
"data",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/connection.py#L68-L87 |
249,274 | henrysher/kotocore | kotocore/connection.py | ConnectionFactory.construct_for | def construct_for(self, service_name):
"""
Builds a new, specialized ``Connection`` subclass for a given service.
This will introspect a service, determine all the API calls it has &
constructs a brand new class with those methods on it.
:param service_name: The name of the service to construct a connection
for. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:returns: A new connection class for that service
"""
# Construct a new ``ConnectionDetails`` (or similar class) for storing
# the relevant details about the service & its operations.
details = self.details_class(service_name, self.session)
# Make sure the new class gets that ``ConnectionDetails`` instance as a
# ``cls._details`` attribute.
attrs = {
'_details': details,
}
# Determine what we should call it.
klass_name = self._build_class_name(service_name)
# Construct what the class ought to have on it.
attrs.update(self._build_methods(details))
# Create the class.
return type(
klass_name,
(self.base_connection,),
attrs
) | python | def construct_for(self, service_name):
"""
Builds a new, specialized ``Connection`` subclass for a given service.
This will introspect a service, determine all the API calls it has &
constructs a brand new class with those methods on it.
:param service_name: The name of the service to construct a connection
for. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:returns: A new connection class for that service
"""
# Construct a new ``ConnectionDetails`` (or similar class) for storing
# the relevant details about the service & its operations.
details = self.details_class(service_name, self.session)
# Make sure the new class gets that ``ConnectionDetails`` instance as a
# ``cls._details`` attribute.
attrs = {
'_details': details,
}
# Determine what we should call it.
klass_name = self._build_class_name(service_name)
# Construct what the class ought to have on it.
attrs.update(self._build_methods(details))
# Create the class.
return type(
klass_name,
(self.base_connection,),
attrs
) | [
"def",
"construct_for",
"(",
"self",
",",
"service_name",
")",
":",
"# Construct a new ``ConnectionDetails`` (or similar class) for storing",
"# the relevant details about the service & its operations.",
"details",
"=",
"self",
".",
"details_class",
"(",
"service_name",
",",
"self",
".",
"session",
")",
"# Make sure the new class gets that ``ConnectionDetails`` instance as a",
"# ``cls._details`` attribute.",
"attrs",
"=",
"{",
"'_details'",
":",
"details",
",",
"}",
"# Determine what we should call it.",
"klass_name",
"=",
"self",
".",
"_build_class_name",
"(",
"service_name",
")",
"# Construct what the class ought to have on it.",
"attrs",
".",
"update",
"(",
"self",
".",
"_build_methods",
"(",
"details",
")",
")",
"# Create the class.",
"return",
"type",
"(",
"klass_name",
",",
"(",
"self",
".",
"base_connection",
",",
")",
",",
"attrs",
")"
] | Builds a new, specialized ``Connection`` subclass for a given service.
This will introspect a service, determine all the API calls it has &
constructs a brand new class with those methods on it.
:param service_name: The name of the service to construct a connection
for. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:returns: A new connection class for that service | [
"Builds",
"a",
"new",
"specialized",
"Connection",
"subclass",
"for",
"a",
"given",
"service",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/connection.py#L258-L291 |
249,275 | sochotnicky/pytrailer | pytrailer.py | getMoviesFromJSON | def getMoviesFromJSON(jsonURL):
"""Main function for this library
Returns list of Movie classes from apple.com/trailers json URL
such as: http://trailers.apple.com/trailers/home/feeds/just_added.json
The Movie classes use lazy loading mechanisms so that data not
directly available from JSON are loaded on demand. Currently these
lazy loaded parts are:
* poster
* trailerLinks
* description
Be warned that accessing these fields can take long time due to
network access. Therefore do the loading in thread separate from
UI thread or your users will notice.
There are optional fields that may or may not be present in every
Movie instance. These include:
* actors (list)
* directors (list)
* rating (string)
* genre (string)
* studio (string)
* releasedate (sring)
Please take care when trying to access these fields as they may
not exist.
"""
response = urllib.request.urlopen(jsonURL)
jsonData = response.read().decode('utf-8')
objects = json.loads(jsonData)
# make it work for search urls
if jsonURL.find('quickfind') != -1:
objects = objects['results']
optionalInfo = ['actors','directors','rating','genre','studio','releasedate']
movies = []
for obj in objects:
movie = Movie()
movie.title = obj['title']
movie.baseURL = obj['location']
movie.posterURL = obj['poster']
# sometimes posters don't have http part
if movie.posterURL.find('http:') == -1:
movie.posterURL = "http://apple.com%s" % movie.posterURL
movie.trailers = obj['trailers']
for i in optionalInfo:
if i in obj:
setattr(movie, i, obj[i])
movies.append(movie)
return movies | python | def getMoviesFromJSON(jsonURL):
"""Main function for this library
Returns list of Movie classes from apple.com/trailers json URL
such as: http://trailers.apple.com/trailers/home/feeds/just_added.json
The Movie classes use lazy loading mechanisms so that data not
directly available from JSON are loaded on demand. Currently these
lazy loaded parts are:
* poster
* trailerLinks
* description
Be warned that accessing these fields can take long time due to
network access. Therefore do the loading in thread separate from
UI thread or your users will notice.
There are optional fields that may or may not be present in every
Movie instance. These include:
* actors (list)
* directors (list)
* rating (string)
* genre (string)
* studio (string)
* releasedate (sring)
Please take care when trying to access these fields as they may
not exist.
"""
response = urllib.request.urlopen(jsonURL)
jsonData = response.read().decode('utf-8')
objects = json.loads(jsonData)
# make it work for search urls
if jsonURL.find('quickfind') != -1:
objects = objects['results']
optionalInfo = ['actors','directors','rating','genre','studio','releasedate']
movies = []
for obj in objects:
movie = Movie()
movie.title = obj['title']
movie.baseURL = obj['location']
movie.posterURL = obj['poster']
# sometimes posters don't have http part
if movie.posterURL.find('http:') == -1:
movie.posterURL = "http://apple.com%s" % movie.posterURL
movie.trailers = obj['trailers']
for i in optionalInfo:
if i in obj:
setattr(movie, i, obj[i])
movies.append(movie)
return movies | [
"def",
"getMoviesFromJSON",
"(",
"jsonURL",
")",
":",
"response",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"jsonURL",
")",
"jsonData",
"=",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"objects",
"=",
"json",
".",
"loads",
"(",
"jsonData",
")",
"# make it work for search urls",
"if",
"jsonURL",
".",
"find",
"(",
"'quickfind'",
")",
"!=",
"-",
"1",
":",
"objects",
"=",
"objects",
"[",
"'results'",
"]",
"optionalInfo",
"=",
"[",
"'actors'",
",",
"'directors'",
",",
"'rating'",
",",
"'genre'",
",",
"'studio'",
",",
"'releasedate'",
"]",
"movies",
"=",
"[",
"]",
"for",
"obj",
"in",
"objects",
":",
"movie",
"=",
"Movie",
"(",
")",
"movie",
".",
"title",
"=",
"obj",
"[",
"'title'",
"]",
"movie",
".",
"baseURL",
"=",
"obj",
"[",
"'location'",
"]",
"movie",
".",
"posterURL",
"=",
"obj",
"[",
"'poster'",
"]",
"# sometimes posters don't have http part",
"if",
"movie",
".",
"posterURL",
".",
"find",
"(",
"'http:'",
")",
"==",
"-",
"1",
":",
"movie",
".",
"posterURL",
"=",
"\"http://apple.com%s\"",
"%",
"movie",
".",
"posterURL",
"movie",
".",
"trailers",
"=",
"obj",
"[",
"'trailers'",
"]",
"for",
"i",
"in",
"optionalInfo",
":",
"if",
"i",
"in",
"obj",
":",
"setattr",
"(",
"movie",
",",
"i",
",",
"obj",
"[",
"i",
"]",
")",
"movies",
".",
"append",
"(",
"movie",
")",
"return",
"movies"
] | Main function for this library
Returns list of Movie classes from apple.com/trailers json URL
such as: http://trailers.apple.com/trailers/home/feeds/just_added.json
The Movie classes use lazy loading mechanisms so that data not
directly available from JSON are loaded on demand. Currently these
lazy loaded parts are:
* poster
* trailerLinks
* description
Be warned that accessing these fields can take long time due to
network access. Therefore do the loading in thread separate from
UI thread or your users will notice.
There are optional fields that may or may not be present in every
Movie instance. These include:
* actors (list)
* directors (list)
* rating (string)
* genre (string)
* studio (string)
* releasedate (sring)
Please take care when trying to access these fields as they may
not exist. | [
"Main",
"function",
"for",
"this",
"library"
] | f5ebcb14a53c32b7545a334191745e208a3cc319 | https://github.com/sochotnicky/pytrailer/blob/f5ebcb14a53c32b7545a334191745e208a3cc319/pytrailer.py#L20-L72 |
249,276 | sochotnicky/pytrailer | pytrailer.py | Movie.get_description | def get_description(self):
"""Returns description text as provided by the studio"""
if self._description:
return self._description
try:
trailerURL= "http://trailers.apple.com%s" % self.baseURL
response = urllib.request.urlopen(trailerURL)
Reader = codecs.getreader("utf-8")
responseReader = Reader(response)
trailerHTML = responseReader.read()
description = re.search('<meta *name="Description" *content="(.*?)" *[/]*>'
,trailerHTML)
if description:
self._description = description.group(1)
else:
self._description = "None"
except:
self._description = "Error"
return self._description | python | def get_description(self):
"""Returns description text as provided by the studio"""
if self._description:
return self._description
try:
trailerURL= "http://trailers.apple.com%s" % self.baseURL
response = urllib.request.urlopen(trailerURL)
Reader = codecs.getreader("utf-8")
responseReader = Reader(response)
trailerHTML = responseReader.read()
description = re.search('<meta *name="Description" *content="(.*?)" *[/]*>'
,trailerHTML)
if description:
self._description = description.group(1)
else:
self._description = "None"
except:
self._description = "Error"
return self._description | [
"def",
"get_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"_description",
":",
"return",
"self",
".",
"_description",
"try",
":",
"trailerURL",
"=",
"\"http://trailers.apple.com%s\"",
"%",
"self",
".",
"baseURL",
"response",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"trailerURL",
")",
"Reader",
"=",
"codecs",
".",
"getreader",
"(",
"\"utf-8\"",
")",
"responseReader",
"=",
"Reader",
"(",
"response",
")",
"trailerHTML",
"=",
"responseReader",
".",
"read",
"(",
")",
"description",
"=",
"re",
".",
"search",
"(",
"'<meta *name=\"Description\" *content=\"(.*?)\" *[/]*>'",
",",
"trailerHTML",
")",
"if",
"description",
":",
"self",
".",
"_description",
"=",
"description",
".",
"group",
"(",
"1",
")",
"else",
":",
"self",
".",
"_description",
"=",
"\"None\"",
"except",
":",
"self",
".",
"_description",
"=",
"\"Error\"",
"return",
"self",
".",
"_description"
] | Returns description text as provided by the studio | [
"Returns",
"description",
"text",
"as",
"provided",
"by",
"the",
"studio"
] | f5ebcb14a53c32b7545a334191745e208a3cc319 | https://github.com/sochotnicky/pytrailer/blob/f5ebcb14a53c32b7545a334191745e208a3cc319/pytrailer.py#L130-L149 |
249,277 | eddiejessup/metropack | metropack/draw.py | _unwrap_one_layer | def _unwrap_one_layer(r, L, n):
"""For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points at a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap.
Returns
-------
rcu: float array, shape (:, 2).
The set of points. tiled at the periods at a distance `n` from the
origin.
"""
try:
L[0]
except (TypeError, IndexError):
L = np.ones([r.shape[1]]) * L
if n == 0:
return list(r)
rcu = []
for x, y in r:
for ix in range(-n, n + 1):
for iy in range(-n, n + 1):
if abs(ix) == n or abs(iy) == n:
rcu.append(np.array([x + ix * L[0], y + iy * L[1]]))
return rcu | python | def _unwrap_one_layer(r, L, n):
"""For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points at a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap.
Returns
-------
rcu: float array, shape (:, 2).
The set of points. tiled at the periods at a distance `n` from the
origin.
"""
try:
L[0]
except (TypeError, IndexError):
L = np.ones([r.shape[1]]) * L
if n == 0:
return list(r)
rcu = []
for x, y in r:
for ix in range(-n, n + 1):
for iy in range(-n, n + 1):
if abs(ix) == n or abs(iy) == n:
rcu.append(np.array([x + ix * L[0], y + iy * L[1]]))
return rcu | [
"def",
"_unwrap_one_layer",
"(",
"r",
",",
"L",
",",
"n",
")",
":",
"try",
":",
"L",
"[",
"0",
"]",
"except",
"(",
"TypeError",
",",
"IndexError",
")",
":",
"L",
"=",
"np",
".",
"ones",
"(",
"[",
"r",
".",
"shape",
"[",
"1",
"]",
"]",
")",
"*",
"L",
"if",
"n",
"==",
"0",
":",
"return",
"list",
"(",
"r",
")",
"rcu",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"r",
":",
"for",
"ix",
"in",
"range",
"(",
"-",
"n",
",",
"n",
"+",
"1",
")",
":",
"for",
"iy",
"in",
"range",
"(",
"-",
"n",
",",
"n",
"+",
"1",
")",
":",
"if",
"abs",
"(",
"ix",
")",
"==",
"n",
"or",
"abs",
"(",
"iy",
")",
"==",
"n",
":",
"rcu",
".",
"append",
"(",
"np",
".",
"array",
"(",
"[",
"x",
"+",
"ix",
"*",
"L",
"[",
"0",
"]",
",",
"y",
"+",
"iy",
"*",
"L",
"[",
"1",
"]",
"]",
")",
")",
"return",
"rcu"
] | For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points at a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap.
Returns
-------
rcu: float array, shape (:, 2).
The set of points. tiled at the periods at a distance `n` from the
origin. | [
"For",
"a",
"set",
"of",
"points",
"in",
"a",
"2",
"dimensional",
"periodic",
"system",
"extend",
"the",
"set",
"of",
"points",
"to",
"tile",
"the",
"points",
"at",
"a",
"given",
"period",
"."
] | 528b47d0f2f70f39e1490e41433f2da8c8b9d63c | https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/draw.py#L6-L37 |
249,278 | eddiejessup/metropack | metropack/draw.py | _unwrap_to_layer | def _unwrap_to_layer(r, L, n=1):
"""For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points up to to a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap up to.
Returns
-------
rcu: float array, shape (:, 2).
The set of points. tiled up to the periods at a distance `n` from the
origin.
"""
rcu = []
for i_n in range(n + 1):
rcu.extend(_unwrap_one_layer(r, L, i_n))
return rcu | python | def _unwrap_to_layer(r, L, n=1):
"""For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points up to to a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap up to.
Returns
-------
rcu: float array, shape (:, 2).
The set of points. tiled up to the periods at a distance `n` from the
origin.
"""
rcu = []
for i_n in range(n + 1):
rcu.extend(_unwrap_one_layer(r, L, i_n))
return rcu | [
"def",
"_unwrap_to_layer",
"(",
"r",
",",
"L",
",",
"n",
"=",
"1",
")",
":",
"rcu",
"=",
"[",
"]",
"for",
"i_n",
"in",
"range",
"(",
"n",
"+",
"1",
")",
":",
"rcu",
".",
"extend",
"(",
"_unwrap_one_layer",
"(",
"r",
",",
"L",
",",
"i_n",
")",
")",
"return",
"rcu"
] | For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points up to to a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap up to.
Returns
-------
rcu: float array, shape (:, 2).
The set of points. tiled up to the periods at a distance `n` from the
origin. | [
"For",
"a",
"set",
"of",
"points",
"in",
"a",
"2",
"dimensional",
"periodic",
"system",
"extend",
"the",
"set",
"of",
"points",
"to",
"tile",
"the",
"points",
"up",
"to",
"to",
"a",
"given",
"period",
"."
] | 528b47d0f2f70f39e1490e41433f2da8c8b9d63c | https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/draw.py#L40-L62 |
249,279 | eddiejessup/metropack | metropack/draw.py | draw_medium | def draw_medium(r, R, L, n=1, ax=None):
"""Draw circles representing circles in a two-dimensional periodic system.
Circles may be tiled up to a number of periods.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
R: float
Circle radius.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap up to.
ax: matplotlib axes instance or None
Axes to draw circles onto. If `None`, use default axes.
Returns
-------
None
"""
if ax is None:
ax = plt.gca()
for ru in _unwrap_to_layer(r, L, n):
c = plt.Circle(ru, radius=R, alpha=0.2)
ax.add_artist(c) | python | def draw_medium(r, R, L, n=1, ax=None):
"""Draw circles representing circles in a two-dimensional periodic system.
Circles may be tiled up to a number of periods.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
R: float
Circle radius.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap up to.
ax: matplotlib axes instance or None
Axes to draw circles onto. If `None`, use default axes.
Returns
-------
None
"""
if ax is None:
ax = plt.gca()
for ru in _unwrap_to_layer(r, L, n):
c = plt.Circle(ru, radius=R, alpha=0.2)
ax.add_artist(c) | [
"def",
"draw_medium",
"(",
"r",
",",
"R",
",",
"L",
",",
"n",
"=",
"1",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"for",
"ru",
"in",
"_unwrap_to_layer",
"(",
"r",
",",
"L",
",",
"n",
")",
":",
"c",
"=",
"plt",
".",
"Circle",
"(",
"ru",
",",
"radius",
"=",
"R",
",",
"alpha",
"=",
"0.2",
")",
"ax",
".",
"add_artist",
"(",
"c",
")"
] | Draw circles representing circles in a two-dimensional periodic system.
Circles may be tiled up to a number of periods.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
R: float
Circle radius.
L: float array, shape (2,)
System lengths.
n: integer.
Period to unwrap up to.
ax: matplotlib axes instance or None
Axes to draw circles onto. If `None`, use default axes.
Returns
-------
None | [
"Draw",
"circles",
"representing",
"circles",
"in",
"a",
"two",
"-",
"dimensional",
"periodic",
"system",
".",
"Circles",
"may",
"be",
"tiled",
"up",
"to",
"a",
"number",
"of",
"periods",
"."
] | 528b47d0f2f70f39e1490e41433f2da8c8b9d63c | https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/draw.py#L65-L90 |
249,280 | DoWhileGeek/authentise-services | authentise_services/model.py | Model.upload | def upload(self, # pylint: disable=too-many-arguments
path,
name=None,
resize=False,
rotation=False,
callback_url=None,
callback_method=None,
auto_align=False, ):
"""Create a new model resource in the warehouse and uploads the path contents to it"""
if name is None:
head, tail = ntpath.split(path)
name = tail or ntpath.basename(head)
url = "http://models.{}/model/".format(self.config.host)
payload = {"name": name,
"allowed_transformations": {"resize": resize,
"rotation": rotation, },
"auto-align": auto_align}
if callback_url and callback_method:
payload["callback"] = {"url": callback_url, "method": callback_method}
post_resp = requests.post(url, json=payload, cookies={"session": self.session})
if not post_resp.ok:
raise errors.ResourceError("payload to model service invalid")
self.name = name
with open(path, "rb") as model_file:
put_resp = requests.put(post_resp.headers["x-upload-location"],
data=model_file.read(),
headers={"Content-Type": "application/octet-stream"})
if not put_resp.ok:
raise errors.ResourceError("model upload failed")
self.location = post_resp.headers["Location"]
self._state = self._get_status() | python | def upload(self, # pylint: disable=too-many-arguments
path,
name=None,
resize=False,
rotation=False,
callback_url=None,
callback_method=None,
auto_align=False, ):
"""Create a new model resource in the warehouse and uploads the path contents to it"""
if name is None:
head, tail = ntpath.split(path)
name = tail or ntpath.basename(head)
url = "http://models.{}/model/".format(self.config.host)
payload = {"name": name,
"allowed_transformations": {"resize": resize,
"rotation": rotation, },
"auto-align": auto_align}
if callback_url and callback_method:
payload["callback"] = {"url": callback_url, "method": callback_method}
post_resp = requests.post(url, json=payload, cookies={"session": self.session})
if not post_resp.ok:
raise errors.ResourceError("payload to model service invalid")
self.name = name
with open(path, "rb") as model_file:
put_resp = requests.put(post_resp.headers["x-upload-location"],
data=model_file.read(),
headers={"Content-Type": "application/octet-stream"})
if not put_resp.ok:
raise errors.ResourceError("model upload failed")
self.location = post_resp.headers["Location"]
self._state = self._get_status() | [
"def",
"upload",
"(",
"self",
",",
"# pylint: disable=too-many-arguments",
"path",
",",
"name",
"=",
"None",
",",
"resize",
"=",
"False",
",",
"rotation",
"=",
"False",
",",
"callback_url",
"=",
"None",
",",
"callback_method",
"=",
"None",
",",
"auto_align",
"=",
"False",
",",
")",
":",
"if",
"name",
"is",
"None",
":",
"head",
",",
"tail",
"=",
"ntpath",
".",
"split",
"(",
"path",
")",
"name",
"=",
"tail",
"or",
"ntpath",
".",
"basename",
"(",
"head",
")",
"url",
"=",
"\"http://models.{}/model/\"",
".",
"format",
"(",
"self",
".",
"config",
".",
"host",
")",
"payload",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"allowed_transformations\"",
":",
"{",
"\"resize\"",
":",
"resize",
",",
"\"rotation\"",
":",
"rotation",
",",
"}",
",",
"\"auto-align\"",
":",
"auto_align",
"}",
"if",
"callback_url",
"and",
"callback_method",
":",
"payload",
"[",
"\"callback\"",
"]",
"=",
"{",
"\"url\"",
":",
"callback_url",
",",
"\"method\"",
":",
"callback_method",
"}",
"post_resp",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"json",
"=",
"payload",
",",
"cookies",
"=",
"{",
"\"session\"",
":",
"self",
".",
"session",
"}",
")",
"if",
"not",
"post_resp",
".",
"ok",
":",
"raise",
"errors",
".",
"ResourceError",
"(",
"\"payload to model service invalid\"",
")",
"self",
".",
"name",
"=",
"name",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"model_file",
":",
"put_resp",
"=",
"requests",
".",
"put",
"(",
"post_resp",
".",
"headers",
"[",
"\"x-upload-location\"",
"]",
",",
"data",
"=",
"model_file",
".",
"read",
"(",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/octet-stream\"",
"}",
")",
"if",
"not",
"put_resp",
".",
"ok",
":",
"raise",
"errors",
".",
"ResourceError",
"(",
"\"model upload failed\"",
")",
"self",
".",
"location",
"=",
"post_resp",
".",
"headers",
"[",
"\"Location\"",
"]",
"self",
".",
"_state",
"=",
"self",
".",
"_get_status",
"(",
")"
] | Create a new model resource in the warehouse and uploads the path contents to it | [
"Create",
"a",
"new",
"model",
"resource",
"in",
"the",
"warehouse",
"and",
"uploads",
"the",
"path",
"contents",
"to",
"it"
] | ee32bd7f7de15d3fb24c0a6374640d3a1ec8096d | https://github.com/DoWhileGeek/authentise-services/blob/ee32bd7f7de15d3fb24c0a6374640d3a1ec8096d/authentise_services/model.py#L34-L70 |
249,281 | DoWhileGeek/authentise-services | authentise_services/model.py | Model.download | def download(self, path):
"""downloads a model resource to the path"""
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
self._state = payload["status"]
if self._state != "processed":
raise errors.ResourceError("slice resource status is: {}".format(self._state))
else:
download_get_resp = requests.get(payload["content"])
with open(path, "wb") as model_file:
model_file.write(download_get_resp.content) | python | def download(self, path):
"""downloads a model resource to the path"""
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
self._state = payload["status"]
if self._state != "processed":
raise errors.ResourceError("slice resource status is: {}".format(self._state))
else:
download_get_resp = requests.get(payload["content"])
with open(path, "wb") as model_file:
model_file.write(download_get_resp.content) | [
"def",
"download",
"(",
"self",
",",
"path",
")",
":",
"service_get_resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"location",
",",
"cookies",
"=",
"{",
"\"session\"",
":",
"self",
".",
"session",
"}",
")",
"payload",
"=",
"service_get_resp",
".",
"json",
"(",
")",
"self",
".",
"_state",
"=",
"payload",
"[",
"\"status\"",
"]",
"if",
"self",
".",
"_state",
"!=",
"\"processed\"",
":",
"raise",
"errors",
".",
"ResourceError",
"(",
"\"slice resource status is: {}\"",
".",
"format",
"(",
"self",
".",
"_state",
")",
")",
"else",
":",
"download_get_resp",
"=",
"requests",
".",
"get",
"(",
"payload",
"[",
"\"content\"",
"]",
")",
"with",
"open",
"(",
"path",
",",
"\"wb\"",
")",
"as",
"model_file",
":",
"model_file",
".",
"write",
"(",
"download_get_resp",
".",
"content",
")"
] | downloads a model resource to the path | [
"downloads",
"a",
"model",
"resource",
"to",
"the",
"path"
] | ee32bd7f7de15d3fb24c0a6374640d3a1ec8096d | https://github.com/DoWhileGeek/authentise-services/blob/ee32bd7f7de15d3fb24c0a6374640d3a1ec8096d/authentise_services/model.py#L72-L83 |
249,282 | heikomuller/sco-datastore | scodata/modelrun.py | ModelRunState.to_dict | def to_dict(obj):
"""Generate a JSON serialization for the run state object.
Returns
-------
Json-like object
Json serialization of model run state object
"""
# Have text description of state in Json object (for readability)
json_obj = {'type' : repr(obj)}
# Add state-specific elementsTYPE_MODEL_RUN
if obj.is_failed:
json_obj['errors'] = obj.errors
elif obj.is_success:
json_obj['modelOutput'] = obj.model_output
return json_obj | python | def to_dict(obj):
"""Generate a JSON serialization for the run state object.
Returns
-------
Json-like object
Json serialization of model run state object
"""
# Have text description of state in Json object (for readability)
json_obj = {'type' : repr(obj)}
# Add state-specific elementsTYPE_MODEL_RUN
if obj.is_failed:
json_obj['errors'] = obj.errors
elif obj.is_success:
json_obj['modelOutput'] = obj.model_output
return json_obj | [
"def",
"to_dict",
"(",
"obj",
")",
":",
"# Have text description of state in Json object (for readability)",
"json_obj",
"=",
"{",
"'type'",
":",
"repr",
"(",
"obj",
")",
"}",
"# Add state-specific elementsTYPE_MODEL_RUN",
"if",
"obj",
".",
"is_failed",
":",
"json_obj",
"[",
"'errors'",
"]",
"=",
"obj",
".",
"errors",
"elif",
"obj",
".",
"is_success",
":",
"json_obj",
"[",
"'modelOutput'",
"]",
"=",
"obj",
".",
"model_output",
"return",
"json_obj"
] | Generate a JSON serialization for the run state object.
Returns
-------
Json-like object
Json serialization of model run state object | [
"Generate",
"a",
"JSON",
"serialization",
"for",
"the",
"run",
"state",
"object",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/modelrun.py#L131-L146 |
249,283 | heikomuller/sco-datastore | scodata/modelrun.py | DefaultModelRunManager.create_object | def create_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None):
"""Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
----------
name : string
User-provided name for the model run
experiment_id : string
Unique identifier of associated experiment object
model_id : string
Unique model identifier
argument_defs : list(attribute.AttributeDefinition)
Definition of valid arguments for the given model
arguments : list(dict('name':...,'value:...')), optional
List of attribute instances
properties : Dictionary, optional
Set of model run properties.
Returns
-------
PredictionHandle
Object handle for created model run
"""
# Create a new object identifier.
identifier = str(uuid.uuid4()).replace('-','')
# Directory for successful model run resource files. Directories are
# simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create the directory if it doesn't exists
if not os.access(directory, os.F_OK):
os.makedirs(directory)
# By default all model runs are in IDLE state at creation
state = ModelRunIdle()
# Create the initial set of properties.
run_properties = {
datastore.PROPERTY_NAME: name,
datastore.PROPERTY_STATE: str(state),
datastore.PROPERTY_MODEL: model_id
}
if not properties is None:
for prop in properties:
if not prop in run_properties:
run_properties[prop] = properties[prop]
# If argument list is not given then the initial set of arguments is
# empty. Here we do not validate the given arguments. Definitions of
# valid argument sets are maintained in the model registry and are not
# accessible by the model run manager at this point.
run_arguments = {}
if not arguments is None:
# Convert arguments to dictionary of Atrribute instances. Will
# raise an exception if values are of invalid type.
run_arguments = attribute.to_dict(arguments, argument_defs)
# Create the image group object and store it in the database before
# returning it.
obj = ModelRunHandle(
identifier,
run_properties,
directory,
state,
experiment_id,
model_id,
run_arguments
)
self.insert_object(obj)
return obj | python | def create_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None):
"""Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
----------
name : string
User-provided name for the model run
experiment_id : string
Unique identifier of associated experiment object
model_id : string
Unique model identifier
argument_defs : list(attribute.AttributeDefinition)
Definition of valid arguments for the given model
arguments : list(dict('name':...,'value:...')), optional
List of attribute instances
properties : Dictionary, optional
Set of model run properties.
Returns
-------
PredictionHandle
Object handle for created model run
"""
# Create a new object identifier.
identifier = str(uuid.uuid4()).replace('-','')
# Directory for successful model run resource files. Directories are
# simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create the directory if it doesn't exists
if not os.access(directory, os.F_OK):
os.makedirs(directory)
# By default all model runs are in IDLE state at creation
state = ModelRunIdle()
# Create the initial set of properties.
run_properties = {
datastore.PROPERTY_NAME: name,
datastore.PROPERTY_STATE: str(state),
datastore.PROPERTY_MODEL: model_id
}
if not properties is None:
for prop in properties:
if not prop in run_properties:
run_properties[prop] = properties[prop]
# If argument list is not given then the initial set of arguments is
# empty. Here we do not validate the given arguments. Definitions of
# valid argument sets are maintained in the model registry and are not
# accessible by the model run manager at this point.
run_arguments = {}
if not arguments is None:
# Convert arguments to dictionary of Atrribute instances. Will
# raise an exception if values are of invalid type.
run_arguments = attribute.to_dict(arguments, argument_defs)
# Create the image group object and store it in the database before
# returning it.
obj = ModelRunHandle(
identifier,
run_properties,
directory,
state,
experiment_id,
model_id,
run_arguments
)
self.insert_object(obj)
return obj | [
"def",
"create_object",
"(",
"self",
",",
"name",
",",
"experiment_id",
",",
"model_id",
",",
"argument_defs",
",",
"arguments",
"=",
"None",
",",
"properties",
"=",
"None",
")",
":",
"# Create a new object identifier.",
"identifier",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"# Directory for successful model run resource files. Directories are",
"# simply named by object identifier",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"identifier",
")",
"# Create the directory if it doesn't exists",
"if",
"not",
"os",
".",
"access",
"(",
"directory",
",",
"os",
".",
"F_OK",
")",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"# By default all model runs are in IDLE state at creation",
"state",
"=",
"ModelRunIdle",
"(",
")",
"# Create the initial set of properties.",
"run_properties",
"=",
"{",
"datastore",
".",
"PROPERTY_NAME",
":",
"name",
",",
"datastore",
".",
"PROPERTY_STATE",
":",
"str",
"(",
"state",
")",
",",
"datastore",
".",
"PROPERTY_MODEL",
":",
"model_id",
"}",
"if",
"not",
"properties",
"is",
"None",
":",
"for",
"prop",
"in",
"properties",
":",
"if",
"not",
"prop",
"in",
"run_properties",
":",
"run_properties",
"[",
"prop",
"]",
"=",
"properties",
"[",
"prop",
"]",
"# If argument list is not given then the initial set of arguments is",
"# empty. Here we do not validate the given arguments. Definitions of",
"# valid argument sets are maintained in the model registry and are not",
"# accessible by the model run manager at this point.",
"run_arguments",
"=",
"{",
"}",
"if",
"not",
"arguments",
"is",
"None",
":",
"# Convert arguments to dictionary of Atrribute instances. Will",
"# raise an exception if values are of invalid type.",
"run_arguments",
"=",
"attribute",
".",
"to_dict",
"(",
"arguments",
",",
"argument_defs",
")",
"# Create the image group object and store it in the database before",
"# returning it.",
"obj",
"=",
"ModelRunHandle",
"(",
"identifier",
",",
"run_properties",
",",
"directory",
",",
"state",
",",
"experiment_id",
",",
"model_id",
",",
"run_arguments",
")",
"self",
".",
"insert_object",
"(",
"obj",
")",
"return",
"obj"
] | Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
----------
name : string
User-provided name for the model run
experiment_id : string
Unique identifier of associated experiment object
model_id : string
Unique model identifier
argument_defs : list(attribute.AttributeDefinition)
Definition of valid arguments for the given model
arguments : list(dict('name':...,'value:...')), optional
List of attribute instances
properties : Dictionary, optional
Set of model run properties.
Returns
-------
PredictionHandle
Object handle for created model run | [
"Create",
"a",
"model",
"run",
"object",
"with",
"the",
"given",
"list",
"of",
"arguments",
".",
"The",
"initial",
"state",
"of",
"the",
"object",
"is",
"RUNNING",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/modelrun.py#L456-L522 |
249,284 | heikomuller/sco-datastore | scodata/modelrun.py | DefaultModelRunManager.from_dict | def from_dict(self, document):
"""Create model run object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
PredictionHandle
Handle for model run object
"""
# Get object identifier from Json document
identifier = str(document['_id'])
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create attachment descriptors
attachments = {}
for obj in document['attachments']:
attachment = Attachment.from_dict(obj)
attachments[attachment.identifier] = attachment
# Create model run handle.
return ModelRunHandle(
identifier,
document['properties'],
directory,
ModelRunState.from_dict(document['state']),
document['experiment'],
document['model'],
attribute.attributes_from_dict(document['arguments']),
attachments=attachments,
schedule=document['schedule'],
timestamp=datetime.datetime.strptime(
document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) | python | def from_dict(self, document):
"""Create model run object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
PredictionHandle
Handle for model run object
"""
# Get object identifier from Json document
identifier = str(document['_id'])
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create attachment descriptors
attachments = {}
for obj in document['attachments']:
attachment = Attachment.from_dict(obj)
attachments[attachment.identifier] = attachment
# Create model run handle.
return ModelRunHandle(
identifier,
document['properties'],
directory,
ModelRunState.from_dict(document['state']),
document['experiment'],
document['model'],
attribute.attributes_from_dict(document['arguments']),
attachments=attachments,
schedule=document['schedule'],
timestamp=datetime.datetime.strptime(
document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) | [
"def",
"from_dict",
"(",
"self",
",",
"document",
")",
":",
"# Get object identifier from Json document",
"identifier",
"=",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
"# Directories are simply named by object identifier",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"identifier",
")",
"# Create attachment descriptors",
"attachments",
"=",
"{",
"}",
"for",
"obj",
"in",
"document",
"[",
"'attachments'",
"]",
":",
"attachment",
"=",
"Attachment",
".",
"from_dict",
"(",
"obj",
")",
"attachments",
"[",
"attachment",
".",
"identifier",
"]",
"=",
"attachment",
"# Create model run handle.",
"return",
"ModelRunHandle",
"(",
"identifier",
",",
"document",
"[",
"'properties'",
"]",
",",
"directory",
",",
"ModelRunState",
".",
"from_dict",
"(",
"document",
"[",
"'state'",
"]",
")",
",",
"document",
"[",
"'experiment'",
"]",
",",
"document",
"[",
"'model'",
"]",
",",
"attribute",
".",
"attributes_from_dict",
"(",
"document",
"[",
"'arguments'",
"]",
")",
",",
"attachments",
"=",
"attachments",
",",
"schedule",
"=",
"document",
"[",
"'schedule'",
"]",
",",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"document",
"[",
"'timestamp'",
"]",
",",
"'%Y-%m-%dT%H:%M:%S.%f'",
")",
",",
"is_active",
"=",
"document",
"[",
"'active'",
"]",
")"
] | Create model run object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
PredictionHandle
Handle for model run object | [
"Create",
"model",
"run",
"object",
"from",
"JSON",
"document",
"retrieved",
"from",
"database",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/modelrun.py#L557-L594 |
249,285 | heikomuller/sco-datastore | scodata/modelrun.py | DefaultModelRunManager.get_data_file_attachment | def get_data_file_attachment(self, identifier, resource_id):
"""Get path to attached data file with given resource identifer. If no
data file with given id exists the result will be None.
Raise ValueError if an image archive with the given resource identifier
is attached to the model run instead of a data file.
Parameters
----------
identifier : string
Unique model run identifier
resource_id : string
Unique attachment identifier
Returns
-------
string, string
Path to attached data file on disk and attachments MIME type
"""
# Get model run to ensure that it exists. If not return None
model_run = self.get_object(identifier)
if model_run is None:
return None, None
# Ensure that attachment with given resource identifier exists.
if not resource_id in model_run.attachments:
return None, None
# Raise an exception if the attached resource is not a data file
attachment = model_run.attachments[resource_id]
filename = os.path.join(model_run.attachment_directory, resource_id)
return filename, attachment.mime_type | python | def get_data_file_attachment(self, identifier, resource_id):
"""Get path to attached data file with given resource identifer. If no
data file with given id exists the result will be None.
Raise ValueError if an image archive with the given resource identifier
is attached to the model run instead of a data file.
Parameters
----------
identifier : string
Unique model run identifier
resource_id : string
Unique attachment identifier
Returns
-------
string, string
Path to attached data file on disk and attachments MIME type
"""
# Get model run to ensure that it exists. If not return None
model_run = self.get_object(identifier)
if model_run is None:
return None, None
# Ensure that attachment with given resource identifier exists.
if not resource_id in model_run.attachments:
return None, None
# Raise an exception if the attached resource is not a data file
attachment = model_run.attachments[resource_id]
filename = os.path.join(model_run.attachment_directory, resource_id)
return filename, attachment.mime_type | [
"def",
"get_data_file_attachment",
"(",
"self",
",",
"identifier",
",",
"resource_id",
")",
":",
"# Get model run to ensure that it exists. If not return None",
"model_run",
"=",
"self",
".",
"get_object",
"(",
"identifier",
")",
"if",
"model_run",
"is",
"None",
":",
"return",
"None",
",",
"None",
"# Ensure that attachment with given resource identifier exists.",
"if",
"not",
"resource_id",
"in",
"model_run",
".",
"attachments",
":",
"return",
"None",
",",
"None",
"# Raise an exception if the attached resource is not a data file",
"attachment",
"=",
"model_run",
".",
"attachments",
"[",
"resource_id",
"]",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"model_run",
".",
"attachment_directory",
",",
"resource_id",
")",
"return",
"filename",
",",
"attachment",
".",
"mime_type"
] | Get path to attached data file with given resource identifer. If no
data file with given id exists the result will be None.
Raise ValueError if an image archive with the given resource identifier
is attached to the model run instead of a data file.
Parameters
----------
identifier : string
Unique model run identifier
resource_id : string
Unique attachment identifier
Returns
-------
string, string
Path to attached data file on disk and attachments MIME type | [
"Get",
"path",
"to",
"attached",
"data",
"file",
"with",
"given",
"resource",
"identifer",
".",
"If",
"no",
"data",
"file",
"with",
"given",
"id",
"exists",
"the",
"result",
"will",
"be",
"None",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/modelrun.py#L596-L625 |
249,286 | heikomuller/sco-datastore | scodata/modelrun.py | DefaultModelRunManager.to_dict | def to_dict(self, model_run):
"""Create a Json-like dictionary for a model run object. Extends the
basic object with run state, arguments, and optional prediction results
or error descriptions.
Parameters
----------
model_run : PredictionHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary.
"""
# Get the basic Json object from the super class
json_obj = super(DefaultModelRunManager, self).to_dict(model_run)
# Add run state
json_obj['state'] = ModelRunState.to_dict(model_run.state)
# Add run scheduling Timestamps
json_obj['schedule'] = model_run.schedule
# Add experiment information
json_obj['experiment'] = model_run.experiment_id
# Add model information
json_obj['model'] = model_run.model_id
# Transform dictionary of attributes into list of key-value pairs.
json_obj['arguments'] = attribute.attributes_to_dict(model_run.arguments)
# Include attachments
json_obj['attachments'] = [
attachment.to_dict()
for attachment in model_run.attachments.values()
]
return json_obj | python | def to_dict(self, model_run):
"""Create a Json-like dictionary for a model run object. Extends the
basic object with run state, arguments, and optional prediction results
or error descriptions.
Parameters
----------
model_run : PredictionHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary.
"""
# Get the basic Json object from the super class
json_obj = super(DefaultModelRunManager, self).to_dict(model_run)
# Add run state
json_obj['state'] = ModelRunState.to_dict(model_run.state)
# Add run scheduling Timestamps
json_obj['schedule'] = model_run.schedule
# Add experiment information
json_obj['experiment'] = model_run.experiment_id
# Add model information
json_obj['model'] = model_run.model_id
# Transform dictionary of attributes into list of key-value pairs.
json_obj['arguments'] = attribute.attributes_to_dict(model_run.arguments)
# Include attachments
json_obj['attachments'] = [
attachment.to_dict()
for attachment in model_run.attachments.values()
]
return json_obj | [
"def",
"to_dict",
"(",
"self",
",",
"model_run",
")",
":",
"# Get the basic Json object from the super class",
"json_obj",
"=",
"super",
"(",
"DefaultModelRunManager",
",",
"self",
")",
".",
"to_dict",
"(",
"model_run",
")",
"# Add run state",
"json_obj",
"[",
"'state'",
"]",
"=",
"ModelRunState",
".",
"to_dict",
"(",
"model_run",
".",
"state",
")",
"# Add run scheduling Timestamps",
"json_obj",
"[",
"'schedule'",
"]",
"=",
"model_run",
".",
"schedule",
"# Add experiment information",
"json_obj",
"[",
"'experiment'",
"]",
"=",
"model_run",
".",
"experiment_id",
"# Add model information",
"json_obj",
"[",
"'model'",
"]",
"=",
"model_run",
".",
"model_id",
"# Transform dictionary of attributes into list of key-value pairs.",
"json_obj",
"[",
"'arguments'",
"]",
"=",
"attribute",
".",
"attributes_to_dict",
"(",
"model_run",
".",
"arguments",
")",
"# Include attachments",
"json_obj",
"[",
"'attachments'",
"]",
"=",
"[",
"attachment",
".",
"to_dict",
"(",
")",
"for",
"attachment",
"in",
"model_run",
".",
"attachments",
".",
"values",
"(",
")",
"]",
"return",
"json_obj"
] | Create a Json-like dictionary for a model run object. Extends the
basic object with run state, arguments, and optional prediction results
or error descriptions.
Parameters
----------
model_run : PredictionHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary. | [
"Create",
"a",
"Json",
"-",
"like",
"dictionary",
"for",
"a",
"model",
"run",
"object",
".",
"Extends",
"the",
"basic",
"object",
"with",
"run",
"state",
"arguments",
"and",
"optional",
"prediction",
"results",
"or",
"error",
"descriptions",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/modelrun.py#L627-L658 |
249,287 | heikomuller/sco-datastore | scodata/modelrun.py | DefaultModelRunManager.update_state | def update_state(self, identifier, state):
"""Update state of identified model run.
Raises exception if state change results in invalid run life cycle.
Parameters
----------
identifier : string
Unique model run identifier
state : ModelRunState
Object representing new run state
Returns
-------
ModelRunHandle
Modified model run handle or None if no run with given identifier
exists
"""
# Get model run to ensure that it exists
model_run = self.get_object(identifier)
if model_run is None:
return None
# Set timestamp of state change. Raise exception if state change results
# in invalid life cycle
timestamp = str(datetime.datetime.utcnow().isoformat())
if state.is_idle:
raise ValueError('invalid state change: run cannot become idle')
elif state.is_running:
# Current state is required to be IDLE
if not model_run.state.is_idle:
raise ValueError('invalid state change: finished run cannot start again')
model_run.schedule[RUN_STARTED] = timestamp
elif state.is_failed:
# Current state is required to be RUNNING
if not (model_run.state.is_running or model_run.state.is_idle):
raise ValueError('invalid state change: cannot fail finished run')
model_run.schedule[RUN_FINISHED] = timestamp
elif state.is_success:
# Current state is required to be RUNNING
if not model_run.state.is_running:
raise ValueError('invalid state change: cannot finish inactive run')
model_run.schedule[RUN_FINISHED] = timestamp
# Update model run state and replace object in database
model_run.state = state
model_run.properties[datastore.PROPERTY_STATE] = str(state)
self.replace_object(model_run)
# Return modified model run
return model_run | python | def update_state(self, identifier, state):
"""Update state of identified model run.
Raises exception if state change results in invalid run life cycle.
Parameters
----------
identifier : string
Unique model run identifier
state : ModelRunState
Object representing new run state
Returns
-------
ModelRunHandle
Modified model run handle or None if no run with given identifier
exists
"""
# Get model run to ensure that it exists
model_run = self.get_object(identifier)
if model_run is None:
return None
# Set timestamp of state change. Raise exception if state change results
# in invalid life cycle
timestamp = str(datetime.datetime.utcnow().isoformat())
if state.is_idle:
raise ValueError('invalid state change: run cannot become idle')
elif state.is_running:
# Current state is required to be IDLE
if not model_run.state.is_idle:
raise ValueError('invalid state change: finished run cannot start again')
model_run.schedule[RUN_STARTED] = timestamp
elif state.is_failed:
# Current state is required to be RUNNING
if not (model_run.state.is_running or model_run.state.is_idle):
raise ValueError('invalid state change: cannot fail finished run')
model_run.schedule[RUN_FINISHED] = timestamp
elif state.is_success:
# Current state is required to be RUNNING
if not model_run.state.is_running:
raise ValueError('invalid state change: cannot finish inactive run')
model_run.schedule[RUN_FINISHED] = timestamp
# Update model run state and replace object in database
model_run.state = state
model_run.properties[datastore.PROPERTY_STATE] = str(state)
self.replace_object(model_run)
# Return modified model run
return model_run | [
"def",
"update_state",
"(",
"self",
",",
"identifier",
",",
"state",
")",
":",
"# Get model run to ensure that it exists",
"model_run",
"=",
"self",
".",
"get_object",
"(",
"identifier",
")",
"if",
"model_run",
"is",
"None",
":",
"return",
"None",
"# Set timestamp of state change. Raise exception if state change results",
"# in invalid life cycle",
"timestamp",
"=",
"str",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
")",
"if",
"state",
".",
"is_idle",
":",
"raise",
"ValueError",
"(",
"'invalid state change: run cannot become idle'",
")",
"elif",
"state",
".",
"is_running",
":",
"# Current state is required to be IDLE",
"if",
"not",
"model_run",
".",
"state",
".",
"is_idle",
":",
"raise",
"ValueError",
"(",
"'invalid state change: finished run cannot start again'",
")",
"model_run",
".",
"schedule",
"[",
"RUN_STARTED",
"]",
"=",
"timestamp",
"elif",
"state",
".",
"is_failed",
":",
"# Current state is required to be RUNNING",
"if",
"not",
"(",
"model_run",
".",
"state",
".",
"is_running",
"or",
"model_run",
".",
"state",
".",
"is_idle",
")",
":",
"raise",
"ValueError",
"(",
"'invalid state change: cannot fail finished run'",
")",
"model_run",
".",
"schedule",
"[",
"RUN_FINISHED",
"]",
"=",
"timestamp",
"elif",
"state",
".",
"is_success",
":",
"# Current state is required to be RUNNING",
"if",
"not",
"model_run",
".",
"state",
".",
"is_running",
":",
"raise",
"ValueError",
"(",
"'invalid state change: cannot finish inactive run'",
")",
"model_run",
".",
"schedule",
"[",
"RUN_FINISHED",
"]",
"=",
"timestamp",
"# Update model run state and replace object in database",
"model_run",
".",
"state",
"=",
"state",
"model_run",
".",
"properties",
"[",
"datastore",
".",
"PROPERTY_STATE",
"]",
"=",
"str",
"(",
"state",
")",
"self",
".",
"replace_object",
"(",
"model_run",
")",
"# Return modified model run",
"return",
"model_run"
] | Update state of identified model run.
Raises exception if state change results in invalid run life cycle.
Parameters
----------
identifier : string
Unique model run identifier
state : ModelRunState
Object representing new run state
Returns
-------
ModelRunHandle
Modified model run handle or None if no run with given identifier
exists | [
"Update",
"state",
"of",
"identified",
"model",
"run",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/modelrun.py#L660-L707 |
249,288 | OpenVolunteeringPlatform/django-ovp-projects | ovp_projects/views/project.py | ProjectResourceViewSet.partial_update | def partial_update(self, request, *args, **kwargs):
""" We do not include the mixin as we want only PATCH and no PUT """
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
if getattr(instance, '_prefetched_objects_cache', None): #pragma: no cover
instance = self.get_object()
serializer = self.get_serializer(instance)
return response.Response(serializer.data) | python | def partial_update(self, request, *args, **kwargs):
""" We do not include the mixin as we want only PATCH and no PUT """
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
if getattr(instance, '_prefetched_objects_cache', None): #pragma: no cover
instance = self.get_object()
serializer = self.get_serializer(instance)
return response.Response(serializer.data) | [
"def",
"partial_update",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"self",
".",
"get_object",
"(",
")",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
"instance",
",",
"data",
"=",
"request",
".",
"data",
",",
"partial",
"=",
"True",
",",
"context",
"=",
"self",
".",
"get_serializer_context",
"(",
")",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"serializer",
".",
"save",
"(",
")",
"if",
"getattr",
"(",
"instance",
",",
"'_prefetched_objects_cache'",
",",
"None",
")",
":",
"#pragma: no cover",
"instance",
"=",
"self",
".",
"get_object",
"(",
")",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
"instance",
")",
"return",
"response",
".",
"Response",
"(",
"serializer",
".",
"data",
")"
] | We do not include the mixin as we want only PATCH and no PUT | [
"We",
"do",
"not",
"include",
"the",
"mixin",
"as",
"we",
"want",
"only",
"PATCH",
"and",
"no",
"PUT"
] | 239e27027ca99c7b44ee4f30bf55d06439d49251 | https://github.com/OpenVolunteeringPlatform/django-ovp-projects/blob/239e27027ca99c7b44ee4f30bf55d06439d49251/ovp_projects/views/project.py#L46-L57 |
249,289 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/ssh.py | Connection.connect | def connect(self):
''' connect to the remote host '''
vvv("ESTABLISH CONNECTION FOR USER: %s" % self.runner.remote_user, host=self.host)
self.common_args = []
extra_args = C.ANSIBLE_SSH_ARGS
if extra_args is not None:
self.common_args += shlex.split(extra_args)
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"]
self.common_args += ["-o", "StrictHostKeyChecking=no"]
if self.port is not None:
self.common_args += ["-o", "Port=%d" % (self.port)]
if self.runner.private_key_file is not None:
self.common_args += ["-o", "IdentityFile="+os.path.expanduser(self.runner.private_key_file)]
if self.runner.remote_pass:
self.common_args += ["-o", "GSSAPIAuthentication=no",
"-o", "PubkeyAuthentication=no"]
else:
self.common_args += ["-o", "KbdInteractiveAuthentication=no",
"-o", "PasswordAuthentication=no"]
self.common_args += ["-o", "User="+self.runner.remote_user]
return self | python | def connect(self):
''' connect to the remote host '''
vvv("ESTABLISH CONNECTION FOR USER: %s" % self.runner.remote_user, host=self.host)
self.common_args = []
extra_args = C.ANSIBLE_SSH_ARGS
if extra_args is not None:
self.common_args += shlex.split(extra_args)
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"]
self.common_args += ["-o", "StrictHostKeyChecking=no"]
if self.port is not None:
self.common_args += ["-o", "Port=%d" % (self.port)]
if self.runner.private_key_file is not None:
self.common_args += ["-o", "IdentityFile="+os.path.expanduser(self.runner.private_key_file)]
if self.runner.remote_pass:
self.common_args += ["-o", "GSSAPIAuthentication=no",
"-o", "PubkeyAuthentication=no"]
else:
self.common_args += ["-o", "KbdInteractiveAuthentication=no",
"-o", "PasswordAuthentication=no"]
self.common_args += ["-o", "User="+self.runner.remote_user]
return self | [
"def",
"connect",
"(",
"self",
")",
":",
"vvv",
"(",
"\"ESTABLISH CONNECTION FOR USER: %s\"",
"%",
"self",
".",
"runner",
".",
"remote_user",
",",
"host",
"=",
"self",
".",
"host",
")",
"self",
".",
"common_args",
"=",
"[",
"]",
"extra_args",
"=",
"C",
".",
"ANSIBLE_SSH_ARGS",
"if",
"extra_args",
"is",
"not",
"None",
":",
"self",
".",
"common_args",
"+=",
"shlex",
".",
"split",
"(",
"extra_args",
")",
"else",
":",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"ControlMaster=auto\"",
",",
"\"-o\"",
",",
"\"ControlPersist=60s\"",
",",
"\"-o\"",
",",
"\"ControlPath=/tmp/ansible-ssh-%h-%p-%r\"",
"]",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"StrictHostKeyChecking=no\"",
"]",
"if",
"self",
".",
"port",
"is",
"not",
"None",
":",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"Port=%d\"",
"%",
"(",
"self",
".",
"port",
")",
"]",
"if",
"self",
".",
"runner",
".",
"private_key_file",
"is",
"not",
"None",
":",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"IdentityFile=\"",
"+",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"runner",
".",
"private_key_file",
")",
"]",
"if",
"self",
".",
"runner",
".",
"remote_pass",
":",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"GSSAPIAuthentication=no\"",
",",
"\"-o\"",
",",
"\"PubkeyAuthentication=no\"",
"]",
"else",
":",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"KbdInteractiveAuthentication=no\"",
",",
"\"-o\"",
",",
"\"PasswordAuthentication=no\"",
"]",
"self",
".",
"common_args",
"+=",
"[",
"\"-o\"",
",",
"\"User=\"",
"+",
"self",
".",
"runner",
".",
"remote_user",
"]",
"return",
"self"
] | connect to the remote host | [
"connect",
"to",
"the",
"remote",
"host"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/ssh.py#L39-L65 |
249,290 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/ssh.py | Connection.fetch_file | def fetch_file(self, in_path, out_path):
''' fetch a file from remote to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
cmd = self._password_cmd()
if C.DEFAULT_SCP_IF_SSH:
cmd += ["scp"] + self.common_args
cmd += [self.host + ":" + in_path, out_path]
indata = None
else:
cmd += ["sftp"] + self.common_args + [self.host]
indata = "get %s %s\n" % (in_path, out_path)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self._send_password()
stdout, stderr = p.communicate(indata)
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file from %s:\n%s\n%s" % (in_path, stdout, stderr)) | python | def fetch_file(self, in_path, out_path):
''' fetch a file from remote to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
cmd = self._password_cmd()
if C.DEFAULT_SCP_IF_SSH:
cmd += ["scp"] + self.common_args
cmd += [self.host + ":" + in_path, out_path]
indata = None
else:
cmd += ["sftp"] + self.common_args + [self.host]
indata = "get %s %s\n" % (in_path, out_path)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self._send_password()
stdout, stderr = p.communicate(indata)
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file from %s:\n%s\n%s" % (in_path, stdout, stderr)) | [
"def",
"fetch_file",
"(",
"self",
",",
"in_path",
",",
"out_path",
")",
":",
"vvv",
"(",
"\"FETCH %s TO %s\"",
"%",
"(",
"in_path",
",",
"out_path",
")",
",",
"host",
"=",
"self",
".",
"host",
")",
"cmd",
"=",
"self",
".",
"_password_cmd",
"(",
")",
"if",
"C",
".",
"DEFAULT_SCP_IF_SSH",
":",
"cmd",
"+=",
"[",
"\"scp\"",
"]",
"+",
"self",
".",
"common_args",
"cmd",
"+=",
"[",
"self",
".",
"host",
"+",
"\":\"",
"+",
"in_path",
",",
"out_path",
"]",
"indata",
"=",
"None",
"else",
":",
"cmd",
"+=",
"[",
"\"sftp\"",
"]",
"+",
"self",
".",
"common_args",
"+",
"[",
"self",
".",
"host",
"]",
"indata",
"=",
"\"get %s %s\\n\"",
"%",
"(",
"in_path",
",",
"out_path",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"self",
".",
"_send_password",
"(",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
"indata",
")",
"if",
"p",
".",
"returncode",
"!=",
"0",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"failed to transfer file from %s:\\n%s\\n%s\"",
"%",
"(",
"in_path",
",",
"stdout",
",",
"stderr",
")",
")"
] | fetch a file from remote to local | [
"fetch",
"a",
"file",
"from",
"remote",
"to",
"local"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/ssh.py#L182-L201 |
249,291 | minhhoit/yacms | yacms/blog/admin.py | BlogPostAdmin.save_form | def save_form(self, request, form, change):
"""
Super class ordering is important here - user must get saved first.
"""
OwnableAdmin.save_form(self, request, form, change)
return DisplayableAdmin.save_form(self, request, form, change) | python | def save_form(self, request, form, change):
"""
Super class ordering is important here - user must get saved first.
"""
OwnableAdmin.save_form(self, request, form, change)
return DisplayableAdmin.save_form(self, request, form, change) | [
"def",
"save_form",
"(",
"self",
",",
"request",
",",
"form",
",",
"change",
")",
":",
"OwnableAdmin",
".",
"save_form",
"(",
"self",
",",
"request",
",",
"form",
",",
"change",
")",
"return",
"DisplayableAdmin",
".",
"save_form",
"(",
"self",
",",
"request",
",",
"form",
",",
"change",
")"
] | Super class ordering is important here - user must get saved first. | [
"Super",
"class",
"ordering",
"is",
"important",
"here",
"-",
"user",
"must",
"get",
"saved",
"first",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/admin.py#L38-L43 |
249,292 | minhhoit/yacms | yacms/blog/admin.py | BlogCategoryAdmin.has_module_permission | def has_module_permission(self, request):
"""
Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``.
"""
for (name, items) in settings.ADMIN_MENU_ORDER:
if "blog.BlogCategory" in items:
return True
return False | python | def has_module_permission(self, request):
"""
Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``.
"""
for (name, items) in settings.ADMIN_MENU_ORDER:
if "blog.BlogCategory" in items:
return True
return False | [
"def",
"has_module_permission",
"(",
"self",
",",
"request",
")",
":",
"for",
"(",
"name",
",",
"items",
")",
"in",
"settings",
".",
"ADMIN_MENU_ORDER",
":",
"if",
"\"blog.BlogCategory\"",
"in",
"items",
":",
"return",
"True",
"return",
"False"
] | Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``. | [
"Hide",
"from",
"the",
"admin",
"menu",
"unless",
"explicitly",
"set",
"in",
"ADMIN_MENU_ORDER",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/admin.py#L54-L61 |
249,293 | rackerlabs/rackspace-python-neutronclient | neutronclient/common/utils.py | env | def env(*vars, **kwargs):
"""Returns the first environment variable set.
If none are non-empty, defaults to '' or keyword arg default.
"""
for v in vars:
value = os.environ.get(v)
if value:
return value
return kwargs.get('default', '') | python | def env(*vars, **kwargs):
"""Returns the first environment variable set.
If none are non-empty, defaults to '' or keyword arg default.
"""
for v in vars:
value = os.environ.get(v)
if value:
return value
return kwargs.get('default', '') | [
"def",
"env",
"(",
"*",
"vars",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"v",
"in",
"vars",
":",
"value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"v",
")",
"if",
"value",
":",
"return",
"value",
"return",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"''",
")"
] | Returns the first environment variable set.
If none are non-empty, defaults to '' or keyword arg default. | [
"Returns",
"the",
"first",
"environment",
"variable",
"set",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L37-L46 |
249,294 | rackerlabs/rackspace-python-neutronclient | neutronclient/common/utils.py | get_client_class | def get_client_class(api_name, version, version_map):
"""Returns the client class for the requested API version.
:param api_name: the name of the API, e.g. 'compute', 'image', etc
:param version: the requested API version
:param version_map: a dict of client classes keyed by version
:rtype: a client class for the requested API version
"""
try:
client_path = version_map[str(version)]
except (KeyError, ValueError):
msg = _("Invalid %(api_name)s client version '%(version)s'. must be "
"one of: %(map_keys)s")
msg = msg % {'api_name': api_name, 'version': version,
'map_keys': ', '.join(version_map.keys())}
raise exceptions.UnsupportedVersion(msg)
return importutils.import_class(client_path) | python | def get_client_class(api_name, version, version_map):
"""Returns the client class for the requested API version.
:param api_name: the name of the API, e.g. 'compute', 'image', etc
:param version: the requested API version
:param version_map: a dict of client classes keyed by version
:rtype: a client class for the requested API version
"""
try:
client_path = version_map[str(version)]
except (KeyError, ValueError):
msg = _("Invalid %(api_name)s client version '%(version)s'. must be "
"one of: %(map_keys)s")
msg = msg % {'api_name': api_name, 'version': version,
'map_keys': ', '.join(version_map.keys())}
raise exceptions.UnsupportedVersion(msg)
return importutils.import_class(client_path) | [
"def",
"get_client_class",
"(",
"api_name",
",",
"version",
",",
"version_map",
")",
":",
"try",
":",
"client_path",
"=",
"version_map",
"[",
"str",
"(",
"version",
")",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"msg",
"=",
"_",
"(",
"\"Invalid %(api_name)s client version '%(version)s'. must be \"",
"\"one of: %(map_keys)s\"",
")",
"msg",
"=",
"msg",
"%",
"{",
"'api_name'",
":",
"api_name",
",",
"'version'",
":",
"version",
",",
"'map_keys'",
":",
"', '",
".",
"join",
"(",
"version_map",
".",
"keys",
"(",
")",
")",
"}",
"raise",
"exceptions",
".",
"UnsupportedVersion",
"(",
"msg",
")",
"return",
"importutils",
".",
"import_class",
"(",
"client_path",
")"
] | Returns the client class for the requested API version.
:param api_name: the name of the API, e.g. 'compute', 'image', etc
:param version: the requested API version
:param version_map: a dict of client classes keyed by version
:rtype: a client class for the requested API version | [
"Returns",
"the",
"client",
"class",
"for",
"the",
"requested",
"API",
"version",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L57-L74 |
249,295 | rackerlabs/rackspace-python-neutronclient | neutronclient/common/utils.py | get_item_properties | def get_item_properties(item, fields, mixed_case_fields=(), formatters=None):
"""Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Tenant, etc)
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values
"""
if formatters is None:
formatters = {}
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](item))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
if not hasattr(item, field_name) and isinstance(item, dict):
data = item[field_name]
else:
data = getattr(item, field_name, '')
if data is None:
data = ''
row.append(data)
return tuple(row) | python | def get_item_properties(item, fields, mixed_case_fields=(), formatters=None):
"""Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Tenant, etc)
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values
"""
if formatters is None:
formatters = {}
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](item))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
if not hasattr(item, field_name) and isinstance(item, dict):
data = item[field_name]
else:
data = getattr(item, field_name, '')
if data is None:
data = ''
row.append(data)
return tuple(row) | [
"def",
"get_item_properties",
"(",
"item",
",",
"fields",
",",
"mixed_case_fields",
"=",
"(",
")",
",",
"formatters",
"=",
"None",
")",
":",
"if",
"formatters",
"is",
"None",
":",
"formatters",
"=",
"{",
"}",
"row",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
"in",
"formatters",
":",
"row",
".",
"append",
"(",
"formatters",
"[",
"field",
"]",
"(",
"item",
")",
")",
"else",
":",
"if",
"field",
"in",
"mixed_case_fields",
":",
"field_name",
"=",
"field",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"else",
":",
"field_name",
"=",
"field",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"if",
"not",
"hasattr",
"(",
"item",
",",
"field_name",
")",
"and",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"data",
"=",
"item",
"[",
"field_name",
"]",
"else",
":",
"data",
"=",
"getattr",
"(",
"item",
",",
"field_name",
",",
"''",
")",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"''",
"row",
".",
"append",
"(",
"data",
")",
"return",
"tuple",
"(",
"row",
")"
] | Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Tenant, etc)
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values | [
"Return",
"a",
"tuple",
"containing",
"the",
"item",
"properties",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L77-L106 |
249,296 | rackerlabs/rackspace-python-neutronclient | neutronclient/common/utils.py | str2dict | def str2dict(strdict, required_keys=None, optional_keys=None):
"""Convert key1=value1,key2=value2,... string into dictionary.
:param strdict: string in the form of key1=value1,key2=value2
:param required_keys: list of required keys. All keys in this list must be
specified. Otherwise ArgumentTypeError will be raised.
If this parameter is unspecified, no required key check
will be done.
:param optional_keys: list of optional keys.
This parameter is used for valid key check.
When at least one of required_keys and optional_keys,
a key must be a member of either of required_keys or
optional_keys. Otherwise, ArgumentTypeError will be
raised. When both required_keys and optional_keys are
unspecified, no valid key check will be done.
"""
result = {}
if strdict:
for kv in strdict.split(','):
key, sep, value = kv.partition('=')
if not sep:
msg = _("invalid key-value '%s', expected format: key=value")
raise argparse.ArgumentTypeError(msg % kv)
result[key] = value
valid_keys = set(required_keys or []) | set(optional_keys or [])
if valid_keys:
invalid_keys = [k for k in result if k not in valid_keys]
if invalid_keys:
msg = _("Invalid key(s) '%(invalid_keys)s' specified. "
"Valid key(s): '%(valid_keys)s'.")
raise argparse.ArgumentTypeError(
msg % {'invalid_keys': ', '.join(sorted(invalid_keys)),
'valid_keys': ', '.join(sorted(valid_keys))})
if required_keys:
not_found_keys = [k for k in required_keys if k not in result]
if not_found_keys:
msg = _("Required key(s) '%s' not specified.")
raise argparse.ArgumentTypeError(msg % ', '.join(not_found_keys))
return result | python | def str2dict(strdict, required_keys=None, optional_keys=None):
"""Convert key1=value1,key2=value2,... string into dictionary.
:param strdict: string in the form of key1=value1,key2=value2
:param required_keys: list of required keys. All keys in this list must be
specified. Otherwise ArgumentTypeError will be raised.
If this parameter is unspecified, no required key check
will be done.
:param optional_keys: list of optional keys.
This parameter is used for valid key check.
When at least one of required_keys and optional_keys,
a key must be a member of either of required_keys or
optional_keys. Otherwise, ArgumentTypeError will be
raised. When both required_keys and optional_keys are
unspecified, no valid key check will be done.
"""
result = {}
if strdict:
for kv in strdict.split(','):
key, sep, value = kv.partition('=')
if not sep:
msg = _("invalid key-value '%s', expected format: key=value")
raise argparse.ArgumentTypeError(msg % kv)
result[key] = value
valid_keys = set(required_keys or []) | set(optional_keys or [])
if valid_keys:
invalid_keys = [k for k in result if k not in valid_keys]
if invalid_keys:
msg = _("Invalid key(s) '%(invalid_keys)s' specified. "
"Valid key(s): '%(valid_keys)s'.")
raise argparse.ArgumentTypeError(
msg % {'invalid_keys': ', '.join(sorted(invalid_keys)),
'valid_keys': ', '.join(sorted(valid_keys))})
if required_keys:
not_found_keys = [k for k in required_keys if k not in result]
if not_found_keys:
msg = _("Required key(s) '%s' not specified.")
raise argparse.ArgumentTypeError(msg % ', '.join(not_found_keys))
return result | [
"def",
"str2dict",
"(",
"strdict",
",",
"required_keys",
"=",
"None",
",",
"optional_keys",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"if",
"strdict",
":",
"for",
"kv",
"in",
"strdict",
".",
"split",
"(",
"','",
")",
":",
"key",
",",
"sep",
",",
"value",
"=",
"kv",
".",
"partition",
"(",
"'='",
")",
"if",
"not",
"sep",
":",
"msg",
"=",
"_",
"(",
"\"invalid key-value '%s', expected format: key=value\"",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
"%",
"kv",
")",
"result",
"[",
"key",
"]",
"=",
"value",
"valid_keys",
"=",
"set",
"(",
"required_keys",
"or",
"[",
"]",
")",
"|",
"set",
"(",
"optional_keys",
"or",
"[",
"]",
")",
"if",
"valid_keys",
":",
"invalid_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"result",
"if",
"k",
"not",
"in",
"valid_keys",
"]",
"if",
"invalid_keys",
":",
"msg",
"=",
"_",
"(",
"\"Invalid key(s) '%(invalid_keys)s' specified. \"",
"\"Valid key(s): '%(valid_keys)s'.\"",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
"%",
"{",
"'invalid_keys'",
":",
"', '",
".",
"join",
"(",
"sorted",
"(",
"invalid_keys",
")",
")",
",",
"'valid_keys'",
":",
"', '",
".",
"join",
"(",
"sorted",
"(",
"valid_keys",
")",
")",
"}",
")",
"if",
"required_keys",
":",
"not_found_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"required_keys",
"if",
"k",
"not",
"in",
"result",
"]",
"if",
"not_found_keys",
":",
"msg",
"=",
"_",
"(",
"\"Required key(s) '%s' not specified.\"",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
"%",
"', '",
".",
"join",
"(",
"not_found_keys",
")",
")",
"return",
"result"
] | Convert key1=value1,key2=value2,... string into dictionary.
:param strdict: string in the form of key1=value1,key2=value2
:param required_keys: list of required keys. All keys in this list must be
specified. Otherwise ArgumentTypeError will be raised.
If this parameter is unspecified, no required key check
will be done.
:param optional_keys: list of optional keys.
This parameter is used for valid key check.
When at least one of required_keys and optional_keys,
a key must be a member of either of required_keys or
optional_keys. Otherwise, ArgumentTypeError will be
raised. When both required_keys and optional_keys are
unspecified, no valid key check will be done. | [
"Convert",
"key1",
"=",
"value1",
"key2",
"=",
"value2",
"...",
"string",
"into",
"dictionary",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/common/utils.py#L115-L153 |
249,297 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureCollection.loads | def loads(cls, data):
'''Create a feature collection from a CBOR byte string.'''
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')
metadata = rep[0]
if 'v' not in metadata:
raise SerializationError('no version in CBOR metadata')
if metadata['v'] != 'fc01':
raise SerializationError('invalid CBOR version {!r} '
'(expected "fc01")'
.format(metadata['v']))
read_only = metadata.get('ro', False)
contents = rep[1]
return cls.from_dict(contents, read_only=read_only) | python | def loads(cls, data):
'''Create a feature collection from a CBOR byte string.'''
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')
metadata = rep[0]
if 'v' not in metadata:
raise SerializationError('no version in CBOR metadata')
if metadata['v'] != 'fc01':
raise SerializationError('invalid CBOR version {!r} '
'(expected "fc01")'
.format(metadata['v']))
read_only = metadata.get('ro', False)
contents = rep[1]
return cls.from_dict(contents, read_only=read_only) | [
"def",
"loads",
"(",
"cls",
",",
"data",
")",
":",
"rep",
"=",
"cbor",
".",
"loads",
"(",
"data",
")",
"if",
"not",
"isinstance",
"(",
"rep",
",",
"Sequence",
")",
":",
"raise",
"SerializationError",
"(",
"'expected a CBOR list'",
")",
"if",
"len",
"(",
"rep",
")",
"!=",
"2",
":",
"raise",
"SerializationError",
"(",
"'expected a CBOR list of 2 items'",
")",
"metadata",
"=",
"rep",
"[",
"0",
"]",
"if",
"'v'",
"not",
"in",
"metadata",
":",
"raise",
"SerializationError",
"(",
"'no version in CBOR metadata'",
")",
"if",
"metadata",
"[",
"'v'",
"]",
"!=",
"'fc01'",
":",
"raise",
"SerializationError",
"(",
"'invalid CBOR version {!r} '",
"'(expected \"fc01\")'",
".",
"format",
"(",
"metadata",
"[",
"'v'",
"]",
")",
")",
"read_only",
"=",
"metadata",
".",
"get",
"(",
"'ro'",
",",
"False",
")",
"contents",
"=",
"rep",
"[",
"1",
"]",
"return",
"cls",
".",
"from_dict",
"(",
"contents",
",",
"read_only",
"=",
"read_only",
")"
] | Create a feature collection from a CBOR byte string. | [
"Create",
"a",
"feature",
"collection",
"from",
"a",
"CBOR",
"byte",
"string",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L185-L201 |
249,298 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureCollection.dumps | def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
rep = [metadata, self.to_dict()]
return cbor.dumps(rep) | python | def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
rep = [metadata, self.to_dict()]
return cbor.dumps(rep) | [
"def",
"dumps",
"(",
"self",
")",
":",
"metadata",
"=",
"{",
"'v'",
":",
"'fc01'",
"}",
"if",
"self",
".",
"read_only",
":",
"metadata",
"[",
"'ro'",
"]",
"=",
"1",
"rep",
"=",
"[",
"metadata",
",",
"self",
".",
"to_dict",
"(",
")",
"]",
"return",
"cbor",
".",
"dumps",
"(",
"rep",
")"
] | Create a CBOR byte string from a feature collection. | [
"Create",
"a",
"CBOR",
"byte",
"string",
"from",
"a",
"feature",
"collection",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L203-L209 |
249,299 | dossier/dossier.fc | python/dossier/fc/feature_collection.py | FeatureCollection.from_dict | def from_dict(cls, data, read_only=False):
'''Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
is instead passed as parameters to this function.
'''
fc = cls(read_only=read_only)
fc._features = {}
fc._from_dict_update(data)
return fc | python | def from_dict(cls, data, read_only=False):
'''Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
is instead passed as parameters to this function.
'''
fc = cls(read_only=read_only)
fc._features = {}
fc._from_dict_update(data)
return fc | [
"def",
"from_dict",
"(",
"cls",
",",
"data",
",",
"read_only",
"=",
"False",
")",
":",
"fc",
"=",
"cls",
"(",
"read_only",
"=",
"read_only",
")",
"fc",
".",
"_features",
"=",
"{",
"}",
"fc",
".",
"_from_dict_update",
"(",
"data",
")",
"return",
"fc"
] | Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
is instead passed as parameters to this function. | [
"Recreate",
"a",
"feature",
"collection",
"from",
"a",
"dictionary",
"."
] | 3e969d0cb2592fc06afc1c849d2b22283450b5e2 | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L212-L224 |
Subsets and Splits