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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,300 | Bogdanp/anom-py | anom/query.py | Query.paginate | def paginate(self, *, page_size, **options):
"""Run this query and return a page iterator.
Parameters:
page_size(int): The number of entities to fetch per page.
\**options(QueryOptions, optional)
Returns:
Pages: An iterator for this query's pages of results.
"""
return Pages(self._prepare(), page_size, QueryOptions(self, **options)) | python | def paginate(self, *, page_size, **options):
return Pages(self._prepare(), page_size, QueryOptions(self, **options)) | [
"def",
"paginate",
"(",
"self",
",",
"*",
",",
"page_size",
",",
"*",
"*",
"options",
")",
":",
"return",
"Pages",
"(",
"self",
".",
"_prepare",
"(",
")",
",",
"page_size",
",",
"QueryOptions",
"(",
"self",
",",
"*",
"*",
"options",
")",
")"
] | Run this query and return a page iterator.
Parameters:
page_size(int): The number of entities to fetch per page.
\**options(QueryOptions, optional)
Returns:
Pages: An iterator for this query's pages of results. | [
"Run",
"this",
"query",
"and",
"return",
"a",
"page",
"iterator",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/query.py#L455-L465 |
20,301 | Bogdanp/anom-py | anom/namespaces.py | namespace | def namespace(namespace):
"""Context manager for stacking the current thread-local default
namespace. Exiting the context sets the thread-local default
namespace back to the previously-set namespace. If there is no
previous namespace, then the thread-local namespace is cleared.
Example:
>>> with namespace("foo"):
... with namespace("bar"):
... assert get_namespace() == "bar"
... assert get_namespace() == "foo"
>>> assert get_namespace() == ""
Parameters:
namespace(str): namespace to set as the current thread-local
default.
Returns:
None
"""
try:
current_namespace = _namespace.current
except AttributeError:
current_namespace = None
set_namespace(namespace)
try:
yield
finally:
set_namespace(current_namespace) | python | def namespace(namespace):
try:
current_namespace = _namespace.current
except AttributeError:
current_namespace = None
set_namespace(namespace)
try:
yield
finally:
set_namespace(current_namespace) | [
"def",
"namespace",
"(",
"namespace",
")",
":",
"try",
":",
"current_namespace",
"=",
"_namespace",
".",
"current",
"except",
"AttributeError",
":",
"current_namespace",
"=",
"None",
"set_namespace",
"(",
"namespace",
")",
"try",
":",
"yield",
"finally",
":",
... | Context manager for stacking the current thread-local default
namespace. Exiting the context sets the thread-local default
namespace back to the previously-set namespace. If there is no
previous namespace, then the thread-local namespace is cleared.
Example:
>>> with namespace("foo"):
... with namespace("bar"):
... assert get_namespace() == "bar"
... assert get_namespace() == "foo"
>>> assert get_namespace() == ""
Parameters:
namespace(str): namespace to set as the current thread-local
default.
Returns:
None | [
"Context",
"manager",
"for",
"stacking",
"the",
"current",
"thread",
"-",
"local",
"default",
"namespace",
".",
"Exiting",
"the",
"context",
"sets",
"the",
"thread",
"-",
"local",
"default",
"namespace",
"back",
"to",
"the",
"previously",
"-",
"set",
"namespac... | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/namespaces.py#L55-L85 |
20,302 | Bogdanp/anom-py | anom/model.py | lookup_model_by_kind | def lookup_model_by_kind(kind):
"""Look up the model instance for a given Datastore kind.
Parameters:
kind(str)
Raises:
RuntimeError: If a model for the given kind has not been
defined.
Returns:
model: The model class.
"""
model = _known_models.get(kind)
if model is None:
raise RuntimeError(f"Model for kind {kind!r} not found.")
return model | python | def lookup_model_by_kind(kind):
model = _known_models.get(kind)
if model is None:
raise RuntimeError(f"Model for kind {kind!r} not found.")
return model | [
"def",
"lookup_model_by_kind",
"(",
"kind",
")",
":",
"model",
"=",
"_known_models",
".",
"get",
"(",
"kind",
")",
"if",
"model",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"f\"Model for kind {kind!r} not found.\"",
")",
"return",
"model"
] | Look up the model instance for a given Datastore kind.
Parameters:
kind(str)
Raises:
RuntimeError: If a model for the given kind has not been
defined.
Returns:
model: The model class. | [
"Look",
"up",
"the",
"model",
"instance",
"for",
"a",
"given",
"Datastore",
"kind",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L612-L628 |
20,303 | Bogdanp/anom-py | anom/model.py | delete_multi | def delete_multi(keys):
"""Delete a set of entitites from Datastore by their
respective keys.
Note:
This uses the adapter that is tied to the first model in the list.
If the keys have disparate adapters this function may behave in
unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of keys multiple times.
Parameters:
keys(list[anom.Key]): The list of keys whose entities to delete.
Raises:
RuntimeError: If the given set of keys have models that use
a disparate set of adapters or if any of the keys are
partial.
"""
if not keys:
return
adapter = None
for key in keys:
if key.is_partial:
raise RuntimeError(f"Key {key!r} is partial.")
model = lookup_model_by_kind(key.kind)
if adapter is None:
adapter = model._adapter
model.pre_delete_hook(key)
adapter.delete_multi(keys)
for key in keys:
# Micro-optimization to avoid calling get_model. This is OK
# to do here because we've already proved that a model for
# that kind exists in the previous block.
model = _known_models[key.kind]
model.post_delete_hook(key) | python | def delete_multi(keys):
if not keys:
return
adapter = None
for key in keys:
if key.is_partial:
raise RuntimeError(f"Key {key!r} is partial.")
model = lookup_model_by_kind(key.kind)
if adapter is None:
adapter = model._adapter
model.pre_delete_hook(key)
adapter.delete_multi(keys)
for key in keys:
# Micro-optimization to avoid calling get_model. This is OK
# to do here because we've already proved that a model for
# that kind exists in the previous block.
model = _known_models[key.kind]
model.post_delete_hook(key) | [
"def",
"delete_multi",
"(",
"keys",
")",
":",
"if",
"not",
"keys",
":",
"return",
"adapter",
"=",
"None",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
".",
"is_partial",
":",
"raise",
"RuntimeError",
"(",
"f\"Key {key!r} is partial.\"",
")",
"model",
"=",... | Delete a set of entitites from Datastore by their
respective keys.
Note:
This uses the adapter that is tied to the first model in the list.
If the keys have disparate adapters this function may behave in
unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of keys multiple times.
Parameters:
keys(list[anom.Key]): The list of keys whose entities to delete.
Raises:
RuntimeError: If the given set of keys have models that use
a disparate set of adapters or if any of the keys are
partial. | [
"Delete",
"a",
"set",
"of",
"entitites",
"from",
"Datastore",
"by",
"their",
"respective",
"keys",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L631-L673 |
20,304 | Bogdanp/anom-py | anom/model.py | get_multi | def get_multi(keys):
"""Get a set of entities from Datastore by their respective keys.
Note:
This uses the adapter that is tied to the first model in the
list. If the keys have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of keys multiple times.
Parameters:
keys(list[anom.Key]): The list of keys whose entities to get.
Raises:
RuntimeError: If the given set of keys have models that use
a disparate set of adapters or if any of the keys are
partial.
Returns:
list[Model]: Entities that do not exist are going to be None
in the result list. The order of results matches the order
of the input keys.
"""
if not keys:
return []
adapter = None
for key in keys:
if key.is_partial:
raise RuntimeError(f"Key {key!r} is partial.")
model = lookup_model_by_kind(key.kind)
if adapter is None:
adapter = model._adapter
model.pre_get_hook(key)
entities_data, entities = adapter.get_multi(keys), []
for key, entity_data in zip(keys, entities_data):
if entity_data is None:
entities.append(None)
continue
# Micro-optimization to avoid calling get_model. This is OK
# to do here because we've already proved that a model for
# that kind exists in the previous block.
model = _known_models[key.kind]
entity = model._load(key, entity_data)
entities.append(entity)
entity.post_get_hook()
return entities | python | def get_multi(keys):
if not keys:
return []
adapter = None
for key in keys:
if key.is_partial:
raise RuntimeError(f"Key {key!r} is partial.")
model = lookup_model_by_kind(key.kind)
if adapter is None:
adapter = model._adapter
model.pre_get_hook(key)
entities_data, entities = adapter.get_multi(keys), []
for key, entity_data in zip(keys, entities_data):
if entity_data is None:
entities.append(None)
continue
# Micro-optimization to avoid calling get_model. This is OK
# to do here because we've already proved that a model for
# that kind exists in the previous block.
model = _known_models[key.kind]
entity = model._load(key, entity_data)
entities.append(entity)
entity.post_get_hook()
return entities | [
"def",
"get_multi",
"(",
"keys",
")",
":",
"if",
"not",
"keys",
":",
"return",
"[",
"]",
"adapter",
"=",
"None",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
".",
"is_partial",
":",
"raise",
"RuntimeError",
"(",
"f\"Key {key!r} is partial.\"",
")",
"mod... | Get a set of entities from Datastore by their respective keys.
Note:
This uses the adapter that is tied to the first model in the
list. If the keys have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of keys multiple times.
Parameters:
keys(list[anom.Key]): The list of keys whose entities to get.
Raises:
RuntimeError: If the given set of keys have models that use
a disparate set of adapters or if any of the keys are
partial.
Returns:
list[Model]: Entities that do not exist are going to be None
in the result list. The order of results matches the order
of the input keys. | [
"Get",
"a",
"set",
"of",
"entities",
"from",
"Datastore",
"by",
"their",
"respective",
"keys",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L676-L730 |
20,305 | Bogdanp/anom-py | anom/model.py | put_multi | def put_multi(entities):
"""Persist a set of entities to Datastore.
Note:
This uses the adapter that is tied to the first Entity in the
list. If the entities have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of entities multiple times.
Parameters:
entities(list[Model]): The list of entities to persist.
Raises:
RuntimeError: If the given set of models use a disparate set of
adapters.
Returns:
list[Model]: The list of persisted entitites.
"""
if not entities:
return []
adapter, requests = None, []
for entity in entities:
if adapter is None:
adapter = entity._adapter
entity.pre_put_hook()
requests.append(PutRequest(entity.key, entity.unindexed_properties, entity))
keys = adapter.put_multi(requests)
for key, entity in zip(keys, entities):
entity.key = key
entity.post_put_hook()
return entities | python | def put_multi(entities):
if not entities:
return []
adapter, requests = None, []
for entity in entities:
if adapter is None:
adapter = entity._adapter
entity.pre_put_hook()
requests.append(PutRequest(entity.key, entity.unindexed_properties, entity))
keys = adapter.put_multi(requests)
for key, entity in zip(keys, entities):
entity.key = key
entity.post_put_hook()
return entities | [
"def",
"put_multi",
"(",
"entities",
")",
":",
"if",
"not",
"entities",
":",
"return",
"[",
"]",
"adapter",
",",
"requests",
"=",
"None",
",",
"[",
"]",
"for",
"entity",
"in",
"entities",
":",
"if",
"adapter",
"is",
"None",
":",
"adapter",
"=",
"enti... | Persist a set of entities to Datastore.
Note:
This uses the adapter that is tied to the first Entity in the
list. If the entities have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of entities multiple times.
Parameters:
entities(list[Model]): The list of entities to persist.
Raises:
RuntimeError: If the given set of models use a disparate set of
adapters.
Returns:
list[Model]: The list of persisted entitites. | [
"Persist",
"a",
"set",
"of",
"entities",
"to",
"Datastore",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L733-L772 |
20,306 | Bogdanp/anom-py | anom/model.py | Key.from_path | def from_path(cls, *path, namespace=None):
"""Build up a Datastore key from a path.
Parameters:
\*path(tuple[str or int]): The path segments.
namespace(str): An optional namespace for the key. This is
applied to each key in the tree.
Returns:
anom.Key: The Datastore represented by the given path.
"""
parent = None
for i in range(0, len(path), 2):
parent = cls(*path[i:i + 2], parent=parent, namespace=namespace)
return parent | python | def from_path(cls, *path, namespace=None):
parent = None
for i in range(0, len(path), 2):
parent = cls(*path[i:i + 2], parent=parent, namespace=namespace)
return parent | [
"def",
"from_path",
"(",
"cls",
",",
"*",
"path",
",",
"namespace",
"=",
"None",
")",
":",
"parent",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"path",
")",
",",
"2",
")",
":",
"parent",
"=",
"cls",
"(",
"*",
"path",
"... | Build up a Datastore key from a path.
Parameters:
\*path(tuple[str or int]): The path segments.
namespace(str): An optional namespace for the key. This is
applied to each key in the tree.
Returns:
anom.Key: The Datastore represented by the given path. | [
"Build",
"up",
"a",
"Datastore",
"key",
"from",
"a",
"path",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L70-L85 |
20,307 | Bogdanp/anom-py | anom/model.py | Property.validate | def validate(self, value):
"""Validates that `value` can be assigned to this Property.
Parameters:
value: The value to validate.
Raises:
TypeError: If the type of the assigned value is invalid.
Returns:
The value that should be assigned to the entity.
"""
if isinstance(value, self._types):
return value
elif self.optional and value is None:
return [] if self.repeated else None
elif self.repeated and isinstance(value, (tuple, list)) and all(isinstance(x, self._types) for x in value):
return value
else:
raise TypeError(f"Value of type {classname(value)} assigned to {classname(self)} property.") | python | def validate(self, value):
if isinstance(value, self._types):
return value
elif self.optional and value is None:
return [] if self.repeated else None
elif self.repeated and isinstance(value, (tuple, list)) and all(isinstance(x, self._types) for x in value):
return value
else:
raise TypeError(f"Value of type {classname(value)} assigned to {classname(self)} property.") | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"self",
".",
"_types",
")",
":",
"return",
"value",
"elif",
"self",
".",
"optional",
"and",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"self",
... | Validates that `value` can be assigned to this Property.
Parameters:
value: The value to validate.
Raises:
TypeError: If the type of the assigned value is invalid.
Returns:
The value that should be assigned to the entity. | [
"Validates",
"that",
"value",
"can",
"be",
"assigned",
"to",
"this",
"Property",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L230-L252 |
20,308 | Bogdanp/anom-py | anom/model.py | Property.prepare_to_store | def prepare_to_store(self, entity, value):
"""Prepare `value` for storage. Called by the Model for each
Property, value pair it contains before handing the data off
to an adapter.
Parameters:
entity(Model): The entity to which the value belongs.
value: The value being stored.
Raises:
RuntimeError: If this property is required but no value was
assigned to it.
Returns:
The value that should be persisted.
"""
if value is None and not self.optional:
raise RuntimeError(f"Property {self.name_on_model} requires a value.")
return value | python | def prepare_to_store(self, entity, value):
if value is None and not self.optional:
raise RuntimeError(f"Property {self.name_on_model} requires a value.")
return value | [
"def",
"prepare_to_store",
"(",
"self",
",",
"entity",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"not",
"self",
".",
"optional",
":",
"raise",
"RuntimeError",
"(",
"f\"Property {self.name_on_model} requires a value.\"",
")",
"return",
"value"
] | Prepare `value` for storage. Called by the Model for each
Property, value pair it contains before handing the data off
to an adapter.
Parameters:
entity(Model): The entity to which the value belongs.
value: The value being stored.
Raises:
RuntimeError: If this property is required but no value was
assigned to it.
Returns:
The value that should be persisted. | [
"Prepare",
"value",
"for",
"storage",
".",
"Called",
"by",
"the",
"Model",
"for",
"each",
"Property",
"value",
"pair",
"it",
"contains",
"before",
"handing",
"the",
"data",
"off",
"to",
"an",
"adapter",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L268-L286 |
20,309 | Bogdanp/anom-py | anom/model.py | Model.get | def get(cls, id_or_name, *, parent=None, namespace=None):
"""Get an entity by id.
Parameters:
id_or_name(int or str): The entity's id.
parent(anom.Key, optional): The entity's parent Key.
namespace(str, optional): The entity's namespace.
Returns:
Model: An entity or ``None`` if the entity doesn't exist in
Datastore.
"""
return Key(cls, id_or_name, parent=parent, namespace=namespace).get() | python | def get(cls, id_or_name, *, parent=None, namespace=None):
return Key(cls, id_or_name, parent=parent, namespace=namespace).get() | [
"def",
"get",
"(",
"cls",
",",
"id_or_name",
",",
"*",
",",
"parent",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"Key",
"(",
"cls",
",",
"id_or_name",
",",
"parent",
"=",
"parent",
",",
"namespace",
"=",
"namespace",
")",
".",
... | Get an entity by id.
Parameters:
id_or_name(int or str): The entity's id.
parent(anom.Key, optional): The entity's parent Key.
namespace(str, optional): The entity's namespace.
Returns:
Model: An entity or ``None`` if the entity doesn't exist in
Datastore. | [
"Get",
"an",
"entity",
"by",
"id",
"."
] | 519078b6d1570fa63c5f17cf98817c7bb5588136 | https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/model.py#L519-L531 |
20,310 | grauwoelfchen/flask-dotenv | flask_dotenv.py | DotEnv.init_app | def init_app(self, app, env_file=None, verbose_mode=False):
"""Imports .env file."""
if self.app is None:
self.app = app
self.verbose_mode = verbose_mode
if env_file is None:
env_file = os.path.join(os.getcwd(), ".env")
if not os.path.exists(env_file):
warnings.warn("can't read {0} - it doesn't exist".format(env_file))
else:
self.__import_vars(env_file) | python | def init_app(self, app, env_file=None, verbose_mode=False):
if self.app is None:
self.app = app
self.verbose_mode = verbose_mode
if env_file is None:
env_file = os.path.join(os.getcwd(), ".env")
if not os.path.exists(env_file):
warnings.warn("can't read {0} - it doesn't exist".format(env_file))
else:
self.__import_vars(env_file) | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"env_file",
"=",
"None",
",",
"verbose_mode",
"=",
"False",
")",
":",
"if",
"self",
".",
"app",
"is",
"None",
":",
"self",
".",
"app",
"=",
"app",
"self",
".",
"verbose_mode",
"=",
"verbose_mode",
"if"... | Imports .env file. | [
"Imports",
".",
"env",
"file",
"."
] | 7dc811fff18570c4b6803ce48c3ecca7eebabe51 | https://github.com/grauwoelfchen/flask-dotenv/blob/7dc811fff18570c4b6803ce48c3ecca7eebabe51/flask_dotenv.py#L24-L35 |
20,311 | grauwoelfchen/flask-dotenv | flask_dotenv.py | DotEnv.__import_vars | def __import_vars(self, env_file):
"""Actual importing function."""
with open(env_file, "r") as f: # pylint: disable=invalid-name
for line in f:
try:
line = line.lstrip()
if line.startswith('export'):
line = line.replace('export', '', 1)
key, val = line.strip().split('=', 1)
except ValueError: # Take care of blank or comment lines
pass
else:
if not callable(val):
if self.verbose_mode:
if key in self.app.config:
print(
" * Overwriting an existing config var:"
" {0}".format(key))
else:
print(
" * Setting an entirely new config var:"
" {0}".format(key))
self.app.config[key] = re.sub(
r"\A[\"']|[\"']\Z", "", val) | python | def __import_vars(self, env_file):
with open(env_file, "r") as f: # pylint: disable=invalid-name
for line in f:
try:
line = line.lstrip()
if line.startswith('export'):
line = line.replace('export', '', 1)
key, val = line.strip().split('=', 1)
except ValueError: # Take care of blank or comment lines
pass
else:
if not callable(val):
if self.verbose_mode:
if key in self.app.config:
print(
" * Overwriting an existing config var:"
" {0}".format(key))
else:
print(
" * Setting an entirely new config var:"
" {0}".format(key))
self.app.config[key] = re.sub(
r"\A[\"']|[\"']\Z", "", val) | [
"def",
"__import_vars",
"(",
"self",
",",
"env_file",
")",
":",
"with",
"open",
"(",
"env_file",
",",
"\"r\"",
")",
"as",
"f",
":",
"# pylint: disable=invalid-name",
"for",
"line",
"in",
"f",
":",
"try",
":",
"line",
"=",
"line",
".",
"lstrip",
"(",
")... | Actual importing function. | [
"Actual",
"importing",
"function",
"."
] | 7dc811fff18570c4b6803ce48c3ecca7eebabe51 | https://github.com/grauwoelfchen/flask-dotenv/blob/7dc811fff18570c4b6803ce48c3ecca7eebabe51/flask_dotenv.py#L37-L60 |
20,312 | uktrade/directory-components | directory_components/middleware.py | CountryMiddleware.process_response | def process_response(self, request, response):
"""
Shares config with the language cookie as they serve a similar purpose
"""
if hasattr(request, 'COUNTRY_CODE'):
response.set_cookie(
key=constants.COUNTRY_COOKIE_NAME,
value=request.COUNTRY_CODE,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN
)
return response | python | def process_response(self, request, response):
if hasattr(request, 'COUNTRY_CODE'):
response.set_cookie(
key=constants.COUNTRY_COOKIE_NAME,
value=request.COUNTRY_CODE,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN
)
return response | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'COUNTRY_CODE'",
")",
":",
"response",
".",
"set_cookie",
"(",
"key",
"=",
"constants",
".",
"COUNTRY_COOKIE_NAME",
",",
"value",
"=",
... | Shares config with the language cookie as they serve a similar purpose | [
"Shares",
"config",
"with",
"the",
"language",
"cookie",
"as",
"they",
"serve",
"a",
"similar",
"purpose"
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/directory_components/middleware.py#L91-L104 |
20,313 | uktrade/directory-components | directory_components/widgets.py | PrettyIDsMixin.create_option | def create_option(
self, name, value, label, selected, index,
subindex=None, attrs=None):
"""Patch to use nicer ids."""
index = str(index) if subindex is None else "%s%s%s" % (
index, self.id_separator, subindex)
if attrs is None:
attrs = {}
option_attrs = self.build_attrs(
self.attrs, attrs) if self.option_inherits_attrs else {}
if selected:
option_attrs.update(self.checked_attribute)
if 'id' in option_attrs:
if self.use_nice_ids:
option_attrs['id'] = "%s%s%s" % (
option_attrs['id'],
self.id_separator,
slugify(label.lower())
)
else:
option_attrs['id'] = self.id_for_label(
option_attrs['id'], index)
return {
'name': name,
'value': value,
'label': label,
'selected': selected,
'index': index,
'attrs': option_attrs,
'type': self.input_type,
'template_name': self.option_template_name,
'wrap_label': True,
} | python | def create_option(
self, name, value, label, selected, index,
subindex=None, attrs=None):
index = str(index) if subindex is None else "%s%s%s" % (
index, self.id_separator, subindex)
if attrs is None:
attrs = {}
option_attrs = self.build_attrs(
self.attrs, attrs) if self.option_inherits_attrs else {}
if selected:
option_attrs.update(self.checked_attribute)
if 'id' in option_attrs:
if self.use_nice_ids:
option_attrs['id'] = "%s%s%s" % (
option_attrs['id'],
self.id_separator,
slugify(label.lower())
)
else:
option_attrs['id'] = self.id_for_label(
option_attrs['id'], index)
return {
'name': name,
'value': value,
'label': label,
'selected': selected,
'index': index,
'attrs': option_attrs,
'type': self.input_type,
'template_name': self.option_template_name,
'wrap_label': True,
} | [
"def",
"create_option",
"(",
"self",
",",
"name",
",",
"value",
",",
"label",
",",
"selected",
",",
"index",
",",
"subindex",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"index",
"=",
"str",
"(",
"index",
")",
"if",
"subindex",
"is",
"None",
... | Patch to use nicer ids. | [
"Patch",
"to",
"use",
"nicer",
"ids",
"."
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/directory_components/widgets.py#L15-L47 |
20,314 | uktrade/directory-components | scripts/upgrade_header_footer.py | current_version | def current_version():
"""Get current version of directory-components."""
filepath = os.path.abspath(
project_root / "directory_components" / "version.py")
version_py = get_file_string(filepath)
regex = re.compile(Utils.get_version)
if regex.search(version_py) is not None:
current_version = regex.search(version_py).group(0)
print(color(
"Current directory-components version: {}".format(current_version),
fg='blue', style='bold'))
get_update_info()
else:
print(color(
'Error finding directory-components version.',
fg='red', style='bold')) | python | def current_version():
filepath = os.path.abspath(
project_root / "directory_components" / "version.py")
version_py = get_file_string(filepath)
regex = re.compile(Utils.get_version)
if regex.search(version_py) is not None:
current_version = regex.search(version_py).group(0)
print(color(
"Current directory-components version: {}".format(current_version),
fg='blue', style='bold'))
get_update_info()
else:
print(color(
'Error finding directory-components version.',
fg='red', style='bold')) | [
"def",
"current_version",
"(",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"project_root",
"/",
"\"directory_components\"",
"/",
"\"version.py\"",
")",
"version_py",
"=",
"get_file_string",
"(",
"filepath",
")",
"regex",
"=",
"re",
".",
... | Get current version of directory-components. | [
"Get",
"current",
"version",
"of",
"directory",
"-",
"components",
"."
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L27-L42 |
20,315 | uktrade/directory-components | scripts/upgrade_header_footer.py | get_file_string | def get_file_string(filepath):
"""Get string from file."""
with open(os.path.abspath(filepath)) as f:
return f.read() | python | def get_file_string(filepath):
with open(os.path.abspath(filepath)) as f:
return f.read() | [
"def",
"get_file_string",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"filepath",
")",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Get string from file. | [
"Get",
"string",
"from",
"file",
"."
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L45-L48 |
20,316 | uktrade/directory-components | scripts/upgrade_header_footer.py | replace_in_dirs | def replace_in_dirs(version):
"""Look through dirs and run replace_in_files in each."""
print(color(
"Upgrading directory-components dependency in all repos...",
fg='blue', style='bold'))
for dirname in Utils.dirs:
replace = "directory-components=={}".format(version)
replace_in_files(dirname, replace)
done(version) | python | def replace_in_dirs(version):
print(color(
"Upgrading directory-components dependency in all repos...",
fg='blue', style='bold'))
for dirname in Utils.dirs:
replace = "directory-components=={}".format(version)
replace_in_files(dirname, replace)
done(version) | [
"def",
"replace_in_dirs",
"(",
"version",
")",
":",
"print",
"(",
"color",
"(",
"\"Upgrading directory-components dependency in all repos...\"",
",",
"fg",
"=",
"'blue'",
",",
"style",
"=",
"'bold'",
")",
")",
"for",
"dirname",
"in",
"Utils",
".",
"dirs",
":",
... | Look through dirs and run replace_in_files in each. | [
"Look",
"through",
"dirs",
"and",
"run",
"replace_in_files",
"in",
"each",
"."
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L59-L67 |
20,317 | uktrade/directory-components | scripts/upgrade_header_footer.py | replace_in_files | def replace_in_files(dirname, replace):
"""Replace current version with new version in requirements files."""
filepath = os.path.abspath(dirname / "requirements.in")
if os.path.isfile(filepath) and header_footer_exists(filepath):
replaced = re.sub(Utils.exp, replace, get_file_string(filepath))
with open(filepath, "w") as f:
f.write(replaced)
print(color(
"Written to file: {}".format(filepath),
fg='magenta', style='bold')) | python | def replace_in_files(dirname, replace):
filepath = os.path.abspath(dirname / "requirements.in")
if os.path.isfile(filepath) and header_footer_exists(filepath):
replaced = re.sub(Utils.exp, replace, get_file_string(filepath))
with open(filepath, "w") as f:
f.write(replaced)
print(color(
"Written to file: {}".format(filepath),
fg='magenta', style='bold')) | [
"def",
"replace_in_files",
"(",
"dirname",
",",
"replace",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dirname",
"/",
"\"requirements.in\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
"and",
"header_footer_ex... | Replace current version with new version in requirements files. | [
"Replace",
"current",
"version",
"with",
"new",
"version",
"in",
"requirements",
"files",
"."
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L70-L79 |
20,318 | uktrade/directory-components | scripts/upgrade_header_footer.py | header_footer_exists | def header_footer_exists(filepath):
"""Check if directory-components is listed in requirements files."""
with open(filepath) as f:
return re.search(Utils.exp, f.read()) | python | def header_footer_exists(filepath):
with open(filepath) as f:
return re.search(Utils.exp, f.read()) | [
"def",
"header_footer_exists",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
")",
"as",
"f",
":",
"return",
"re",
".",
"search",
"(",
"Utils",
".",
"exp",
",",
"f",
".",
"read",
"(",
")",
")"
] | Check if directory-components is listed in requirements files. | [
"Check",
"if",
"directory",
"-",
"components",
"is",
"listed",
"in",
"requirements",
"files",
"."
] | 305b3cfd590e170255503ae3c41aebcaa658af8e | https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L82-L85 |
20,319 | bxlab/bx-python | lib/bx_extras/pstat.py | linedelimited | def linedelimited (inlist,delimiter):
"""
Returns a string composed of elements in inlist, with each element
separated by 'delimiter.' Used by function writedelimited. Use '\t'
for tab-delimiting.
Usage: linedelimited (inlist,delimiter)
"""
outstr = ''
for item in inlist:
if type(item) != StringType:
item = str(item)
outstr = outstr + item + delimiter
outstr = outstr[0:-1]
return outstr | python | def linedelimited (inlist,delimiter):
outstr = ''
for item in inlist:
if type(item) != StringType:
item = str(item)
outstr = outstr + item + delimiter
outstr = outstr[0:-1]
return outstr | [
"def",
"linedelimited",
"(",
"inlist",
",",
"delimiter",
")",
":",
"outstr",
"=",
"''",
"for",
"item",
"in",
"inlist",
":",
"if",
"type",
"(",
"item",
")",
"!=",
"StringType",
":",
"item",
"=",
"str",
"(",
"item",
")",
"outstr",
"=",
"outstr",
"+",
... | Returns a string composed of elements in inlist, with each element
separated by 'delimiter.' Used by function writedelimited. Use '\t'
for tab-delimiting.
Usage: linedelimited (inlist,delimiter) | [
"Returns",
"a",
"string",
"composed",
"of",
"elements",
"in",
"inlist",
"with",
"each",
"element",
"separated",
"by",
"delimiter",
".",
"Used",
"by",
"function",
"writedelimited",
".",
"Use",
"\\",
"t",
"for",
"tab",
"-",
"delimiting",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L396-L410 |
20,320 | bxlab/bx-python | lib/bx_extras/pstat.py | lineincustcols | def lineincustcols (inlist,colsizes):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes. The
length of colsizes must be greater than or equal to the number of columns
in inlist.
Usage: lineincustcols (inlist,colsizes)
Returns: formatted string created from inlist
"""
outstr = ''
for i in range(len(inlist)):
if type(inlist[i]) != StringType:
item = str(inlist[i])
else:
item = inlist[i]
size = len(item)
if size <= colsizes[i]:
for j in range(colsizes[i]-size):
outstr = outstr + ' '
outstr = outstr + item
else:
outstr = outstr + item[0:colsizes[i]+1]
return outstr | python | def lineincustcols (inlist,colsizes):
outstr = ''
for i in range(len(inlist)):
if type(inlist[i]) != StringType:
item = str(inlist[i])
else:
item = inlist[i]
size = len(item)
if size <= colsizes[i]:
for j in range(colsizes[i]-size):
outstr = outstr + ' '
outstr = outstr + item
else:
outstr = outstr + item[0:colsizes[i]+1]
return outstr | [
"def",
"lineincustcols",
"(",
"inlist",
",",
"colsizes",
")",
":",
"outstr",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"inlist",
")",
")",
":",
"if",
"type",
"(",
"inlist",
"[",
"i",
"]",
")",
"!=",
"StringType",
":",
"item",
"=",
"s... | Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes. The
length of colsizes must be greater than or equal to the number of columns
in inlist.
Usage: lineincustcols (inlist,colsizes)
Returns: formatted string created from inlist | [
"Returns",
"a",
"string",
"composed",
"of",
"elements",
"in",
"inlist",
"with",
"each",
"element",
"right",
"-",
"aligned",
"in",
"a",
"column",
"of",
"width",
"specified",
"by",
"a",
"sequence",
"colsizes",
".",
"The",
"length",
"of",
"colsizes",
"must",
... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L434-L457 |
20,321 | bxlab/bx-python | lib/bx_extras/pstat.py | list2string | def list2string (inlist,delimit=' '):
"""
Converts a 1D list to a single long string for file output, using
the string.join function.
Usage: list2string (inlist,delimit=' ')
Returns: the string created from inlist
"""
stringlist = [makestr(_) for _ in inlist]
return string.join(stringlist,delimit) | python | def list2string (inlist,delimit=' '):
stringlist = [makestr(_) for _ in inlist]
return string.join(stringlist,delimit) | [
"def",
"list2string",
"(",
"inlist",
",",
"delimit",
"=",
"' '",
")",
":",
"stringlist",
"=",
"[",
"makestr",
"(",
"_",
")",
"for",
"_",
"in",
"inlist",
"]",
"return",
"string",
".",
"join",
"(",
"stringlist",
",",
"delimit",
")"
] | Converts a 1D list to a single long string for file output, using
the string.join function.
Usage: list2string (inlist,delimit=' ')
Returns: the string created from inlist | [
"Converts",
"a",
"1D",
"list",
"to",
"a",
"single",
"long",
"string",
"for",
"file",
"output",
"using",
"the",
"string",
".",
"join",
"function",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L460-L469 |
20,322 | bxlab/bx-python | lib/bx_extras/pstat.py | replace | def replace (inlst,oldval,newval):
"""
Replaces all occurrences of 'oldval' with 'newval', recursively.
Usage: replace (inlst,oldval,newval)
"""
lst = inlst*1
for i in range(len(lst)):
if type(lst[i]) not in [ListType,TupleType]:
if lst[i]==oldval: lst[i]=newval
else:
lst[i] = replace(lst[i],oldval,newval)
return lst | python | def replace (inlst,oldval,newval):
lst = inlst*1
for i in range(len(lst)):
if type(lst[i]) not in [ListType,TupleType]:
if lst[i]==oldval: lst[i]=newval
else:
lst[i] = replace(lst[i],oldval,newval)
return lst | [
"def",
"replace",
"(",
"inlst",
",",
"oldval",
",",
"newval",
")",
":",
"lst",
"=",
"inlst",
"*",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"lst",
")",
")",
":",
"if",
"type",
"(",
"lst",
"[",
"i",
"]",
")",
"not",
"in",
"[",
"ListType... | Replaces all occurrences of 'oldval' with 'newval', recursively.
Usage: replace (inlst,oldval,newval) | [
"Replaces",
"all",
"occurrences",
"of",
"oldval",
"with",
"newval",
"recursively",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L564-L576 |
20,323 | bxlab/bx-python | lib/bx_extras/pstat.py | duplicates | def duplicates(inlist):
"""
Returns duplicate items in the FIRST dimension of the passed list.
Usage: duplicates (inlist)
"""
dups = []
for i in range(len(inlist)):
if inlist[i] in inlist[i+1:]:
dups.append(inlist[i])
return dups | python | def duplicates(inlist):
dups = []
for i in range(len(inlist)):
if inlist[i] in inlist[i+1:]:
dups.append(inlist[i])
return dups | [
"def",
"duplicates",
"(",
"inlist",
")",
":",
"dups",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"inlist",
")",
")",
":",
"if",
"inlist",
"[",
"i",
"]",
"in",
"inlist",
"[",
"i",
"+",
"1",
":",
"]",
":",
"dups",
".",
"append",... | Returns duplicate items in the FIRST dimension of the passed list.
Usage: duplicates (inlist) | [
"Returns",
"duplicate",
"items",
"in",
"the",
"FIRST",
"dimension",
"of",
"the",
"passed",
"list",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L676-L686 |
20,324 | bxlab/bx-python | lib/bx_extras/pstat.py | nonrepeats | def nonrepeats(inlist):
"""
Returns items that are NOT duplicated in the first dim of the passed list.
Usage: nonrepeats (inlist)
"""
nonrepeats = []
for i in range(len(inlist)):
if inlist.count(inlist[i]) == 1:
nonrepeats.append(inlist[i])
return nonrepeats | python | def nonrepeats(inlist):
nonrepeats = []
for i in range(len(inlist)):
if inlist.count(inlist[i]) == 1:
nonrepeats.append(inlist[i])
return nonrepeats | [
"def",
"nonrepeats",
"(",
"inlist",
")",
":",
"nonrepeats",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"inlist",
")",
")",
":",
"if",
"inlist",
".",
"count",
"(",
"inlist",
"[",
"i",
"]",
")",
"==",
"1",
":",
"nonrepeats",
".",
... | Returns items that are NOT duplicated in the first dim of the passed list.
Usage: nonrepeats (inlist) | [
"Returns",
"items",
"that",
"are",
"NOT",
"duplicated",
"in",
"the",
"first",
"dim",
"of",
"the",
"passed",
"list",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L689-L699 |
20,325 | bxlab/bx-python | lib/bx_extras/stats.py | lz | def lz (inlist, score):
"""
Returns the z-score for a given input score, given that score and the
list from which that score came. Not appropriate for population calculations.
Usage: lz(inlist, score)
"""
z = (score-mean(inlist))/samplestdev(inlist)
return z | python | def lz (inlist, score):
z = (score-mean(inlist))/samplestdev(inlist)
return z | [
"def",
"lz",
"(",
"inlist",
",",
"score",
")",
":",
"z",
"=",
"(",
"score",
"-",
"mean",
"(",
"inlist",
")",
")",
"/",
"samplestdev",
"(",
"inlist",
")",
"return",
"z"
] | Returns the z-score for a given input score, given that score and the
list from which that score came. Not appropriate for population calculations.
Usage: lz(inlist, score) | [
"Returns",
"the",
"z",
"-",
"score",
"for",
"a",
"given",
"input",
"score",
"given",
"that",
"score",
"and",
"the",
"list",
"from",
"which",
"that",
"score",
"came",
".",
"Not",
"appropriate",
"for",
"population",
"calculations",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L681-L689 |
20,326 | bxlab/bx-python | lib/bx_extras/stats.py | llinregress | def llinregress(x,y):
"""
Calculates a regression line on x,y pairs.
Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates
Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate
"""
TINY = 1.0e-20
if len(x) != len(y):
raise ValueError('Input values not paired in linregress. Aborting.')
n = len(x)
x = [float(_) for _ in x]
y = [float(_) for _ in y]
xmean = mean(x)
ymean = mean(y)
r_num = float(n*(summult(x,y)) - sum(x)*sum(y))
r_den = math.sqrt((n*ss(x) - square_of_sums(x))*(n*ss(y)-square_of_sums(y)))
r = r_num / r_den
z = 0.5*math.log((1.0+r+TINY)/(1.0-r+TINY))
df = n-2
t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)))
prob = betai(0.5*df,0.5,df/(df+t*t))
slope = r_num / float(n*ss(x) - square_of_sums(x))
intercept = ymean - slope*xmean
sterrest = math.sqrt(1-r*r)*samplestdev(y)
return slope, intercept, r, prob, sterrest | python | def llinregress(x,y):
TINY = 1.0e-20
if len(x) != len(y):
raise ValueError('Input values not paired in linregress. Aborting.')
n = len(x)
x = [float(_) for _ in x]
y = [float(_) for _ in y]
xmean = mean(x)
ymean = mean(y)
r_num = float(n*(summult(x,y)) - sum(x)*sum(y))
r_den = math.sqrt((n*ss(x) - square_of_sums(x))*(n*ss(y)-square_of_sums(y)))
r = r_num / r_den
z = 0.5*math.log((1.0+r+TINY)/(1.0-r+TINY))
df = n-2
t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY)))
prob = betai(0.5*df,0.5,df/(df+t*t))
slope = r_num / float(n*ss(x) - square_of_sums(x))
intercept = ymean - slope*xmean
sterrest = math.sqrt(1-r*r)*samplestdev(y)
return slope, intercept, r, prob, sterrest | [
"def",
"llinregress",
"(",
"x",
",",
"y",
")",
":",
"TINY",
"=",
"1.0e-20",
"if",
"len",
"(",
"x",
")",
"!=",
"len",
"(",
"y",
")",
":",
"raise",
"ValueError",
"(",
"'Input values not paired in linregress. Aborting.'",
")",
"n",
"=",
"len",
"(",
"x",
... | Calculates a regression line on x,y pairs.
Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates
Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate | [
"Calculates",
"a",
"regression",
"line",
"on",
"x",
"y",
"pairs",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L928-L953 |
20,327 | bxlab/bx-python | lib/bx_extras/stats.py | lks_2samp | def lks_2samp (data1,data2):
"""
Computes the Kolmogorov-Smirnof statistic on 2 samples. From
Numerical Recipies in C, page 493.
Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions
Returns: KS D-value, associated p-value
"""
j1 = 0
j2 = 0
fn1 = 0.0
fn2 = 0.0
n1 = len(data1)
n2 = len(data2)
en1 = n1
en2 = n2
d = 0.0
data1.sort()
data2.sort()
while j1 < n1 and j2 < n2:
d1=data1[j1]
d2=data2[j2]
if d1 <= d2:
fn1 = (j1)/float(en1)
j1 = j1 + 1
if d2 <= d1:
fn2 = (j2)/float(en2)
j2 = j2 + 1
dt = (fn2-fn1)
if math.fabs(dt) > math.fabs(d):
d = dt
try:
en = math.sqrt(en1*en2/float(en1+en2))
prob = ksprob((en+0.12+0.11/en)*abs(d))
except:
prob = 1.0
return d, prob | python | def lks_2samp (data1,data2):
j1 = 0
j2 = 0
fn1 = 0.0
fn2 = 0.0
n1 = len(data1)
n2 = len(data2)
en1 = n1
en2 = n2
d = 0.0
data1.sort()
data2.sort()
while j1 < n1 and j2 < n2:
d1=data1[j1]
d2=data2[j2]
if d1 <= d2:
fn1 = (j1)/float(en1)
j1 = j1 + 1
if d2 <= d1:
fn2 = (j2)/float(en2)
j2 = j2 + 1
dt = (fn2-fn1)
if math.fabs(dt) > math.fabs(d):
d = dt
try:
en = math.sqrt(en1*en2/float(en1+en2))
prob = ksprob((en+0.12+0.11/en)*abs(d))
except:
prob = 1.0
return d, prob | [
"def",
"lks_2samp",
"(",
"data1",
",",
"data2",
")",
":",
"j1",
"=",
"0",
"j2",
"=",
"0",
"fn1",
"=",
"0.0",
"fn2",
"=",
"0.0",
"n1",
"=",
"len",
"(",
"data1",
")",
"n2",
"=",
"len",
"(",
"data2",
")",
"en1",
"=",
"n1",
"en2",
"=",
"n2",
"d... | Computes the Kolmogorov-Smirnof statistic on 2 samples. From
Numerical Recipies in C, page 493.
Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions
Returns: KS D-value, associated p-value | [
"Computes",
"the",
"Kolmogorov",
"-",
"Smirnof",
"statistic",
"on",
"2",
"samples",
".",
"From",
"Numerical",
"Recipies",
"in",
"C",
"page",
"493",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1072-L1108 |
20,328 | bxlab/bx-python | lib/bx_extras/stats.py | lranksums | def lranksums(x,y):
"""
Calculates the rank sums statistic on the provided scores and
returns the result. Use only when the n in each condition is > 20 and you
have 2 independent samples of ranks.
Usage: lranksums(x,y)
Returns: a z-statistic, two-tailed p-value
"""
n1 = len(x)
n2 = len(y)
alldata = x+y
ranked = rankdata(alldata)
x = ranked[:n1]
y = ranked[n1:]
s = sum(x)
expected = n1*(n1+n2+1) / 2.0
z = (s - expected) / math.sqrt(n1*n2*(n1+n2+1)/12.0)
prob = 2*(1.0 -zprob(abs(z)))
return z, prob | python | def lranksums(x,y):
n1 = len(x)
n2 = len(y)
alldata = x+y
ranked = rankdata(alldata)
x = ranked[:n1]
y = ranked[n1:]
s = sum(x)
expected = n1*(n1+n2+1) / 2.0
z = (s - expected) / math.sqrt(n1*n2*(n1+n2+1)/12.0)
prob = 2*(1.0 -zprob(abs(z)))
return z, prob | [
"def",
"lranksums",
"(",
"x",
",",
"y",
")",
":",
"n1",
"=",
"len",
"(",
"x",
")",
"n2",
"=",
"len",
"(",
"y",
")",
"alldata",
"=",
"x",
"+",
"y",
"ranked",
"=",
"rankdata",
"(",
"alldata",
")",
"x",
"=",
"ranked",
"[",
":",
"n1",
"]",
"y",... | Calculates the rank sums statistic on the provided scores and
returns the result. Use only when the n in each condition is > 20 and you
have 2 independent samples of ranks.
Usage: lranksums(x,y)
Returns: a z-statistic, two-tailed p-value | [
"Calculates",
"the",
"rank",
"sums",
"statistic",
"on",
"the",
"provided",
"scores",
"and",
"returns",
"the",
"result",
".",
"Use",
"only",
"when",
"the",
"n",
"in",
"each",
"condition",
"is",
">",
"20",
"and",
"you",
"have",
"2",
"independent",
"samples",... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1165-L1184 |
20,329 | bxlab/bx-python | lib/bx_extras/stats.py | lkruskalwallish | def lkruskalwallish(*args):
"""
The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more
groups, requiring at least 5 subjects in each group. This function
calculates the Kruskal-Wallis H-test for 3 or more independent samples
and returns the result.
Usage: lkruskalwallish(*args)
Returns: H-statistic (corrected for ties), associated p-value
"""
args = list(args)
n = [0]*len(args)
all = []
n = [len(_) for _ in args]
for i in range(len(args)):
all = all + args[i]
ranked = rankdata(all)
T = tiecorrect(ranked)
for i in range(len(args)):
args[i] = ranked[0:n[i]]
del ranked[0:n[i]]
rsums = []
for i in range(len(args)):
rsums.append(sum(args[i])**2)
rsums[i] = rsums[i] / float(n[i])
ssbn = sum(rsums)
totaln = sum(n)
h = 12.0 / (totaln*(totaln+1)) * ssbn - 3*(totaln+1)
df = len(args) - 1
if T == 0:
raise ValueError('All numbers are identical in lkruskalwallish')
h = h / float(T)
return h, chisqprob(h,df) | python | def lkruskalwallish(*args):
args = list(args)
n = [0]*len(args)
all = []
n = [len(_) for _ in args]
for i in range(len(args)):
all = all + args[i]
ranked = rankdata(all)
T = tiecorrect(ranked)
for i in range(len(args)):
args[i] = ranked[0:n[i]]
del ranked[0:n[i]]
rsums = []
for i in range(len(args)):
rsums.append(sum(args[i])**2)
rsums[i] = rsums[i] / float(n[i])
ssbn = sum(rsums)
totaln = sum(n)
h = 12.0 / (totaln*(totaln+1)) * ssbn - 3*(totaln+1)
df = len(args) - 1
if T == 0:
raise ValueError('All numbers are identical in lkruskalwallish')
h = h / float(T)
return h, chisqprob(h,df) | [
"def",
"lkruskalwallish",
"(",
"*",
"args",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"n",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"args",
")",
"all",
"=",
"[",
"]",
"n",
"=",
"[",
"len",
"(",
"_",
")",
"for",
"_",
"in",
"args",
"]",
... | The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more
groups, requiring at least 5 subjects in each group. This function
calculates the Kruskal-Wallis H-test for 3 or more independent samples
and returns the result.
Usage: lkruskalwallish(*args)
Returns: H-statistic (corrected for ties), associated p-value | [
"The",
"Kruskal",
"-",
"Wallis",
"H",
"-",
"test",
"is",
"a",
"non",
"-",
"parametric",
"ANOVA",
"for",
"3",
"or",
"more",
"groups",
"requiring",
"at",
"least",
"5",
"subjects",
"in",
"each",
"group",
".",
"This",
"function",
"calculates",
"the",
"Kruska... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1220-L1252 |
20,330 | bxlab/bx-python | lib/bx_extras/stats.py | lksprob | def lksprob(alam):
"""
Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from
Numerical Recipies.
Usage: lksprob(alam)
"""
fac = 2.0
sum = 0.0
termbf = 0.0
a2 = -2.0*alam*alam
for j in range(1,201):
term = fac*math.exp(a2*j*j)
sum = sum + term
if math.fabs(term) <= (0.001*termbf) or math.fabs(term) < (1.0e-8*sum):
return sum
fac = -fac
termbf = math.fabs(term)
return 1.0 | python | def lksprob(alam):
fac = 2.0
sum = 0.0
termbf = 0.0
a2 = -2.0*alam*alam
for j in range(1,201):
term = fac*math.exp(a2*j*j)
sum = sum + term
if math.fabs(term) <= (0.001*termbf) or math.fabs(term) < (1.0e-8*sum):
return sum
fac = -fac
termbf = math.fabs(term)
return 1.0 | [
"def",
"lksprob",
"(",
"alam",
")",
":",
"fac",
"=",
"2.0",
"sum",
"=",
"0.0",
"termbf",
"=",
"0.0",
"a2",
"=",
"-",
"2.0",
"*",
"alam",
"*",
"alam",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"201",
")",
":",
"term",
"=",
"fac",
"*",
"math",
... | Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from
Numerical Recipies.
Usage: lksprob(alam) | [
"Computes",
"a",
"Kolmolgorov",
"-",
"Smirnov",
"t",
"-",
"test",
"significance",
"level",
".",
"Adapted",
"from",
"Numerical",
"Recipies",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1403-L1421 |
20,331 | bxlab/bx-python | lib/bx_extras/stats.py | outputpairedstats | def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob):
"""
Prints or write to a file stats for two groups, using the name, n,
mean, sterr, min and max for each group, as well as the statistic name,
its value, and the associated p-value.
Usage: outputpairedstats(fname,writemode,
name1,n1,mean1,stderr1,min1,max1,
name2,n2,mean2,stderr2,min2,max2,
statname,stat,prob)
Returns: None
"""
suffix = '' # for *s after the p-value
try:
x = prob.shape
prob = prob[0]
except:
pass
if prob < 0.001: suffix = ' ***'
elif prob < 0.01: suffix = ' **'
elif prob < 0.05: suffix = ' *'
title = [['Name','N','Mean','SD','Min','Max']]
lofl = title+[[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1],
[name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]]
if type(fname)!=StringType or len(fname)==0:
print()
print(statname)
print()
pstat.printcc(lofl)
print()
try:
if stat.shape == ():
stat = stat[0]
if prob.shape == ():
prob = prob[0]
except:
pass
print('Test statistic = ',round(stat,3),' p = ',round(prob,3),suffix)
print()
else:
file = open(fname,writemode)
file.write('\n'+statname+'\n\n')
file.close()
writecc(lofl,fname,'a')
file = open(fname,'a')
try:
if stat.shape == ():
stat = stat[0]
if prob.shape == ():
prob = prob[0]
except:
pass
file.write(pstat.list2string(['\nTest statistic = ',round(stat,4),' p = ',round(prob,4),suffix,'\n\n']))
file.close()
return None | python | def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob):
suffix = '' # for *s after the p-value
try:
x = prob.shape
prob = prob[0]
except:
pass
if prob < 0.001: suffix = ' ***'
elif prob < 0.01: suffix = ' **'
elif prob < 0.05: suffix = ' *'
title = [['Name','N','Mean','SD','Min','Max']]
lofl = title+[[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1],
[name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]]
if type(fname)!=StringType or len(fname)==0:
print()
print(statname)
print()
pstat.printcc(lofl)
print()
try:
if stat.shape == ():
stat = stat[0]
if prob.shape == ():
prob = prob[0]
except:
pass
print('Test statistic = ',round(stat,3),' p = ',round(prob,3),suffix)
print()
else:
file = open(fname,writemode)
file.write('\n'+statname+'\n\n')
file.close()
writecc(lofl,fname,'a')
file = open(fname,'a')
try:
if stat.shape == ():
stat = stat[0]
if prob.shape == ():
prob = prob[0]
except:
pass
file.write(pstat.list2string(['\nTest statistic = ',round(stat,4),' p = ',round(prob,4),suffix,'\n\n']))
file.close()
return None | [
"def",
"outputpairedstats",
"(",
"fname",
",",
"writemode",
",",
"name1",
",",
"n1",
",",
"m1",
",",
"se1",
",",
"min1",
",",
"max1",
",",
"name2",
",",
"n2",
",",
"m2",
",",
"se2",
",",
"min2",
",",
"max2",
",",
"statname",
",",
"stat",
",",
"pr... | Prints or write to a file stats for two groups, using the name, n,
mean, sterr, min and max for each group, as well as the statistic name,
its value, and the associated p-value.
Usage: outputpairedstats(fname,writemode,
name1,n1,mean1,stderr1,min1,max1,
name2,n2,mean2,stderr2,min2,max2,
statname,stat,prob)
Returns: None | [
"Prints",
"or",
"write",
"to",
"a",
"file",
"stats",
"for",
"two",
"groups",
"using",
"the",
"name",
"n",
"mean",
"sterr",
"min",
"and",
"max",
"for",
"each",
"group",
"as",
"well",
"as",
"the",
"statistic",
"name",
"its",
"value",
"and",
"the",
"assoc... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1762-L1816 |
20,332 | bxlab/bx-python | lib/bx/gene_reader.py | GeneReader | def GeneReader( fh, format='gff' ):
""" yield chrom, strand, gene_exons, name """
known_formats = ( 'gff', 'gtf', 'bed')
if format not in known_formats:
print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr)
raise Exception('?')
if format == 'bed':
for line in fh:
f = line.strip().split()
chrom = f[0]
chrom_start = int(f[1])
name = f[4]
strand = f[5]
cdsStart = int(f[6])
cdsEnd = int(f[7])
blockCount = int(f[9])
blockSizes = [ int(i) for i in f[10].strip(',').split(',') ]
blockStarts = [ chrom_start + int(i) for i in f[11].strip(',').split(',') ]
# grab cdsStart - cdsEnd
gene_exons = []
for base,offset in zip( blockStarts, blockSizes ):
exon_start = base
exon_end = base+offset
gene_exons.append( (exon_start, exon_end) )
yield chrom, strand, gene_exons, name
genelist = {}
grouplist = []
if format == 'gff' or format == 'gtf':
for line in fh:
if line.startswith('#'): continue
fields = line.strip().split('\t')
if len( fields ) < 9: continue
# fields
chrom = fields[0]
ex_st = int( fields[3] ) - 1 # make zero-centered
ex_end = int( fields[4] ) #+ 1 # make exclusive
strand = fields[6]
if format == 'gtf':
group = fields[8].split(';')[0]
else:
group = fields[8]
if group not in grouplist: grouplist.append( group )
if group not in genelist:
genelist[group] = (chrom, strand, [])
exons_i = 2
genelist[group][exons_i].append( ( ex_st, ex_end ) )
sp = lambda a,b: cmp( a[0], b[0] )
#for gene in genelist.values():
for gene in grouplist:
chrom, strand, gene_exons = genelist[ gene ]
gene_exons = bitset_union( gene_exons )
yield chrom, strand, gene_exons, gene | python | def GeneReader( fh, format='gff' ):
known_formats = ( 'gff', 'gtf', 'bed')
if format not in known_formats:
print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr)
raise Exception('?')
if format == 'bed':
for line in fh:
f = line.strip().split()
chrom = f[0]
chrom_start = int(f[1])
name = f[4]
strand = f[5]
cdsStart = int(f[6])
cdsEnd = int(f[7])
blockCount = int(f[9])
blockSizes = [ int(i) for i in f[10].strip(',').split(',') ]
blockStarts = [ chrom_start + int(i) for i in f[11].strip(',').split(',') ]
# grab cdsStart - cdsEnd
gene_exons = []
for base,offset in zip( blockStarts, blockSizes ):
exon_start = base
exon_end = base+offset
gene_exons.append( (exon_start, exon_end) )
yield chrom, strand, gene_exons, name
genelist = {}
grouplist = []
if format == 'gff' or format == 'gtf':
for line in fh:
if line.startswith('#'): continue
fields = line.strip().split('\t')
if len( fields ) < 9: continue
# fields
chrom = fields[0]
ex_st = int( fields[3] ) - 1 # make zero-centered
ex_end = int( fields[4] ) #+ 1 # make exclusive
strand = fields[6]
if format == 'gtf':
group = fields[8].split(';')[0]
else:
group = fields[8]
if group not in grouplist: grouplist.append( group )
if group not in genelist:
genelist[group] = (chrom, strand, [])
exons_i = 2
genelist[group][exons_i].append( ( ex_st, ex_end ) )
sp = lambda a,b: cmp( a[0], b[0] )
#for gene in genelist.values():
for gene in grouplist:
chrom, strand, gene_exons = genelist[ gene ]
gene_exons = bitset_union( gene_exons )
yield chrom, strand, gene_exons, gene | [
"def",
"GeneReader",
"(",
"fh",
",",
"format",
"=",
"'gff'",
")",
":",
"known_formats",
"=",
"(",
"'gff'",
",",
"'gtf'",
",",
"'bed'",
")",
"if",
"format",
"not",
"in",
"known_formats",
":",
"print",
"(",
"'%s format not in %s'",
"%",
"(",
"format",
",",... | yield chrom, strand, gene_exons, name | [
"yield",
"chrom",
"strand",
"gene_exons",
"name"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/gene_reader.py#L19-L79 |
20,333 | bxlab/bx-python | lib/bx/seq/seq.py | SeqFile.get | def get(self, start, length):
"""
Fetch subsequence starting at position `start` with length `length`.
This method is picky about parameters, the requested interval must
have non-negative length and fit entirely inside the NIB sequence,
the returned string will contain exactly 'length' characters, or an
AssertionError will be generated.
"""
# Check parameters
assert length >= 0, "Length must be non-negative (got %d)" % length
assert start >= 0,"Start must be greater than 0 (got %d)" % start
assert start + length <= self.length, \
"Interval beyond end of sequence (%s..%s > %s)" % ( start, start + length, self.length )
# Fetch sequence and reverse complement if necesary
if not self.revcomp:
return self.raw_fetch( start, length )
if self.revcomp == "-3'":
return self.reverse_complement(self.raw_fetch(start,length))
assert self.revcomp == "-5'", "unrecognized reverse complement scheme"
start = self.length - (start+length)
return self.reverse_complement(self.raw_fetch(start,length)) | python | def get(self, start, length):
# Check parameters
assert length >= 0, "Length must be non-negative (got %d)" % length
assert start >= 0,"Start must be greater than 0 (got %d)" % start
assert start + length <= self.length, \
"Interval beyond end of sequence (%s..%s > %s)" % ( start, start + length, self.length )
# Fetch sequence and reverse complement if necesary
if not self.revcomp:
return self.raw_fetch( start, length )
if self.revcomp == "-3'":
return self.reverse_complement(self.raw_fetch(start,length))
assert self.revcomp == "-5'", "unrecognized reverse complement scheme"
start = self.length - (start+length)
return self.reverse_complement(self.raw_fetch(start,length)) | [
"def",
"get",
"(",
"self",
",",
"start",
",",
"length",
")",
":",
"# Check parameters",
"assert",
"length",
">=",
"0",
",",
"\"Length must be non-negative (got %d)\"",
"%",
"length",
"assert",
"start",
">=",
"0",
",",
"\"Start must be greater than 0 (got %d)\"",
"%"... | Fetch subsequence starting at position `start` with length `length`.
This method is picky about parameters, the requested interval must
have non-negative length and fit entirely inside the NIB sequence,
the returned string will contain exactly 'length' characters, or an
AssertionError will be generated. | [
"Fetch",
"subsequence",
"starting",
"at",
"position",
"start",
"with",
"length",
"length",
".",
"This",
"method",
"is",
"picky",
"about",
"parameters",
"the",
"requested",
"interval",
"must",
"have",
"non",
"-",
"negative",
"length",
"and",
"fit",
"entirely",
... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/seq/seq.py#L74-L94 |
20,334 | bxlab/bx-python | lib/bx/align/score.py | read_scoring_scheme | def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ):
"""
Initialize scoring scheme from a file containint a blastz style text blob.
f can be either a file or the name of a file.
"""
close_it = False
if (type(f) == str):
f = file(f,"rt")
close_it = True
ss = build_scoring_scheme("".join([line for line in f]),gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)
if (close_it):
f.close()
return ss | python | def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ):
close_it = False
if (type(f) == str):
f = file(f,"rt")
close_it = True
ss = build_scoring_scheme("".join([line for line in f]),gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)
if (close_it):
f.close()
return ss | [
"def",
"read_scoring_scheme",
"(",
"f",
",",
"gap_open",
",",
"gap_extend",
",",
"gap1",
"=",
"\"-\"",
",",
"gap2",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"close_it",
"=",
"False",
"if",
"(",
"type",
"(",
"f",
")",
"==",
"str",
")",
":",
... | Initialize scoring scheme from a file containint a blastz style text blob.
f can be either a file or the name of a file. | [
"Initialize",
"scoring",
"scheme",
"from",
"a",
"file",
"containint",
"a",
"blastz",
"style",
"text",
"blob",
".",
"f",
"can",
"be",
"either",
"a",
"file",
"or",
"the",
"name",
"of",
"a",
"file",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/score.py#L91-L103 |
20,335 | bxlab/bx-python | lib/bx/align/core.py | shuffle_columns | def shuffle_columns( a ):
"""Randomize the columns of an alignment"""
mask = range( a.text_size )
random.shuffle( mask )
for c in a.components:
c.text = ''.join( [ c.text[i] for i in mask ] ) | python | def shuffle_columns( a ):
mask = range( a.text_size )
random.shuffle( mask )
for c in a.components:
c.text = ''.join( [ c.text[i] for i in mask ] ) | [
"def",
"shuffle_columns",
"(",
"a",
")",
":",
"mask",
"=",
"range",
"(",
"a",
".",
"text_size",
")",
"random",
".",
"shuffle",
"(",
"mask",
")",
"for",
"c",
"in",
"a",
".",
"components",
":",
"c",
".",
"text",
"=",
"''",
".",
"join",
"(",
"[",
... | Randomize the columns of an alignment | [
"Randomize",
"the",
"columns",
"of",
"an",
"alignment"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L403-L408 |
20,336 | bxlab/bx-python | lib/bx/align/core.py | Alignment.slice_by_component | def slice_by_component( self, component_index, start, end ):
"""
Return a slice of the alignment, corresponding to an coordinate interval in a specific component.
component_index is one of
an integer offset into the components list
a string indicating the src of the desired component
a component
start and end are relative to the + strand, regardless of the component's strand.
"""
if type( component_index ) == type( 0 ):
ref = self.components[ component_index ]
elif type( component_index ) == type( "" ):
ref = self.get_component_by_src( component_index )
elif type( component_index ) == Component:
ref = component_index
else:
raise ValueError( "can't figure out what to do" )
start_col = ref.coord_to_col( start )
end_col = ref.coord_to_col( end )
if (ref.strand == '-'):
(start_col,end_col) = (end_col,start_col)
return self.slice( start_col, end_col ) | python | def slice_by_component( self, component_index, start, end ):
if type( component_index ) == type( 0 ):
ref = self.components[ component_index ]
elif type( component_index ) == type( "" ):
ref = self.get_component_by_src( component_index )
elif type( component_index ) == Component:
ref = component_index
else:
raise ValueError( "can't figure out what to do" )
start_col = ref.coord_to_col( start )
end_col = ref.coord_to_col( end )
if (ref.strand == '-'):
(start_col,end_col) = (end_col,start_col)
return self.slice( start_col, end_col ) | [
"def",
"slice_by_component",
"(",
"self",
",",
"component_index",
",",
"start",
",",
"end",
")",
":",
"if",
"type",
"(",
"component_index",
")",
"==",
"type",
"(",
"0",
")",
":",
"ref",
"=",
"self",
".",
"components",
"[",
"component_index",
"]",
"elif",... | Return a slice of the alignment, corresponding to an coordinate interval in a specific component.
component_index is one of
an integer offset into the components list
a string indicating the src of the desired component
a component
start and end are relative to the + strand, regardless of the component's strand. | [
"Return",
"a",
"slice",
"of",
"the",
"alignment",
"corresponding",
"to",
"an",
"coordinate",
"interval",
"in",
"a",
"specific",
"component",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L122-L146 |
20,337 | bxlab/bx-python | lib/bx/align/core.py | Alignment.remove_all_gap_columns | def remove_all_gap_columns( self ):
"""
Remove any columns containing only gaps from alignment components,
text of components is modified IN PLACE.
"""
seqs = []
for c in self.components:
try:
seqs.append( list( c.text ) )
except TypeError:
seqs.append( None )
i = 0
text_size = self.text_size
while i < text_size:
all_gap = True
for seq in seqs:
if seq is None: continue
if seq[i] != '-': all_gap = False
if all_gap:
for seq in seqs:
if seq is None: continue
del seq[i]
text_size -= 1
else:
i += 1
for i in range( len( self.components ) ):
if seqs[i] is None: continue
self.components[i].text = ''.join( seqs[i] )
self.text_size = text_size | python | def remove_all_gap_columns( self ):
seqs = []
for c in self.components:
try:
seqs.append( list( c.text ) )
except TypeError:
seqs.append( None )
i = 0
text_size = self.text_size
while i < text_size:
all_gap = True
for seq in seqs:
if seq is None: continue
if seq[i] != '-': all_gap = False
if all_gap:
for seq in seqs:
if seq is None: continue
del seq[i]
text_size -= 1
else:
i += 1
for i in range( len( self.components ) ):
if seqs[i] is None: continue
self.components[i].text = ''.join( seqs[i] )
self.text_size = text_size | [
"def",
"remove_all_gap_columns",
"(",
"self",
")",
":",
"seqs",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"components",
":",
"try",
":",
"seqs",
".",
"append",
"(",
"list",
"(",
"c",
".",
"text",
")",
")",
"except",
"TypeError",
":",
"seqs",
".... | Remove any columns containing only gaps from alignment components,
text of components is modified IN PLACE. | [
"Remove",
"any",
"columns",
"containing",
"only",
"gaps",
"from",
"alignment",
"components",
"text",
"of",
"components",
"is",
"modified",
"IN",
"PLACE",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L160-L188 |
20,338 | bxlab/bx-python | lib/bx/align/core.py | Component.slice_by_coord | def slice_by_coord( self, start, end ):
"""
Return the slice of the component corresponding to a coordinate interval.
start and end are relative to the + strand, regardless of the component's strand.
"""
start_col = self.coord_to_col( start )
end_col = self.coord_to_col( end )
if (self.strand == '-'):
(start_col,end_col) = (end_col,start_col)
return self.slice( start_col, end_col ) | python | def slice_by_coord( self, start, end ):
start_col = self.coord_to_col( start )
end_col = self.coord_to_col( end )
if (self.strand == '-'):
(start_col,end_col) = (end_col,start_col)
return self.slice( start_col, end_col ) | [
"def",
"slice_by_coord",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"start_col",
"=",
"self",
".",
"coord_to_col",
"(",
"start",
")",
"end_col",
"=",
"self",
".",
"coord_to_col",
"(",
"end",
")",
"if",
"(",
"self",
".",
"strand",
"==",
"'-'",
"... | Return the slice of the component corresponding to a coordinate interval.
start and end are relative to the + strand, regardless of the component's strand. | [
"Return",
"the",
"slice",
"of",
"the",
"component",
"corresponding",
"to",
"a",
"coordinate",
"interval",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L307-L318 |
20,339 | bxlab/bx-python | lib/bx/align/core.py | Component.coord_to_col | def coord_to_col( self, pos ):
"""
Return the alignment column index corresponding to coordinate pos.
pos is relative to the + strand, regardless of the component's strand.
"""
start,end = self.get_forward_strand_start(),self.get_forward_strand_end()
if pos < start or pos > end:
raise ValueError("Range error: %d not in %d-%d" % ( pos, start, end ))
if not self.index:
self.index = list()
if (self.strand == '-'):
# nota bene: for - strand self.index[x] maps to one column
# higher than is actually associated with the position; thus
# when slice_by_component() and slice_by_coord() flip the ends,
# the resulting slice is correct
for x in range( len(self.text)-1,-1,-1 ):
if not self.text[x] == '-':
self.index.append( x + 1 )
self.index.append( 0 )
else:
for x in range( len(self.text) ):
if not self.text[x] == '-':
self.index.append(x)
self.index.append( len(self.text) )
x = None
try:
x = self.index[ pos - start ]
except:
raise Exception("Error in index.")
return x | python | def coord_to_col( self, pos ):
start,end = self.get_forward_strand_start(),self.get_forward_strand_end()
if pos < start or pos > end:
raise ValueError("Range error: %d not in %d-%d" % ( pos, start, end ))
if not self.index:
self.index = list()
if (self.strand == '-'):
# nota bene: for - strand self.index[x] maps to one column
# higher than is actually associated with the position; thus
# when slice_by_component() and slice_by_coord() flip the ends,
# the resulting slice is correct
for x in range( len(self.text)-1,-1,-1 ):
if not self.text[x] == '-':
self.index.append( x + 1 )
self.index.append( 0 )
else:
for x in range( len(self.text) ):
if not self.text[x] == '-':
self.index.append(x)
self.index.append( len(self.text) )
x = None
try:
x = self.index[ pos - start ]
except:
raise Exception("Error in index.")
return x | [
"def",
"coord_to_col",
"(",
"self",
",",
"pos",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"get_forward_strand_start",
"(",
")",
",",
"self",
".",
"get_forward_strand_end",
"(",
")",
"if",
"pos",
"<",
"start",
"or",
"pos",
">",
"end",
":",
"raise... | Return the alignment column index corresponding to coordinate pos.
pos is relative to the + strand, regardless of the component's strand. | [
"Return",
"the",
"alignment",
"column",
"index",
"corresponding",
"to",
"coordinate",
"pos",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/core.py#L320-L351 |
20,340 | bxlab/bx-python | lib/bx/align/tools/thread.py | get_components_for_species | def get_components_for_species( alignment, species ):
"""Return the component for each species in the list `species` or None"""
# If the number of components in the alignment is less that the requested number
# of species we can immediately fail
if len( alignment.components ) < len( species ): return None
# Otherwise, build an index of components by species, then lookup
index = dict( [ ( c.src.split( '.' )[0], c ) for c in alignment.components ] )
try: return [ index[s] for s in species ]
except: return None | python | def get_components_for_species( alignment, species ):
# If the number of components in the alignment is less that the requested number
# of species we can immediately fail
if len( alignment.components ) < len( species ): return None
# Otherwise, build an index of components by species, then lookup
index = dict( [ ( c.src.split( '.' )[0], c ) for c in alignment.components ] )
try: return [ index[s] for s in species ]
except: return None | [
"def",
"get_components_for_species",
"(",
"alignment",
",",
"species",
")",
":",
"# If the number of components in the alignment is less that the requested number",
"# of species we can immediately fail",
"if",
"len",
"(",
"alignment",
".",
"components",
")",
"<",
"len",
"(",
... | Return the component for each species in the list `species` or None | [
"Return",
"the",
"component",
"for",
"each",
"species",
"in",
"the",
"list",
"species",
"or",
"None"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/thread.py#L68-L76 |
20,341 | bxlab/bx-python | lib/bx/align/maf.py | read_next_maf | def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ):
"""
Read the next MAF block from `file` and return as an `Alignment`
instance. If `parse_i_rows` is true, empty components will be created
when e rows are encountered.
"""
alignment = Alignment(species_to_lengths=species_to_lengths)
# Attributes line
line = readline( file, skip_blank=True )
if not line: return None
fields = line.split()
if fields[0] != 'a': raise Exception("Expected 'a ...' line")
alignment.attributes = parse_attributes( fields[1:] )
if 'score' in alignment.attributes:
alignment.score = alignment.attributes['score']
del alignment.attributes['score']
else:
alignment.score = 0
# Sequence lines
last_component = None
while 1:
line = readline( file )
# EOF or Blank line terminates alignment components
if not line or line.isspace(): break
if line.isspace(): break
# Parse row
fields = line.split()
if fields[0] == 's':
# An 's' row contains sequence for a component
component = Component()
component.src = fields[1]
component.start = int( fields[2] )
component.size = int( fields[3] )
component.strand = fields[4]
component.src_size = int( fields[5] )
if len(fields) > 6: component.text = fields[6].strip()
# Add to set
alignment.add_component( component )
last_component = component
elif fields[0] == 'e':
# An 'e' row, when no bases align for a given species this tells
# us something about the synteny
if parse_e_rows:
component = Component()
component.empty = True
component.src = fields[1]
component.start = int( fields[2] )
component.size = int( fields[3] )
component.strand = fields[4]
component.src_size = int( fields[5] )
component.text = None
synteny = fields[6].strip()
assert len( synteny ) == 1, \
"Synteny status in 'e' rows should be denoted with a single character code"
component.synteny_empty = synteny
alignment.add_component( component )
last_component = component
elif fields[0] == 'i':
# An 'i' row, indicates left and right synteny status for the
# previous component, we hope ;)
assert fields[1] == last_component.src, "'i' row does not follow matching 's' row"
last_component.synteny_left = ( fields[2], int( fields[3] ) )
last_component.synteny_right = ( fields[4], int( fields[5] ) )
elif fields[0] == 'q':
assert fields[1] == last_component.src, "'q' row does not follow matching 's' row"
# TODO: Should convert this to an integer array?
last_component.quality = fields[2]
return alignment | python | def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ):
alignment = Alignment(species_to_lengths=species_to_lengths)
# Attributes line
line = readline( file, skip_blank=True )
if not line: return None
fields = line.split()
if fields[0] != 'a': raise Exception("Expected 'a ...' line")
alignment.attributes = parse_attributes( fields[1:] )
if 'score' in alignment.attributes:
alignment.score = alignment.attributes['score']
del alignment.attributes['score']
else:
alignment.score = 0
# Sequence lines
last_component = None
while 1:
line = readline( file )
# EOF or Blank line terminates alignment components
if not line or line.isspace(): break
if line.isspace(): break
# Parse row
fields = line.split()
if fields[0] == 's':
# An 's' row contains sequence for a component
component = Component()
component.src = fields[1]
component.start = int( fields[2] )
component.size = int( fields[3] )
component.strand = fields[4]
component.src_size = int( fields[5] )
if len(fields) > 6: component.text = fields[6].strip()
# Add to set
alignment.add_component( component )
last_component = component
elif fields[0] == 'e':
# An 'e' row, when no bases align for a given species this tells
# us something about the synteny
if parse_e_rows:
component = Component()
component.empty = True
component.src = fields[1]
component.start = int( fields[2] )
component.size = int( fields[3] )
component.strand = fields[4]
component.src_size = int( fields[5] )
component.text = None
synteny = fields[6].strip()
assert len( synteny ) == 1, \
"Synteny status in 'e' rows should be denoted with a single character code"
component.synteny_empty = synteny
alignment.add_component( component )
last_component = component
elif fields[0] == 'i':
# An 'i' row, indicates left and right synteny status for the
# previous component, we hope ;)
assert fields[1] == last_component.src, "'i' row does not follow matching 's' row"
last_component.synteny_left = ( fields[2], int( fields[3] ) )
last_component.synteny_right = ( fields[4], int( fields[5] ) )
elif fields[0] == 'q':
assert fields[1] == last_component.src, "'q' row does not follow matching 's' row"
# TODO: Should convert this to an integer array?
last_component.quality = fields[2]
return alignment | [
"def",
"read_next_maf",
"(",
"file",
",",
"species_to_lengths",
"=",
"None",
",",
"parse_e_rows",
"=",
"False",
")",
":",
"alignment",
"=",
"Alignment",
"(",
"species_to_lengths",
"=",
"species_to_lengths",
")",
"# Attributes line",
"line",
"=",
"readline",
"(",
... | Read the next MAF block from `file` and return as an `Alignment`
instance. If `parse_i_rows` is true, empty components will be created
when e rows are encountered. | [
"Read",
"the",
"next",
"MAF",
"block",
"from",
"file",
"and",
"return",
"as",
"an",
"Alignment",
"instance",
".",
"If",
"parse_i_rows",
"is",
"true",
"empty",
"components",
"will",
"be",
"created",
"when",
"e",
"rows",
"are",
"encountered",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/maf.py#L133-L201 |
20,342 | bxlab/bx-python | lib/bx/align/maf.py | readline | def readline( file, skip_blank=False ):
"""Read a line from provided file, skipping any blank or comment lines"""
while 1:
line = file.readline()
#print "every line: %r" % line
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
return line | python | def readline( file, skip_blank=False ):
while 1:
line = file.readline()
#print "every line: %r" % line
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
return line | [
"def",
"readline",
"(",
"file",
",",
"skip_blank",
"=",
"False",
")",
":",
"while",
"1",
":",
"line",
"=",
"file",
".",
"readline",
"(",
")",
"#print \"every line: %r\" % line",
"if",
"not",
"line",
":",
"return",
"None",
"if",
"line",
"[",
"0",
"]",
"... | Read a line from provided file, skipping any blank or comment lines | [
"Read",
"a",
"line",
"from",
"provided",
"file",
"skipping",
"any",
"blank",
"or",
"comment",
"lines"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/maf.py#L203-L210 |
20,343 | bxlab/bx-python | lib/bx/align/maf.py | parse_attributes | def parse_attributes( fields ):
"""Parse list of key=value strings into a dict"""
attributes = {}
for field in fields:
pair = field.split( '=' )
attributes[ pair[0] ] = pair[1]
return attributes | python | def parse_attributes( fields ):
attributes = {}
for field in fields:
pair = field.split( '=' )
attributes[ pair[0] ] = pair[1]
return attributes | [
"def",
"parse_attributes",
"(",
"fields",
")",
":",
"attributes",
"=",
"{",
"}",
"for",
"field",
"in",
"fields",
":",
"pair",
"=",
"field",
".",
"split",
"(",
"'='",
")",
"attributes",
"[",
"pair",
"[",
"0",
"]",
"]",
"=",
"pair",
"[",
"1",
"]",
... | Parse list of key=value strings into a dict | [
"Parse",
"list",
"of",
"key",
"=",
"value",
"strings",
"into",
"a",
"dict"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/maf.py#L212-L218 |
20,344 | bxlab/bx-python | lib/bx/motif/io/transfac.py | TransfacReader.as_dict | def as_dict( self, key="id" ):
"""
Return a dictionary containing all remaining motifs, using `key`
as the dictionary key.
"""
rval = {}
for motif in self:
rval[ getattr( motif, key ) ] = motif
return rval | python | def as_dict( self, key="id" ):
rval = {}
for motif in self:
rval[ getattr( motif, key ) ] = motif
return rval | [
"def",
"as_dict",
"(",
"self",
",",
"key",
"=",
"\"id\"",
")",
":",
"rval",
"=",
"{",
"}",
"for",
"motif",
"in",
"self",
":",
"rval",
"[",
"getattr",
"(",
"motif",
",",
"key",
")",
"]",
"=",
"motif",
"return",
"rval"
] | Return a dictionary containing all remaining motifs, using `key`
as the dictionary key. | [
"Return",
"a",
"dictionary",
"containing",
"all",
"remaining",
"motifs",
"using",
"key",
"as",
"the",
"dictionary",
"key",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/io/transfac.py#L52-L60 |
20,345 | bxlab/bx-python | lib/bx/motif/io/transfac.py | TransfacReader.parse_record | def parse_record( self, lines ):
"""
Parse a TRANSFAC record out of `lines` and return a motif.
"""
# Break lines up
temp_lines = []
for line in lines:
fields = line.rstrip( "\r\n" ).split( None, 1 )
if len( fields ) == 1:
fields.append( "" )
temp_lines.append( fields )
lines = temp_lines
# Fill in motif from lines
motif = TransfacMotif()
current_line = 0
while 1:
# Done parsing if no more lines to consume
if current_line >= len( lines ):
break
# Remove prefix and first separator from line
prefix, rest = lines[ current_line ]
# No action for this prefix, just ignore the line
if prefix not in self.parse_actions:
current_line += 1
continue
# Get action for line
action = self.parse_actions[ prefix ]
# Store a single line value
if action[0] == "store_single":
key = action[1]
setattr( motif, key, rest )
current_line += 1
# Add a single line value to a list
if action[0] == "store_single_list":
key = action[1]
if not getattr( motif, key ):
setattr( motif, key, [] )
getattr( motif, key ).append( rest )
current_line += 1
# Add a single line value to a dictionary
if action[0] == "store_single_key_value":
key = action[1]
k, v = rest.strip().split( '=', 1 )
if not getattr( motif, key ):
setattr( motif, key, {} )
getattr( motif, key )[k] = v
current_line += 1
# Store a block of text
if action[0] == "store_block":
key = action[1]
value = []
while current_line < len( lines ) and lines[ current_line ][0] == prefix:
value.append( lines[current_line][1] )
current_line += 1
setattr( motif, key, str.join( "\n", value ) )
# Store a matrix
if action[0] == "store_matrix":
# First line is alphabet
alphabet = rest.split()
alphabet_size = len( alphabet )
rows = []
pattern = ""
current_line += 1
# Next lines are the rows of the matrix (we allow 0 rows)
while current_line < len( lines ):
prefix, rest = lines[ current_line ]
# Prefix should be a two digit 0 padded row number
if not prefix.isdigit():
break
# The first `alphabet_size` fields are the row values
values = rest.split()
rows.append( [ float(_) for _ in values[:alphabet_size] ] )
# TRANSFAC includes an extra column with the IUPAC code
if len( values ) > alphabet_size:
pattern += values[alphabet_size]
current_line += 1
# Only store the pattern if it is the correct length (meaning
# that every row had an extra field)
if len( pattern ) != len( rows ):
pattern = None
matrix = FrequencyMatrix.from_rows( alphabet, rows )
setattr( motif, action[1], matrix )
# Only return a motif if we saw at least ID or AC or NA
if motif.id or motif.accession or motif.name:
return motif | python | def parse_record( self, lines ):
# Break lines up
temp_lines = []
for line in lines:
fields = line.rstrip( "\r\n" ).split( None, 1 )
if len( fields ) == 1:
fields.append( "" )
temp_lines.append( fields )
lines = temp_lines
# Fill in motif from lines
motif = TransfacMotif()
current_line = 0
while 1:
# Done parsing if no more lines to consume
if current_line >= len( lines ):
break
# Remove prefix and first separator from line
prefix, rest = lines[ current_line ]
# No action for this prefix, just ignore the line
if prefix not in self.parse_actions:
current_line += 1
continue
# Get action for line
action = self.parse_actions[ prefix ]
# Store a single line value
if action[0] == "store_single":
key = action[1]
setattr( motif, key, rest )
current_line += 1
# Add a single line value to a list
if action[0] == "store_single_list":
key = action[1]
if not getattr( motif, key ):
setattr( motif, key, [] )
getattr( motif, key ).append( rest )
current_line += 1
# Add a single line value to a dictionary
if action[0] == "store_single_key_value":
key = action[1]
k, v = rest.strip().split( '=', 1 )
if not getattr( motif, key ):
setattr( motif, key, {} )
getattr( motif, key )[k] = v
current_line += 1
# Store a block of text
if action[0] == "store_block":
key = action[1]
value = []
while current_line < len( lines ) and lines[ current_line ][0] == prefix:
value.append( lines[current_line][1] )
current_line += 1
setattr( motif, key, str.join( "\n", value ) )
# Store a matrix
if action[0] == "store_matrix":
# First line is alphabet
alphabet = rest.split()
alphabet_size = len( alphabet )
rows = []
pattern = ""
current_line += 1
# Next lines are the rows of the matrix (we allow 0 rows)
while current_line < len( lines ):
prefix, rest = lines[ current_line ]
# Prefix should be a two digit 0 padded row number
if not prefix.isdigit():
break
# The first `alphabet_size` fields are the row values
values = rest.split()
rows.append( [ float(_) for _ in values[:alphabet_size] ] )
# TRANSFAC includes an extra column with the IUPAC code
if len( values ) > alphabet_size:
pattern += values[alphabet_size]
current_line += 1
# Only store the pattern if it is the correct length (meaning
# that every row had an extra field)
if len( pattern ) != len( rows ):
pattern = None
matrix = FrequencyMatrix.from_rows( alphabet, rows )
setattr( motif, action[1], matrix )
# Only return a motif if we saw at least ID or AC or NA
if motif.id or motif.accession or motif.name:
return motif | [
"def",
"parse_record",
"(",
"self",
",",
"lines",
")",
":",
"# Break lines up",
"temp_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"fields",
"=",
"line",
".",
"rstrip",
"(",
"\"\\r\\n\"",
")",
".",
"split",
"(",
"None",
",",
"1",
")",
"i... | Parse a TRANSFAC record out of `lines` and return a motif. | [
"Parse",
"a",
"TRANSFAC",
"record",
"out",
"of",
"lines",
"and",
"return",
"a",
"motif",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/io/transfac.py#L90-L174 |
20,346 | bxlab/bx-python | scripts/bed_rand_intersect.py | bit_clone | def bit_clone( bits ):
"""
Clone a bitset
"""
new = BitSet( bits.size )
new.ior( bits )
return new | python | def bit_clone( bits ):
new = BitSet( bits.size )
new.ior( bits )
return new | [
"def",
"bit_clone",
"(",
"bits",
")",
":",
"new",
"=",
"BitSet",
"(",
"bits",
".",
"size",
")",
"new",
".",
"ior",
"(",
"bits",
")",
"return",
"new"
] | Clone a bitset | [
"Clone",
"a",
"bitset"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L35-L41 |
20,347 | bxlab/bx-python | scripts/bed_rand_intersect.py | throw_random | def throw_random( lengths, mask ):
"""
Try multiple times to run 'throw_random'
"""
saved = None
for i in range( maxtries ):
try:
return throw_random_bits( lengths, mask )
except MaxtriesException as e:
saved = e
continue
raise e | python | def throw_random( lengths, mask ):
saved = None
for i in range( maxtries ):
try:
return throw_random_bits( lengths, mask )
except MaxtriesException as e:
saved = e
continue
raise e | [
"def",
"throw_random",
"(",
"lengths",
",",
"mask",
")",
":",
"saved",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"maxtries",
")",
":",
"try",
":",
"return",
"throw_random_bits",
"(",
"lengths",
",",
"mask",
")",
"except",
"MaxtriesException",
"as",
"e... | Try multiple times to run 'throw_random' | [
"Try",
"multiple",
"times",
"to",
"run",
"throw_random"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L43-L54 |
20,348 | bxlab/bx-python | scripts/bed_rand_intersect.py | as_bits | def as_bits( region_start, region_length, intervals ):
"""
Convert a set of intervals overlapping a region of a chromosome into
a bitset for just that region with the bits covered by the intervals
set.
"""
bits = BitSet( region_length )
for chr, start, stop in intervals:
bits.set_range( start - region_start, stop - start )
return bits | python | def as_bits( region_start, region_length, intervals ):
bits = BitSet( region_length )
for chr, start, stop in intervals:
bits.set_range( start - region_start, stop - start )
return bits | [
"def",
"as_bits",
"(",
"region_start",
",",
"region_length",
",",
"intervals",
")",
":",
"bits",
"=",
"BitSet",
"(",
"region_length",
")",
"for",
"chr",
",",
"start",
",",
"stop",
"in",
"intervals",
":",
"bits",
".",
"set_range",
"(",
"start",
"-",
"regi... | Convert a set of intervals overlapping a region of a chromosome into
a bitset for just that region with the bits covered by the intervals
set. | [
"Convert",
"a",
"set",
"of",
"intervals",
"overlapping",
"a",
"region",
"of",
"a",
"chromosome",
"into",
"a",
"bitset",
"for",
"just",
"that",
"region",
"with",
"the",
"bits",
"covered",
"by",
"the",
"intervals",
"set",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L56-L65 |
20,349 | bxlab/bx-python | scripts/bed_rand_intersect.py | interval_lengths | def interval_lengths( bits ):
"""
Get the length distribution of all contiguous runs of set bits from
"""
end = 0
while 1:
start = bits.next_set( end )
if start == bits.size: break
end = bits.next_clear( start )
yield end - start | python | def interval_lengths( bits ):
end = 0
while 1:
start = bits.next_set( end )
if start == bits.size: break
end = bits.next_clear( start )
yield end - start | [
"def",
"interval_lengths",
"(",
"bits",
")",
":",
"end",
"=",
"0",
"while",
"1",
":",
"start",
"=",
"bits",
".",
"next_set",
"(",
"end",
")",
"if",
"start",
"==",
"bits",
".",
"size",
":",
"break",
"end",
"=",
"bits",
".",
"next_clear",
"(",
"start... | Get the length distribution of all contiguous runs of set bits from | [
"Get",
"the",
"length",
"distribution",
"of",
"all",
"contiguous",
"runs",
"of",
"set",
"bits",
"from"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L67-L76 |
20,350 | bxlab/bx-python | scripts/bed_rand_intersect.py | count_overlap | def count_overlap( bits1, bits2 ):
"""
Count the number of bits that overlap between two sets
"""
b = BitSet( bits1.size )
b |= bits1
b &= bits2
return b.count_range( 0, b.size ) | python | def count_overlap( bits1, bits2 ):
b = BitSet( bits1.size )
b |= bits1
b &= bits2
return b.count_range( 0, b.size ) | [
"def",
"count_overlap",
"(",
"bits1",
",",
"bits2",
")",
":",
"b",
"=",
"BitSet",
"(",
"bits1",
".",
"size",
")",
"b",
"|=",
"bits1",
"b",
"&=",
"bits2",
"return",
"b",
".",
"count_range",
"(",
"0",
",",
"b",
".",
"size",
")"
] | Count the number of bits that overlap between two sets | [
"Count",
"the",
"number",
"of",
"bits",
"that",
"overlap",
"between",
"two",
"sets"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L78-L85 |
20,351 | bxlab/bx-python | scripts/bed_rand_intersect.py | overlapping_in_bed | def overlapping_in_bed( fname, r_chr, r_start, r_stop ):
"""
Get from a bed all intervals that overlap the region defined by
r_chr, r_start, r_stop.
"""
rval = []
for line in open( fname ):
if line.startswith( "#" ) or line.startswith( "track" ):
continue
fields = line.split()
chr, start, stop = fields[0], int( fields[1] ), int( fields[2] )
if chr == r_chr and start < r_stop and stop >= r_start:
rval.append( ( chr, max( start, r_start ), min( stop, r_stop ) ) )
return rval | python | def overlapping_in_bed( fname, r_chr, r_start, r_stop ):
rval = []
for line in open( fname ):
if line.startswith( "#" ) or line.startswith( "track" ):
continue
fields = line.split()
chr, start, stop = fields[0], int( fields[1] ), int( fields[2] )
if chr == r_chr and start < r_stop and stop >= r_start:
rval.append( ( chr, max( start, r_start ), min( stop, r_stop ) ) )
return rval | [
"def",
"overlapping_in_bed",
"(",
"fname",
",",
"r_chr",
",",
"r_start",
",",
"r_stop",
")",
":",
"rval",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"fname",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
"or",
"line",
".",
"st... | Get from a bed all intervals that overlap the region defined by
r_chr, r_start, r_stop. | [
"Get",
"from",
"a",
"bed",
"all",
"intervals",
"that",
"overlap",
"the",
"region",
"defined",
"by",
"r_chr",
"r_start",
"r_stop",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_rand_intersect.py#L87-L100 |
20,352 | bxlab/bx-python | lib/bx/align/tools/tile.py | tile_interval | def tile_interval( sources, index, ref_src, start, end, seq_db=None ):
"""
Tile maf blocks onto an interval. The resulting block will span the interval
exactly and contain the column from the highest scoring alignment at each
position.
`sources`: list of sequence source names to include in final block
`index`: an instnace that can return maf blocks overlapping intervals
`ref_src`: source name of the interval (ie, hg17.chr7)
`start`: start of interval
`end`: end of interval
`seq_db`: a mapping for source names in the reference species to nib files
"""
# First entry in sources should also be on the reference species
assert sources[0].split('.')[0] == ref_src.split('.')[0], \
"%s != %s" % ( sources[0].split('.')[0], ref_src.split('.')[0] )
base_len = end - start
blocks = index.get( ref_src, start, end )
# From low to high score
blocks.sort(key=lambda t: t.score)
mask = [ -1 ] * base_len
ref_src_size = None
for i, block in enumerate( blocks ):
ref = block.get_component_by_src_start( ref_src )
ref_src_size = ref.src_size
assert ref.strand == "+"
slice_start = max( start, ref.start )
slice_end = min( end, ref.end )
for j in range( slice_start, slice_end ):
mask[j-start] = i
tiled = []
for i in range( len( sources ) ):
tiled.append( [] )
for ss, ee, index in intervals_from_mask( mask ):
# Interval with no covering alignments
if index < 0:
# Get sequence if available, otherwise just use 'N'
if seq_db:
tiled[0].append( bx.seq.nib.NibFile( open( seq_db[ ref_src ] ) ).get( start+ss, ee-ss ) )
else:
tiled[0].append( "N" * (ee-ss) )
# Gaps in all other species
for row in tiled[1:]:
row.append( "-" * ( ee - ss ) )
else:
slice_start = start + ss
slice_end = start + ee
block = blocks[index]
ref = block.get_component_by_src_start( ref_src )
sliced = block.slice_by_component( ref, slice_start, slice_end )
sliced = sliced.limit_to_species( sources )
sliced.remove_all_gap_columns()
for i, src in enumerate( sources ):
comp = sliced.get_component_by_src_start( src )
if comp:
tiled[i].append( comp.text )
else:
tiled[i].append( "-" * sliced.text_size )
return [ "".join( t ) for t in tiled ] | python | def tile_interval( sources, index, ref_src, start, end, seq_db=None ):
# First entry in sources should also be on the reference species
assert sources[0].split('.')[0] == ref_src.split('.')[0], \
"%s != %s" % ( sources[0].split('.')[0], ref_src.split('.')[0] )
base_len = end - start
blocks = index.get( ref_src, start, end )
# From low to high score
blocks.sort(key=lambda t: t.score)
mask = [ -1 ] * base_len
ref_src_size = None
for i, block in enumerate( blocks ):
ref = block.get_component_by_src_start( ref_src )
ref_src_size = ref.src_size
assert ref.strand == "+"
slice_start = max( start, ref.start )
slice_end = min( end, ref.end )
for j in range( slice_start, slice_end ):
mask[j-start] = i
tiled = []
for i in range( len( sources ) ):
tiled.append( [] )
for ss, ee, index in intervals_from_mask( mask ):
# Interval with no covering alignments
if index < 0:
# Get sequence if available, otherwise just use 'N'
if seq_db:
tiled[0].append( bx.seq.nib.NibFile( open( seq_db[ ref_src ] ) ).get( start+ss, ee-ss ) )
else:
tiled[0].append( "N" * (ee-ss) )
# Gaps in all other species
for row in tiled[1:]:
row.append( "-" * ( ee - ss ) )
else:
slice_start = start + ss
slice_end = start + ee
block = blocks[index]
ref = block.get_component_by_src_start( ref_src )
sliced = block.slice_by_component( ref, slice_start, slice_end )
sliced = sliced.limit_to_species( sources )
sliced.remove_all_gap_columns()
for i, src in enumerate( sources ):
comp = sliced.get_component_by_src_start( src )
if comp:
tiled[i].append( comp.text )
else:
tiled[i].append( "-" * sliced.text_size )
return [ "".join( t ) for t in tiled ] | [
"def",
"tile_interval",
"(",
"sources",
",",
"index",
",",
"ref_src",
",",
"start",
",",
"end",
",",
"seq_db",
"=",
"None",
")",
":",
"# First entry in sources should also be on the reference species",
"assert",
"sources",
"[",
"0",
"]",
".",
"split",
"(",
"'.'"... | Tile maf blocks onto an interval. The resulting block will span the interval
exactly and contain the column from the highest scoring alignment at each
position.
`sources`: list of sequence source names to include in final block
`index`: an instnace that can return maf blocks overlapping intervals
`ref_src`: source name of the interval (ie, hg17.chr7)
`start`: start of interval
`end`: end of interval
`seq_db`: a mapping for source names in the reference species to nib files | [
"Tile",
"maf",
"blocks",
"onto",
"an",
"interval",
".",
"The",
"resulting",
"block",
"will",
"span",
"the",
"interval",
"exactly",
"and",
"contain",
"the",
"column",
"from",
"the",
"highest",
"scoring",
"alignment",
"at",
"each",
"position",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/tile.py#L13-L71 |
20,353 | bxlab/bx-python | scripts/maf_tile_2bit.py | get_fill_char | def get_fill_char( maf_status ):
"""
Return the character that should be used to fill between blocks
having a given status
"""
## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS,
## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \
## "Nested rows do not make sense in a single coverage MAF (or do they?)"
if maf_status in ( maf.MAF_NEW_STATUS, maf.MAF_MAYBE_NEW_STATUS,
maf.MAF_NEW_NESTED_STATUS, maf.MAF_MAYBE_NEW_NESTED_STATUS ):
return "*"
elif maf_status in ( maf.MAF_INVERSE_STATUS, maf.MAF_INSERT_STATUS ):
return "="
elif maf_status in ( maf.MAF_CONTIG_STATUS, maf.MAF_CONTIG_NESTED_STATUS ):
return "#"
elif maf_status == maf.MAF_MISSING_STATUS:
return "X"
else:
raise ValueError("Unknwon maf status") | python | def get_fill_char( maf_status ):
## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS,
## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \
## "Nested rows do not make sense in a single coverage MAF (or do they?)"
if maf_status in ( maf.MAF_NEW_STATUS, maf.MAF_MAYBE_NEW_STATUS,
maf.MAF_NEW_NESTED_STATUS, maf.MAF_MAYBE_NEW_NESTED_STATUS ):
return "*"
elif maf_status in ( maf.MAF_INVERSE_STATUS, maf.MAF_INSERT_STATUS ):
return "="
elif maf_status in ( maf.MAF_CONTIG_STATUS, maf.MAF_CONTIG_NESTED_STATUS ):
return "#"
elif maf_status == maf.MAF_MISSING_STATUS:
return "X"
else:
raise ValueError("Unknwon maf status") | [
"def",
"get_fill_char",
"(",
"maf_status",
")",
":",
"## assert maf_status not in ( maf.MAF_CONTIG_NESTED_STATUS, maf.MAF_NEW_NESTED_STATUS, ",
"## maf.MAF_MAYBE_NEW_NESTED_STATUS ), \\",
"## \"Nested rows do not make sense in a single coverage MAF (or do they?)\"",
... | Return the character that should be used to fill between blocks
having a given status | [
"Return",
"the",
"character",
"that",
"should",
"be",
"used",
"to",
"fill",
"between",
"blocks",
"having",
"a",
"given",
"status"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2bit.py#L72-L90 |
20,354 | bxlab/bx-python | scripts/maf_tile_2bit.py | guess_fill_char | def guess_fill_char( left_comp, right_comp ):
"""
For the case where there is no annotated synteny we will try to guess it
"""
# No left component, obiously new
return "*"
# First check that the blocks have the same src (not just species) and
# orientation
if ( left_comp.src == right_comp.src and left_comp.strand != right_comp.strand ):
# Are they completely contiguous? Easy to call that a gap
if left_comp.end == right_comp.start:
return "-"
# TODO: should be able to make some guesses about short insertions
# here
# All other cases we have no clue about
return "*" | python | def guess_fill_char( left_comp, right_comp ):
# No left component, obiously new
return "*"
# First check that the blocks have the same src (not just species) and
# orientation
if ( left_comp.src == right_comp.src and left_comp.strand != right_comp.strand ):
# Are they completely contiguous? Easy to call that a gap
if left_comp.end == right_comp.start:
return "-"
# TODO: should be able to make some guesses about short insertions
# here
# All other cases we have no clue about
return "*" | [
"def",
"guess_fill_char",
"(",
"left_comp",
",",
"right_comp",
")",
":",
"# No left component, obiously new",
"return",
"\"*\"",
"# First check that the blocks have the same src (not just species) and ",
"# orientation",
"if",
"(",
"left_comp",
".",
"src",
"==",
"right_comp",
... | For the case where there is no annotated synteny we will try to guess it | [
"For",
"the",
"case",
"where",
"there",
"is",
"no",
"annotated",
"synteny",
"we",
"will",
"try",
"to",
"guess",
"it"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2bit.py#L92-L107 |
20,355 | bxlab/bx-python | scripts/maf_tile_2bit.py | remove_all_gap_columns | def remove_all_gap_columns( texts ):
"""
Remove any columns containing only gaps from alignment texts
"""
seqs = [ list( t ) for t in texts ]
i = 0
text_size = len( texts[0] )
while i < text_size:
all_gap = True
for seq in seqs:
if seq[i] not in ( '-', '#', '*', '=', 'X', '@' ):
all_gap = False
if all_gap:
for seq in seqs:
del seq[i]
text_size -= 1
else:
i += 1
return [ ''.join( s ) for s in seqs ] | python | def remove_all_gap_columns( texts ):
seqs = [ list( t ) for t in texts ]
i = 0
text_size = len( texts[0] )
while i < text_size:
all_gap = True
for seq in seqs:
if seq[i] not in ( '-', '#', '*', '=', 'X', '@' ):
all_gap = False
if all_gap:
for seq in seqs:
del seq[i]
text_size -= 1
else:
i += 1
return [ ''.join( s ) for s in seqs ] | [
"def",
"remove_all_gap_columns",
"(",
"texts",
")",
":",
"seqs",
"=",
"[",
"list",
"(",
"t",
")",
"for",
"t",
"in",
"texts",
"]",
"i",
"=",
"0",
"text_size",
"=",
"len",
"(",
"texts",
"[",
"0",
"]",
")",
"while",
"i",
"<",
"text_size",
":",
"all_... | Remove any columns containing only gaps from alignment texts | [
"Remove",
"any",
"columns",
"containing",
"only",
"gaps",
"from",
"alignment",
"texts"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2bit.py#L109-L127 |
20,356 | bxlab/bx-python | lib/bx/cookbook/__init__.py | cross_lists | def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
break
except StopIteration:
wheels[i] = iter(sets[i])
digits[i] = next(wheels[i])
else:
break | python | def cross_lists(*sets):
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
break
except StopIteration:
wheels[i] = iter(sets[i])
digits[i] = next(wheels[i])
else:
break | [
"def",
"cross_lists",
"(",
"*",
"sets",
")",
":",
"wheels",
"=",
"[",
"iter",
"(",
"_",
")",
"for",
"_",
"in",
"sets",
"]",
"digits",
"=",
"[",
"next",
"(",
"it",
")",
"for",
"it",
"in",
"wheels",
"]",
"while",
"True",
":",
"yield",
"digits",
"... | Return the cross product of the arguments | [
"Return",
"the",
"cross",
"product",
"of",
"the",
"arguments"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/cookbook/__init__.py#L16-L30 |
20,357 | bxlab/bx-python | lib/bx/misc/readlengths.py | read_lengths_file | def read_lengths_file( name ):
"""
Returns a hash from sequence name to length.
"""
chrom_to_length = {}
f = file ( name, "rt" )
for line in f:
line = line.strip()
if line == '' or line[0] == '#': continue
try:
fields = line.split()
if len(fields) != 2: raise
chrom = fields[0]
length = int( fields[1] )
except:
raise ValueError("bad length file line: %s" % line)
if chrom in chrom_to_length and length != chrom_to_length[chrom]:
raise ValueError("%s has more than one length!" % chrom)
chrom_to_length[chrom] = length
f.close()
return chrom_to_length | python | def read_lengths_file( name ):
chrom_to_length = {}
f = file ( name, "rt" )
for line in f:
line = line.strip()
if line == '' or line[0] == '#': continue
try:
fields = line.split()
if len(fields) != 2: raise
chrom = fields[0]
length = int( fields[1] )
except:
raise ValueError("bad length file line: %s" % line)
if chrom in chrom_to_length and length != chrom_to_length[chrom]:
raise ValueError("%s has more than one length!" % chrom)
chrom_to_length[chrom] = length
f.close()
return chrom_to_length | [
"def",
"read_lengths_file",
"(",
"name",
")",
":",
"chrom_to_length",
"=",
"{",
"}",
"f",
"=",
"file",
"(",
"name",
",",
"\"rt\"",
")",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"==",
"''",
"or",
"l... | Returns a hash from sequence name to length. | [
"Returns",
"a",
"hash",
"from",
"sequence",
"name",
"to",
"length",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/readlengths.py#L7-L28 |
20,358 | bxlab/bx-python | lib/bx/wiggle.py | IntervalReader | def IntervalReader( f ):
"""
Iterator yielding chrom, start, end, strand, value.
Values are zero-based, half-open.
Regions which lack a score are ignored.
"""
current_chrom = None
current_pos = None
current_step = None
# always for wiggle data
strand = '+'
mode = "bed"
for line in f:
if line.isspace() or line.startswith( "track" ) or line.startswith( "#" ) or line.startswith( "browser" ):
continue
elif line.startswith( "variableStep" ):
header = parse_header( line )
current_chrom = header['chrom']
current_pos = None
current_step = None
if 'span' in header: current_span = int( header['span'] )
else: current_span = 1
mode = "variableStep"
elif line.startswith( "fixedStep" ):
header = parse_header( line )
current_chrom = header['chrom']
current_pos = int( header['start'] ) - 1
current_step = int( header['step'] )
if 'span' in header: current_span = int( header['span'] )
else: current_span = 1
mode = "fixedStep"
elif mode == "bed":
fields = line.split()
if len( fields ) > 3:
if len( fields ) > 5:
yield fields[0], int( fields[1] ), int( fields[2] ), fields[5], float( fields[3] )
else:
yield fields[0], int( fields[1] ), int( fields[2] ), strand, float( fields[3] )
elif mode == "variableStep":
fields = line.split()
pos = int( fields[0] ) - 1
yield current_chrom, pos, pos + current_span, strand, float( fields[1] )
elif mode == "fixedStep":
yield current_chrom, current_pos, current_pos + current_span, strand, float( line.split()[0] )
current_pos += current_step
else:
raise ValueError("Unexpected input line: %s" % line.strip()) | python | def IntervalReader( f ):
current_chrom = None
current_pos = None
current_step = None
# always for wiggle data
strand = '+'
mode = "bed"
for line in f:
if line.isspace() or line.startswith( "track" ) or line.startswith( "#" ) or line.startswith( "browser" ):
continue
elif line.startswith( "variableStep" ):
header = parse_header( line )
current_chrom = header['chrom']
current_pos = None
current_step = None
if 'span' in header: current_span = int( header['span'] )
else: current_span = 1
mode = "variableStep"
elif line.startswith( "fixedStep" ):
header = parse_header( line )
current_chrom = header['chrom']
current_pos = int( header['start'] ) - 1
current_step = int( header['step'] )
if 'span' in header: current_span = int( header['span'] )
else: current_span = 1
mode = "fixedStep"
elif mode == "bed":
fields = line.split()
if len( fields ) > 3:
if len( fields ) > 5:
yield fields[0], int( fields[1] ), int( fields[2] ), fields[5], float( fields[3] )
else:
yield fields[0], int( fields[1] ), int( fields[2] ), strand, float( fields[3] )
elif mode == "variableStep":
fields = line.split()
pos = int( fields[0] ) - 1
yield current_chrom, pos, pos + current_span, strand, float( fields[1] )
elif mode == "fixedStep":
yield current_chrom, current_pos, current_pos + current_span, strand, float( line.split()[0] )
current_pos += current_step
else:
raise ValueError("Unexpected input line: %s" % line.strip()) | [
"def",
"IntervalReader",
"(",
"f",
")",
":",
"current_chrom",
"=",
"None",
"current_pos",
"=",
"None",
"current_step",
"=",
"None",
"# always for wiggle data",
"strand",
"=",
"'+'",
"mode",
"=",
"\"bed\"",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
... | Iterator yielding chrom, start, end, strand, value.
Values are zero-based, half-open.
Regions which lack a score are ignored. | [
"Iterator",
"yielding",
"chrom",
"start",
"end",
"strand",
"value",
".",
"Values",
"are",
"zero",
"-",
"based",
"half",
"-",
"open",
".",
"Regions",
"which",
"lack",
"a",
"score",
"are",
"ignored",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/wiggle.py#L14-L63 |
20,359 | bxlab/bx-python | lib/bx/align/tools/fuse.py | fuse_list | def fuse_list( mafs ):
"""
Try to fuse a list of blocks by progressively fusing each adjacent pair.
"""
last = None
for m in mafs:
if last is None:
last = m
else:
fused = fuse( last, m )
if fused:
last = fused
else:
yield last
last = m
if last:
yield last | python | def fuse_list( mafs ):
last = None
for m in mafs:
if last is None:
last = m
else:
fused = fuse( last, m )
if fused:
last = fused
else:
yield last
last = m
if last:
yield last | [
"def",
"fuse_list",
"(",
"mafs",
")",
":",
"last",
"=",
"None",
"for",
"m",
"in",
"mafs",
":",
"if",
"last",
"is",
"None",
":",
"last",
"=",
"m",
"else",
":",
"fused",
"=",
"fuse",
"(",
"last",
",",
"m",
")",
"if",
"fused",
":",
"last",
"=",
... | Try to fuse a list of blocks by progressively fusing each adjacent pair. | [
"Try",
"to",
"fuse",
"a",
"list",
"of",
"blocks",
"by",
"progressively",
"fusing",
"each",
"adjacent",
"pair",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/tools/fuse.py#L8-L24 |
20,360 | bxlab/bx-python | lib/bx_extras/pyparsing.py | ParserElement.setBreak | def setBreak(self,breakFlag = True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set breakFlag to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doActions=True, callPreParse=True):
import pdb
pdb.set_trace()
_parseMethod( instring, loc, doActions, callPreParse )
breaker._originalParseMethod = _parseMethod
self._parse = breaker
else:
if hasattr(self._parse,"_originalParseMethod"):
self._parse = self._parse._originalParseMethod
return self | python | def setBreak(self,breakFlag = True):
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doActions=True, callPreParse=True):
import pdb
pdb.set_trace()
_parseMethod( instring, loc, doActions, callPreParse )
breaker._originalParseMethod = _parseMethod
self._parse = breaker
else:
if hasattr(self._parse,"_originalParseMethod"):
self._parse = self._parse._originalParseMethod
return self | [
"def",
"setBreak",
"(",
"self",
",",
"breakFlag",
"=",
"True",
")",
":",
"if",
"breakFlag",
":",
"_parseMethod",
"=",
"self",
".",
"_parse",
"def",
"breaker",
"(",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
",",
"callPreParse",
"=",
"True",
... | Method to invoke the Python pdb debugger when this element is
about to be parsed. Set breakFlag to True to enable, False to
disable. | [
"Method",
"to",
"invoke",
"the",
"Python",
"pdb",
"debugger",
"when",
"this",
"element",
"is",
"about",
"to",
"be",
"parsed",
".",
"Set",
"breakFlag",
"to",
"True",
"to",
"enable",
"False",
"to",
"disable",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pyparsing.py#L709-L725 |
20,361 | bxlab/bx-python | lib/bx_extras/pyparsing.py | ParserElement.searchString | def searchString( self, instring, maxMatches=_MAX_INT ):
"""Another extension to scanString, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
maxMatches argument, to clip searching after 'n' matches are found.
"""
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) | python | def searchString( self, instring, maxMatches=_MAX_INT ):
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) | [
"def",
"searchString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
")",
":",
"return",
"ParseResults",
"(",
"[",
"t",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",
")",
"]",
... | Another extension to scanString, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
maxMatches argument, to clip searching after 'n' matches are found. | [
"Another",
"extension",
"to",
"scanString",
"simplifying",
"the",
"access",
"to",
"the",
"tokens",
"found",
"to",
"match",
"the",
"given",
"parse",
"expression",
".",
"May",
"be",
"called",
"with",
"optional",
"maxMatches",
"argument",
"to",
"clip",
"searching",... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pyparsing.py#L1111-L1116 |
20,362 | bxlab/bx-python | lib/bx/align/epo.py | Chain._strfactory | def _strfactory(cls, line):
"""factory class method for Chain
:param line: header of a chain (in .chain format)
"""
assert type(line) == str, "this is a factory from string"
line = line.rstrip().split()[1:] # the first component is the keyword "chain"
tup = [t[0](t[1]) for t in zip([int, str, int, str, int, int, str, int, str, int, int, str], line)]
return tuple.__new__(cls, tup) | python | def _strfactory(cls, line):
assert type(line) == str, "this is a factory from string"
line = line.rstrip().split()[1:] # the first component is the keyword "chain"
tup = [t[0](t[1]) for t in zip([int, str, int, str, int, int, str, int, str, int, int, str], line)]
return tuple.__new__(cls, tup) | [
"def",
"_strfactory",
"(",
"cls",
",",
"line",
")",
":",
"assert",
"type",
"(",
"line",
")",
"==",
"str",
",",
"\"this is a factory from string\"",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
")",
"[",
"1",
":",
"]",
"# the first c... | factory class method for Chain
:param line: header of a chain (in .chain format) | [
"factory",
"class",
"method",
"for",
"Chain"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/epo.py#L30-L40 |
20,363 | bxlab/bx-python | lib/bx/align/epo.py | Chain.bedInterval | def bedInterval(self, who):
"return a BED6 entry, thus DOES coordinate conversion for minus strands"
if who == 't':
st, en = self.tStart, self.tEnd
if self.tStrand == '-':
st, en = self.tSize-en, self.tSize-st
return (self.tName, st, en, self.id, self.score, self.tStrand)
else:
st, en = self.qStart, self.qEnd
if self.qStrand == '-':
st, en = self.qSize-en, self.qSize-st
assert en-st == self.qEnd - self.qStart
return (self.qName, st, en, self.id, self.score, self.qStrand) | python | def bedInterval(self, who):
"return a BED6 entry, thus DOES coordinate conversion for minus strands"
if who == 't':
st, en = self.tStart, self.tEnd
if self.tStrand == '-':
st, en = self.tSize-en, self.tSize-st
return (self.tName, st, en, self.id, self.score, self.tStrand)
else:
st, en = self.qStart, self.qEnd
if self.qStrand == '-':
st, en = self.qSize-en, self.qSize-st
assert en-st == self.qEnd - self.qStart
return (self.qName, st, en, self.id, self.score, self.qStrand) | [
"def",
"bedInterval",
"(",
"self",
",",
"who",
")",
":",
"if",
"who",
"==",
"'t'",
":",
"st",
",",
"en",
"=",
"self",
".",
"tStart",
",",
"self",
".",
"tEnd",
"if",
"self",
".",
"tStrand",
"==",
"'-'",
":",
"st",
",",
"en",
"=",
"self",
".",
... | return a BED6 entry, thus DOES coordinate conversion for minus strands | [
"return",
"a",
"BED6",
"entry",
"thus",
"DOES",
"coordinate",
"conversion",
"for",
"minus",
"strands"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/epo.py#L135-L148 |
20,364 | bxlab/bx-python | lib/bx/align/epo.py | EPOitem._strfactory | def _strfactory(cls, line):
"""factory method for an EPOitem
:param line: a line of input"""
cmp = line.rstrip().split()
chrom = cmp[2]
if not chrom.startswith("chr"):
chrom = "chr%s" % chrom
instance = tuple.__new__(cls,
(cmp[0], cmp[1],
chrom, int(cmp[3]), int(cmp[4]),
{'1' : '+', '-1' : '-'}[cmp[5]], cmp[6]))
span = instance.end - instance.start + 1
m_num = sum( (t[1] == "M" and [t[0]] or [0])[0] for t in instance.cigar_iter(False) )
if span != m_num:
log.warning("[{gabid}] {species}.{chrom}:{start}-{end}.".format(**instance._asdict()) + "(span) %d != %d (matches)" % (span, m_num))
return None
return instance | python | def _strfactory(cls, line):
cmp = line.rstrip().split()
chrom = cmp[2]
if not chrom.startswith("chr"):
chrom = "chr%s" % chrom
instance = tuple.__new__(cls,
(cmp[0], cmp[1],
chrom, int(cmp[3]), int(cmp[4]),
{'1' : '+', '-1' : '-'}[cmp[5]], cmp[6]))
span = instance.end - instance.start + 1
m_num = sum( (t[1] == "M" and [t[0]] or [0])[0] for t in instance.cigar_iter(False) )
if span != m_num:
log.warning("[{gabid}] {species}.{chrom}:{start}-{end}.".format(**instance._asdict()) + "(span) %d != %d (matches)" % (span, m_num))
return None
return instance | [
"def",
"_strfactory",
"(",
"cls",
",",
"line",
")",
":",
"cmp",
"=",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
")",
"chrom",
"=",
"cmp",
"[",
"2",
"]",
"if",
"not",
"chrom",
".",
"startswith",
"(",
"\"chr\"",
")",
":",
"chrom",
"=",
"... | factory method for an EPOitem
:param line: a line of input | [
"factory",
"method",
"for",
"an",
"EPOitem"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/epo.py#L192-L210 |
20,365 | bxlab/bx-python | lib/bx/bitset_builders.py | binned_bitsets_proximity | def binned_bitsets_proximity( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0 ):
"""Read a file into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
for line in f:
if line.startswith("#"): continue
# print "input=%s" % ( line ),
fields = line.split()
strand = "+"
if len(fields) >= strand_col + 1:
if fields[strand_col] == "-": strand = "-"
chrom = fields[chrom_col]
if chrom != last_chrom:
if chrom not in bitsets:
bitsets[chrom] = BinnedBitSet( MAX )
last_chrom = chrom
last_bitset = bitsets[chrom]
start, end = int( fields[start_col] ), int( fields[end_col] )
if strand == "+":
if upstream: start = max( 0, start - upstream )
if downstream: end = min( MAX, end + downstream )
if strand == "-":
if upstream: end = min( MAX, end + upstream )
if downstream: start = max( 0, start - downstream )
# print "set: start=%d\tend=%d" % ( start, end )
if end-start > 0:
last_bitset.set_range( start, end-start )
return bitsets | python | def binned_bitsets_proximity( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0 ):
last_chrom = None
last_bitset = None
bitsets = dict()
for line in f:
if line.startswith("#"): continue
# print "input=%s" % ( line ),
fields = line.split()
strand = "+"
if len(fields) >= strand_col + 1:
if fields[strand_col] == "-": strand = "-"
chrom = fields[chrom_col]
if chrom != last_chrom:
if chrom not in bitsets:
bitsets[chrom] = BinnedBitSet( MAX )
last_chrom = chrom
last_bitset = bitsets[chrom]
start, end = int( fields[start_col] ), int( fields[end_col] )
if strand == "+":
if upstream: start = max( 0, start - upstream )
if downstream: end = min( MAX, end + downstream )
if strand == "-":
if upstream: end = min( MAX, end + upstream )
if downstream: start = max( 0, start - downstream )
# print "set: start=%d\tend=%d" % ( start, end )
if end-start > 0:
last_bitset.set_range( start, end-start )
return bitsets | [
"def",
"binned_bitsets_proximity",
"(",
"f",
",",
"chrom_col",
"=",
"0",
",",
"start_col",
"=",
"1",
",",
"end_col",
"=",
"2",
",",
"strand_col",
"=",
"5",
",",
"upstream",
"=",
"0",
",",
"downstream",
"=",
"0",
")",
":",
"last_chrom",
"=",
"None",
"... | Read a file into a dictionary of bitsets | [
"Read",
"a",
"file",
"into",
"a",
"dictionary",
"of",
"bitsets"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/bitset_builders.py#L100-L128 |
20,366 | bxlab/bx-python | lib/bx/bitset_builders.py | binned_bitsets_from_list | def binned_bitsets_from_list( list=[] ):
"""Read a list into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
for l in list:
chrom = l[0]
if chrom != last_chrom:
if chrom not in bitsets:
bitsets[chrom] = BinnedBitSet(MAX)
last_chrom = chrom
last_bitset = bitsets[chrom]
start, end = int( l[1] ), int( l[2] )
last_bitset.set_range( start, end - start )
return bitsets | python | def binned_bitsets_from_list( list=[] ):
last_chrom = None
last_bitset = None
bitsets = dict()
for l in list:
chrom = l[0]
if chrom != last_chrom:
if chrom not in bitsets:
bitsets[chrom] = BinnedBitSet(MAX)
last_chrom = chrom
last_bitset = bitsets[chrom]
start, end = int( l[1] ), int( l[2] )
last_bitset.set_range( start, end - start )
return bitsets | [
"def",
"binned_bitsets_from_list",
"(",
"list",
"=",
"[",
"]",
")",
":",
"last_chrom",
"=",
"None",
"last_bitset",
"=",
"None",
"bitsets",
"=",
"dict",
"(",
")",
"for",
"l",
"in",
"list",
":",
"chrom",
"=",
"l",
"[",
"0",
"]",
"if",
"chrom",
"!=",
... | Read a list into a dictionary of bitsets | [
"Read",
"a",
"list",
"into",
"a",
"dictionary",
"of",
"bitsets"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/bitset_builders.py#L130-L144 |
20,367 | bxlab/bx-python | lib/bx/bitset_builders.py | binned_bitsets_by_chrom | def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
"""Read a file by chrom name into a bitset"""
bitset = BinnedBitSet( MAX )
for line in f:
if line.startswith("#"): continue
fields = line.split()
if fields[chrom_col] == chrom:
start, end = int( fields[start_col] ), int( fields[end_col] )
bitset.set_range( start, end-start )
return bitset | python | def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
bitset = BinnedBitSet( MAX )
for line in f:
if line.startswith("#"): continue
fields = line.split()
if fields[chrom_col] == chrom:
start, end = int( fields[start_col] ), int( fields[end_col] )
bitset.set_range( start, end-start )
return bitset | [
"def",
"binned_bitsets_by_chrom",
"(",
"f",
",",
"chrom",
",",
"chrom_col",
"=",
"0",
",",
"start_col",
"=",
"1",
",",
"end_col",
"=",
"2",
")",
":",
"bitset",
"=",
"BinnedBitSet",
"(",
"MAX",
")",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
... | Read a file by chrom name into a bitset | [
"Read",
"a",
"file",
"by",
"chrom",
"name",
"into",
"a",
"bitset"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/bitset_builders.py#L146-L155 |
20,368 | bxlab/bx-python | lib/bx_extras/fpconst.py | _double_as_bytes | def _double_as_bytes(dval):
"Use struct.unpack to decode a double precision float into eight bytes"
tmp = list(struct.unpack('8B',struct.pack('d', dval)))
if not _big_endian:
tmp.reverse()
return tmp | python | def _double_as_bytes(dval):
"Use struct.unpack to decode a double precision float into eight bytes"
tmp = list(struct.unpack('8B',struct.pack('d', dval)))
if not _big_endian:
tmp.reverse()
return tmp | [
"def",
"_double_as_bytes",
"(",
"dval",
")",
":",
"tmp",
"=",
"list",
"(",
"struct",
".",
"unpack",
"(",
"'8B'",
",",
"struct",
".",
"pack",
"(",
"'d'",
",",
"dval",
")",
")",
")",
"if",
"not",
"_big_endian",
":",
"tmp",
".",
"reverse",
"(",
")",
... | Use struct.unpack to decode a double precision float into eight bytes | [
"Use",
"struct",
".",
"unpack",
"to",
"decode",
"a",
"double",
"precision",
"float",
"into",
"eight",
"bytes"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/fpconst.py#L45-L50 |
20,369 | bxlab/bx-python | lib/bx_extras/fpconst.py | _mantissa | def _mantissa(dval):
"""Extract the _mantissa bits from a double-precision floating
point value."""
bb = _double_as_bytes(dval)
mantissa = bb[1] & 0x0f << 48
mantissa += bb[2] << 40
mantissa += bb[3] << 32
mantissa += bb[4]
return mantissa | python | def _mantissa(dval):
bb = _double_as_bytes(dval)
mantissa = bb[1] & 0x0f << 48
mantissa += bb[2] << 40
mantissa += bb[3] << 32
mantissa += bb[4]
return mantissa | [
"def",
"_mantissa",
"(",
"dval",
")",
":",
"bb",
"=",
"_double_as_bytes",
"(",
"dval",
")",
"mantissa",
"=",
"bb",
"[",
"1",
"]",
"&",
"0x0f",
"<<",
"48",
"mantissa",
"+=",
"bb",
"[",
"2",
"]",
"<<",
"40",
"mantissa",
"+=",
"bb",
"[",
"3",
"]",
... | Extract the _mantissa bits from a double-precision floating
point value. | [
"Extract",
"the",
"_mantissa",
"bits",
"from",
"a",
"double",
"-",
"precision",
"floating",
"point",
"value",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/fpconst.py#L72-L81 |
20,370 | bxlab/bx-python | lib/bx_extras/fpconst.py | _zero_mantissa | def _zero_mantissa(dval):
"""Determine whether the mantissa bits of the given double are all
zero."""
bb = _double_as_bytes(dval)
return ((bb[1] & 0x0f) | reduce(operator.or_, bb[2:])) == 0 | python | def _zero_mantissa(dval):
bb = _double_as_bytes(dval)
return ((bb[1] & 0x0f) | reduce(operator.or_, bb[2:])) == 0 | [
"def",
"_zero_mantissa",
"(",
"dval",
")",
":",
"bb",
"=",
"_double_as_bytes",
"(",
"dval",
")",
"return",
"(",
"(",
"bb",
"[",
"1",
"]",
"&",
"0x0f",
")",
"|",
"reduce",
"(",
"operator",
".",
"or_",
",",
"bb",
"[",
"2",
":",
"]",
")",
")",
"==... | Determine whether the mantissa bits of the given double are all
zero. | [
"Determine",
"whether",
"the",
"mantissa",
"bits",
"of",
"the",
"given",
"double",
"are",
"all",
"zero",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/fpconst.py#L83-L87 |
20,371 | bxlab/bx-python | scripts/aggregate_scores_in_intervals.py | load_scores_wiggle | def load_scores_wiggle( fname ):
"""
Read a wiggle file and return a dict of BinnedArray objects keyed
by chromosome.
"""
scores_by_chrom = dict()
for chrom, pos, val in bx.wiggle.Reader( misc.open_compressed( fname ) ):
if chrom not in scores_by_chrom:
scores_by_chrom[chrom] = BinnedArray()
scores_by_chrom[chrom][pos] = val
return scores_by_chrom | python | def load_scores_wiggle( fname ):
scores_by_chrom = dict()
for chrom, pos, val in bx.wiggle.Reader( misc.open_compressed( fname ) ):
if chrom not in scores_by_chrom:
scores_by_chrom[chrom] = BinnedArray()
scores_by_chrom[chrom][pos] = val
return scores_by_chrom | [
"def",
"load_scores_wiggle",
"(",
"fname",
")",
":",
"scores_by_chrom",
"=",
"dict",
"(",
")",
"for",
"chrom",
",",
"pos",
",",
"val",
"in",
"bx",
".",
"wiggle",
".",
"Reader",
"(",
"misc",
".",
"open_compressed",
"(",
"fname",
")",
")",
":",
"if",
"... | Read a wiggle file and return a dict of BinnedArray objects keyed
by chromosome. | [
"Read",
"a",
"wiggle",
"file",
"and",
"return",
"a",
"dict",
"of",
"BinnedArray",
"objects",
"keyed",
"by",
"chromosome",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/aggregate_scores_in_intervals.py#L60-L70 |
20,372 | bxlab/bx-python | lib/bx/interval_index_file.py | Index.new | def new( self, min, max ):
"""Create an empty index for intervals in the range min, max"""
# Ensure the range will fit given the shifting strategy
assert MIN <= min <= max <= MAX
self.min = min
self.max = max
# Determine offsets to use
self.offsets = offsets_for_max_size( max )
# Determine the largest bin we will actually use
self.bin_count = bin_for_range( max - 1, max, offsets = self.offsets ) + 1
# Create empty bins
self.bins = [ [] for i in range( self.bin_count ) ] | python | def new( self, min, max ):
# Ensure the range will fit given the shifting strategy
assert MIN <= min <= max <= MAX
self.min = min
self.max = max
# Determine offsets to use
self.offsets = offsets_for_max_size( max )
# Determine the largest bin we will actually use
self.bin_count = bin_for_range( max - 1, max, offsets = self.offsets ) + 1
# Create empty bins
self.bins = [ [] for i in range( self.bin_count ) ] | [
"def",
"new",
"(",
"self",
",",
"min",
",",
"max",
")",
":",
"# Ensure the range will fit given the shifting strategy",
"assert",
"MIN",
"<=",
"min",
"<=",
"max",
"<=",
"MAX",
"self",
".",
"min",
"=",
"min",
"self",
".",
"max",
"=",
"max",
"# Determine offse... | Create an empty index for intervals in the range min, max | [
"Create",
"an",
"empty",
"index",
"for",
"intervals",
"in",
"the",
"range",
"min",
"max"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/interval_index_file.py#L357-L368 |
20,373 | bxlab/bx-python | lib/bx/misc/filecache.py | FileCache.seek | def seek( self, offset, whence=0 ):
"""
Move the file pointer to a particular offset.
"""
# Determine absolute target position
if whence == 0:
target_pos = offset
elif whence == 1:
target_pos = self.file_pos + offset
elif whence == 2:
target_pos = self.size - offset
else:
raise Exception( "Invalid `whence` argument: %r", whence )
# Check if this is a noop
if target_pos == self.file_pos:
return
# Verify it is valid
assert 0 <= target_pos < self.size, "Attempt to seek outside file"
# Move the position
self.file_pos = target_pos
# Mark as dirty, the next time a read is done we need to actually
# move the position in the bzip2 file
self.dirty = True | python | def seek( self, offset, whence=0 ):
# Determine absolute target position
if whence == 0:
target_pos = offset
elif whence == 1:
target_pos = self.file_pos + offset
elif whence == 2:
target_pos = self.size - offset
else:
raise Exception( "Invalid `whence` argument: %r", whence )
# Check if this is a noop
if target_pos == self.file_pos:
return
# Verify it is valid
assert 0 <= target_pos < self.size, "Attempt to seek outside file"
# Move the position
self.file_pos = target_pos
# Mark as dirty, the next time a read is done we need to actually
# move the position in the bzip2 file
self.dirty = True | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"0",
")",
":",
"# Determine absolute target position",
"if",
"whence",
"==",
"0",
":",
"target_pos",
"=",
"offset",
"elif",
"whence",
"==",
"1",
":",
"target_pos",
"=",
"self",
".",
"file_pos",... | Move the file pointer to a particular offset. | [
"Move",
"the",
"file",
"pointer",
"to",
"a",
"particular",
"offset",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/filecache.py#L60-L82 |
20,374 | bxlab/bx-python | lib/bx_extras/lrucache.py | LRUCache.mtime | def mtime(self, key):
"""Return the last modification time for the cache record with key.
May be useful for cache instances where the stored values can get
'stale', such as caching file or network resource contents."""
if key not in self.__dict:
raise CacheKeyError(key)
else:
node = self.__dict[key]
return node.mtime | python | def mtime(self, key):
if key not in self.__dict:
raise CacheKeyError(key)
else:
node = self.__dict[key]
return node.mtime | [
"def",
"mtime",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"__dict",
":",
"raise",
"CacheKeyError",
"(",
"key",
")",
"else",
":",
"node",
"=",
"self",
".",
"__dict",
"[",
"key",
"]",
"return",
"node",
".",
"mtime"
] | Return the last modification time for the cache record with key.
May be useful for cache instances where the stored values can get
'stale', such as caching file or network resource contents. | [
"Return",
"the",
"last",
"modification",
"time",
"for",
"the",
"cache",
"record",
"with",
"key",
".",
"May",
"be",
"useful",
"for",
"cache",
"instances",
"where",
"the",
"stored",
"values",
"can",
"get",
"stale",
"such",
"as",
"caching",
"file",
"or",
"net... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/lrucache.py#L203-L211 |
20,375 | bxlab/bx-python | lib/bx/cookbook/attribute.py | class_space | def class_space(classlevel=3):
"returns the calling class' name and dictionary"
frame = sys._getframe(classlevel)
classname = frame.f_code.co_name
classdict = frame.f_locals
return classname, classdict | python | def class_space(classlevel=3):
"returns the calling class' name and dictionary"
frame = sys._getframe(classlevel)
classname = frame.f_code.co_name
classdict = frame.f_locals
return classname, classdict | [
"def",
"class_space",
"(",
"classlevel",
"=",
"3",
")",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"classlevel",
")",
"classname",
"=",
"frame",
".",
"f_code",
".",
"co_name",
"classdict",
"=",
"frame",
".",
"f_locals",
"return",
"classname",
",",
... | returns the calling class' name and dictionary | [
"returns",
"the",
"calling",
"class",
"name",
"and",
"dictionary"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/cookbook/attribute.py#L67-L72 |
20,376 | bxlab/bx-python | lib/bx/align/lav.py | Reader.build_alignment | def build_alignment(self,score,pieces):
"""converts a score and pieces to an alignment"""
# build text
self.open_seqs()
text1 = text2 = ""
end1 = end2 = None
for (start1,start2,length,pctId) in pieces:
if (end1 != None):
if (start1 == end1): # insertion in sequence 2
text1 += self.seq1_gap * (start2-end2)
text2 += self.seq2_file.get(end2,start2-end2)
else: # insertion in sequence 1
text1 += self.seq1_file.get(end1,start1-end1)
text2 += self.seq2_gap * (start1-end1)
text1 += self.seq1_file.get(start1,length)
text2 += self.seq2_file.get(start2,length)
end1 = start1 + length
end2 = start2 + length
# create alignment
start1 = pieces[0][0]
start2 = pieces[0][1]
end1 = pieces[-1][0] + pieces[-1][2]
end2 = pieces[-1][1] + pieces[-1][2]
size1 = end1 - start1
size2 = end2 - start2
a = Alignment(score=score,species_to_lengths=self.species_to_lengths)
#if (self.seq1_strand == "-"): start1 = self.seq1_file.length - end1
a.add_component(Component(self.seq1_src,start1,size1,self.seq1_strand,text=text1))
#if (self.seq2_strand == "-"): start2 = self.seq2_file.length - end2
a.add_component(Component(self.seq2_src,start2,size2,self.seq2_strand,text=text2))
return a | python | def build_alignment(self,score,pieces):
# build text
self.open_seqs()
text1 = text2 = ""
end1 = end2 = None
for (start1,start2,length,pctId) in pieces:
if (end1 != None):
if (start1 == end1): # insertion in sequence 2
text1 += self.seq1_gap * (start2-end2)
text2 += self.seq2_file.get(end2,start2-end2)
else: # insertion in sequence 1
text1 += self.seq1_file.get(end1,start1-end1)
text2 += self.seq2_gap * (start1-end1)
text1 += self.seq1_file.get(start1,length)
text2 += self.seq2_file.get(start2,length)
end1 = start1 + length
end2 = start2 + length
# create alignment
start1 = pieces[0][0]
start2 = pieces[0][1]
end1 = pieces[-1][0] + pieces[-1][2]
end2 = pieces[-1][1] + pieces[-1][2]
size1 = end1 - start1
size2 = end2 - start2
a = Alignment(score=score,species_to_lengths=self.species_to_lengths)
#if (self.seq1_strand == "-"): start1 = self.seq1_file.length - end1
a.add_component(Component(self.seq1_src,start1,size1,self.seq1_strand,text=text1))
#if (self.seq2_strand == "-"): start2 = self.seq2_file.length - end2
a.add_component(Component(self.seq2_src,start2,size2,self.seq2_strand,text=text2))
return a | [
"def",
"build_alignment",
"(",
"self",
",",
"score",
",",
"pieces",
")",
":",
"# build text",
"self",
".",
"open_seqs",
"(",
")",
"text1",
"=",
"text2",
"=",
"\"\"",
"end1",
"=",
"end2",
"=",
"None",
"for",
"(",
"start1",
",",
"start2",
",",
"length",
... | converts a score and pieces to an alignment | [
"converts",
"a",
"score",
"and",
"pieces",
"to",
"an",
"alignment"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/align/lav.py#L326-L357 |
20,377 | bxlab/bx-python | lib/bx/intervals/operations/__init__.py | bits_clear_in_range | def bits_clear_in_range( bits, range_start, range_end ):
"""
Yield start,end tuples for each span of clear bits in [range_start,range_end)
"""
end = range_start
while 1:
start = bits.next_clear( end )
if start >= range_end: break
end = min( bits.next_set( start ), range_end )
yield start, end | python | def bits_clear_in_range( bits, range_start, range_end ):
end = range_start
while 1:
start = bits.next_clear( end )
if start >= range_end: break
end = min( bits.next_set( start ), range_end )
yield start, end | [
"def",
"bits_clear_in_range",
"(",
"bits",
",",
"range_start",
",",
"range_end",
")",
":",
"end",
"=",
"range_start",
"while",
"1",
":",
"start",
"=",
"bits",
".",
"next_clear",
"(",
"end",
")",
"if",
"start",
">=",
"range_end",
":",
"break",
"end",
"=",... | Yield start,end tuples for each span of clear bits in [range_start,range_end) | [
"Yield",
"start",
"end",
"tuples",
"for",
"each",
"span",
"of",
"clear",
"bits",
"in",
"[",
"range_start",
"range_end",
")"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/intervals/operations/__init__.py#L31-L40 |
20,378 | bxlab/bx-python | lib/bx/cookbook/progress_bar.py | iterprogress | def iterprogress( sized_iterable ):
"""
Iterate something printing progress bar to stdout
"""
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | python | def iterprogress( sized_iterable ):
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | [
"def",
"iterprogress",
"(",
"sized_iterable",
")",
":",
"pb",
"=",
"ProgressBar",
"(",
"0",
",",
"len",
"(",
"sized_iterable",
")",
")",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"sized_iterable",
")",
":",
"yield",
"value",
"pb",
".",
"update_an... | Iterate something printing progress bar to stdout | [
"Iterate",
"something",
"printing",
"progress",
"bar",
"to",
"stdout"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/cookbook/progress_bar.py#L61-L68 |
20,379 | bxlab/bx-python | lib/bx/misc/cdb.py | FileCDBDict.to_file | def to_file( Class, dict, file, is_little_endian=True ):
"""
For constructing a CDB structure in a file. Able to calculate size on
disk and write to a file
"""
io = BinaryFileWriter( file, is_little_endian=is_little_endian )
start_offset = io.tell()
# Header is of fixed length
io.seek( start_offset + ( 8 * 256 ) )
# For each item, key and value length (written as length prefixed
# strings). We also calculate the subtables on this pass.
# NOTE: This requires the key and value be byte strings, support for
# dealing with encoding specific value types should be
# added to this wrapper
subtables = [ [] for i in range(256) ]
for key, value in dict.items():
pair_offset = io.tell()
io.write_uint32( len( key ) )
io.write_uint32( len( value ) )
io.write( key )
io.write( value )
hash = cdbhash( key )
subtables[ hash % 256 ].append( ( hash, pair_offset ) )
# Save the offset where the subtables will start
subtable_offset = io.tell()
# Write subtables
for subtable in subtables:
if len( subtable ) > 0:
# Construct hashtable to be twice the size of the number
# of items in the subtable, and built it in memory
ncells = len( subtable ) * 2
cells = [ (0,0) for i in range( ncells ) ]
for hash, pair_offset in subtable:
index = ( hash >> 8 ) % ncells
while cells[index][1] != 0:
index = ( index + 1 ) % ncells
# Guaranteed to find a non-empty cell
cells[index] = ( hash, pair_offset )
# Write subtable
for hash, pair_offset in cells:
io.write_uint32( hash )
io.write_uint32( pair_offset )
# Go back and write the header
end_offset = io.tell()
io.seek( start_offset )
index = subtable_offset
for subtable in subtables:
io.write_uint32( index )
io.write_uint32( len( subtable * 2 ) )
# For each cell in the subtable, a hash and a pointer to a value
index += ( len( subtable ) * 2 ) * 8
# Leave fp at end of cdb
io.seek( end_offset ) | python | def to_file( Class, dict, file, is_little_endian=True ):
io = BinaryFileWriter( file, is_little_endian=is_little_endian )
start_offset = io.tell()
# Header is of fixed length
io.seek( start_offset + ( 8 * 256 ) )
# For each item, key and value length (written as length prefixed
# strings). We also calculate the subtables on this pass.
# NOTE: This requires the key and value be byte strings, support for
# dealing with encoding specific value types should be
# added to this wrapper
subtables = [ [] for i in range(256) ]
for key, value in dict.items():
pair_offset = io.tell()
io.write_uint32( len( key ) )
io.write_uint32( len( value ) )
io.write( key )
io.write( value )
hash = cdbhash( key )
subtables[ hash % 256 ].append( ( hash, pair_offset ) )
# Save the offset where the subtables will start
subtable_offset = io.tell()
# Write subtables
for subtable in subtables:
if len( subtable ) > 0:
# Construct hashtable to be twice the size of the number
# of items in the subtable, and built it in memory
ncells = len( subtable ) * 2
cells = [ (0,0) for i in range( ncells ) ]
for hash, pair_offset in subtable:
index = ( hash >> 8 ) % ncells
while cells[index][1] != 0:
index = ( index + 1 ) % ncells
# Guaranteed to find a non-empty cell
cells[index] = ( hash, pair_offset )
# Write subtable
for hash, pair_offset in cells:
io.write_uint32( hash )
io.write_uint32( pair_offset )
# Go back and write the header
end_offset = io.tell()
io.seek( start_offset )
index = subtable_offset
for subtable in subtables:
io.write_uint32( index )
io.write_uint32( len( subtable * 2 ) )
# For each cell in the subtable, a hash and a pointer to a value
index += ( len( subtable ) * 2 ) * 8
# Leave fp at end of cdb
io.seek( end_offset ) | [
"def",
"to_file",
"(",
"Class",
",",
"dict",
",",
"file",
",",
"is_little_endian",
"=",
"True",
")",
":",
"io",
"=",
"BinaryFileWriter",
"(",
"file",
",",
"is_little_endian",
"=",
"is_little_endian",
")",
"start_offset",
"=",
"io",
".",
"tell",
"(",
")",
... | For constructing a CDB structure in a file. Able to calculate size on
disk and write to a file | [
"For",
"constructing",
"a",
"CDB",
"structure",
"in",
"a",
"file",
".",
"Able",
"to",
"calculate",
"size",
"on",
"disk",
"and",
"write",
"to",
"a",
"file"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/misc/cdb.py#L65-L117 |
20,380 | bxlab/bx-python | scripts/bed_complement.py | read_len | def read_len( f ):
"""Read a 'LEN' file and return a mapping from chromosome to length"""
mapping = dict()
for line in f:
fields = line.split()
mapping[ fields[0] ] = int( fields[1] )
return mapping | python | def read_len( f ):
mapping = dict()
for line in f:
fields = line.split()
mapping[ fields[0] ] = int( fields[1] )
return mapping | [
"def",
"read_len",
"(",
"f",
")",
":",
"mapping",
"=",
"dict",
"(",
")",
"for",
"line",
"in",
"f",
":",
"fields",
"=",
"line",
".",
"split",
"(",
")",
"mapping",
"[",
"fields",
"[",
"0",
"]",
"]",
"=",
"int",
"(",
"fields",
"[",
"1",
"]",
")"... | Read a 'LEN' file and return a mapping from chromosome to length | [
"Read",
"a",
"LEN",
"file",
"and",
"return",
"a",
"mapping",
"from",
"chromosome",
"to",
"length"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bed_complement.py#L20-L26 |
20,381 | bxlab/bx-python | lib/bx/motif/logo/__init__.py | eps_logo | def eps_logo( matrix, base_width, height, colors=DNA_DEFAULT_COLORS ):
"""
Return an EPS document containing a sequence logo for matrix where each
bases is shown as a column of `base_width` points and the total logo
height is `height` points. If `colors` is provided it is a mapping from
characters to rgb color strings.
"""
alphabet = matrix.sorted_alphabet
rval = StringIO()
# Read header ans substitute in width / height
header = Template( pkg_resources.resource_string( __name__, "template.ps" ) )
rval.write( header.substitute( bounding_box_width = ceil( base_width * matrix.width ) + PAD,
bounding_box_height = ceil( height ) + PAD ) )
# Determine heights
heights = freqs_to_heights( matrix )
height_scale = height / log2( len( alphabet ) )
# Draw each "row" of the matrix
for i, row in enumerate( heights ):
x = ( i * base_width )
y = 0
for j, base_height in enumerate( row ):
char = alphabet[j]
page_height = height_scale * base_height
# print matrix.alphabet[j], base_height, height_scale, page_height
if page_height > 1:
# Draw letter
rval.write( "%s setrgbcolor\n" % colors.get( char, '0 0 0' ) )
rval.write( "%3.2f " % x )
rval.write( "%3.2f " % y )
rval.write( "%3.2f " % ( x + base_width ) )
rval.write( "%3.2f " % ( y + page_height ) )
rval.write( "(%s) textInBox\n" % char )
y += page_height
rval.write( "showpage" )
return rval.getvalue() | python | def eps_logo( matrix, base_width, height, colors=DNA_DEFAULT_COLORS ):
alphabet = matrix.sorted_alphabet
rval = StringIO()
# Read header ans substitute in width / height
header = Template( pkg_resources.resource_string( __name__, "template.ps" ) )
rval.write( header.substitute( bounding_box_width = ceil( base_width * matrix.width ) + PAD,
bounding_box_height = ceil( height ) + PAD ) )
# Determine heights
heights = freqs_to_heights( matrix )
height_scale = height / log2( len( alphabet ) )
# Draw each "row" of the matrix
for i, row in enumerate( heights ):
x = ( i * base_width )
y = 0
for j, base_height in enumerate( row ):
char = alphabet[j]
page_height = height_scale * base_height
# print matrix.alphabet[j], base_height, height_scale, page_height
if page_height > 1:
# Draw letter
rval.write( "%s setrgbcolor\n" % colors.get( char, '0 0 0' ) )
rval.write( "%3.2f " % x )
rval.write( "%3.2f " % y )
rval.write( "%3.2f " % ( x + base_width ) )
rval.write( "%3.2f " % ( y + page_height ) )
rval.write( "(%s) textInBox\n" % char )
y += page_height
rval.write( "showpage" )
return rval.getvalue() | [
"def",
"eps_logo",
"(",
"matrix",
",",
"base_width",
",",
"height",
",",
"colors",
"=",
"DNA_DEFAULT_COLORS",
")",
":",
"alphabet",
"=",
"matrix",
".",
"sorted_alphabet",
"rval",
"=",
"StringIO",
"(",
")",
"# Read header ans substitute in width / height",
"header",
... | Return an EPS document containing a sequence logo for matrix where each
bases is shown as a column of `base_width` points and the total logo
height is `height` points. If `colors` is provided it is a mapping from
characters to rgb color strings. | [
"Return",
"an",
"EPS",
"document",
"containing",
"a",
"sequence",
"logo",
"for",
"matrix",
"where",
"each",
"bases",
"is",
"shown",
"as",
"a",
"column",
"of",
"base_width",
"points",
"and",
"the",
"total",
"logo",
"height",
"is",
"height",
"points",
".",
"... | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/logo/__init__.py#L38-L72 |
20,382 | bxlab/bx-python | scripts/bnMapper.py | transform | def transform(elem, chain_CT_CQ, max_gap):
"""transform the coordinates of this elem into the other species.
elem intersects this chain's ginterval.
:return: a list of the type [(to_chr, start, end, elem[id]) ... ]"""
(chain, CT, CQ) = chain_CT_CQ
start, end = max(elem['start'], chain.tStart) - chain.tStart, min(elem['end'], chain.tEnd) - chain.tStart
assert np.all( (CT[:,1] - CT[:,0]) == (CQ[:,1] - CQ[:,0]) )
to_chrom = chain.qName
to_gab_start = chain.qStart
start_idx = np.where( CT[:,1] > start )[0][0]
end_idx = np.where( CT[:,0] < end )[0][-1]
if start_idx > end_idx: #maps to a gap region on the other species
return []
## apply the gap threshold
if max_gap >= 0 and start_idx < end_idx - 1:
if np.max(CT[(start_idx+1):end_idx,0] - CT[start_idx:(end_idx-1),1]) > max_gap or np.max(CQ[(start_idx+1):end_idx,0] - CQ[start_idx:(end_idx-1),1]) > max_gap:
return []
assert start < CT[start_idx, 1]
assert CT[end_idx, 0] < end
to_start = CQ[start_idx, 0] + max(0, start - CT[start_idx,0]) # correct if on middle of interval
to_end = CQ[end_idx, 1] - max(0, CT[end_idx, 1] - end) # idem
if start_idx == end_idx: #elem falls in a single run of matches
slices = [(to_start, to_end)]
else:
slices = [(to_start, CQ[start_idx,1])]
slices += [(CQ[i,0], CQ[i,1]) for i in range(start_idx+1, end_idx)]
slices.append( (CQ[end_idx,0], to_end) )
if chain.qStrand == '-':
Sz = chain.qEnd - chain.qStart
slices = [(Sz-t[1], Sz-t[0]) for t in slices]
return [(to_chrom, to_gab_start + t[0], to_gab_start + t[1], elem['id']) for t in slices] | python | def transform(elem, chain_CT_CQ, max_gap):
(chain, CT, CQ) = chain_CT_CQ
start, end = max(elem['start'], chain.tStart) - chain.tStart, min(elem['end'], chain.tEnd) - chain.tStart
assert np.all( (CT[:,1] - CT[:,0]) == (CQ[:,1] - CQ[:,0]) )
to_chrom = chain.qName
to_gab_start = chain.qStart
start_idx = np.where( CT[:,1] > start )[0][0]
end_idx = np.where( CT[:,0] < end )[0][-1]
if start_idx > end_idx: #maps to a gap region on the other species
return []
## apply the gap threshold
if max_gap >= 0 and start_idx < end_idx - 1:
if np.max(CT[(start_idx+1):end_idx,0] - CT[start_idx:(end_idx-1),1]) > max_gap or np.max(CQ[(start_idx+1):end_idx,0] - CQ[start_idx:(end_idx-1),1]) > max_gap:
return []
assert start < CT[start_idx, 1]
assert CT[end_idx, 0] < end
to_start = CQ[start_idx, 0] + max(0, start - CT[start_idx,0]) # correct if on middle of interval
to_end = CQ[end_idx, 1] - max(0, CT[end_idx, 1] - end) # idem
if start_idx == end_idx: #elem falls in a single run of matches
slices = [(to_start, to_end)]
else:
slices = [(to_start, CQ[start_idx,1])]
slices += [(CQ[i,0], CQ[i,1]) for i in range(start_idx+1, end_idx)]
slices.append( (CQ[end_idx,0], to_end) )
if chain.qStrand == '-':
Sz = chain.qEnd - chain.qStart
slices = [(Sz-t[1], Sz-t[0]) for t in slices]
return [(to_chrom, to_gab_start + t[0], to_gab_start + t[1], elem['id']) for t in slices] | [
"def",
"transform",
"(",
"elem",
",",
"chain_CT_CQ",
",",
"max_gap",
")",
":",
"(",
"chain",
",",
"CT",
",",
"CQ",
")",
"=",
"chain_CT_CQ",
"start",
",",
"end",
"=",
"max",
"(",
"elem",
"[",
"'start'",
"]",
",",
"chain",
".",
"tStart",
")",
"-",
... | transform the coordinates of this elem into the other species.
elem intersects this chain's ginterval.
:return: a list of the type [(to_chr, start, end, elem[id]) ... ] | [
"transform",
"the",
"coordinates",
"of",
"this",
"elem",
"into",
"the",
"other",
"species",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bnMapper.py#L63-L100 |
20,383 | bxlab/bx-python | scripts/bnMapper.py | loadChains | def loadChains(path):
"name says it."
EPO = epo.Chain._parse_file(path, True)
## convert coordinates w.r.t the forward strand (into slices)
## compute cummulative intervals
for i in range( len(EPO) ):
ch, S, T, Q = EPO[i]
if ch.tStrand == '-':
ch = ch._replace(tEnd = ch.tSize - ch.tStart,
tStart = ch.tSize - ch.tEnd)
if ch.qStrand == '-':
ch = ch._replace(qEnd = ch.qSize - ch.qStart,
qStart = ch.qSize - ch.qEnd)
EPO[i] = (ch,
epo.cummulative_intervals(S, T),
epo.cummulative_intervals(S, Q)
)
##now each element of epo is (chain_header, target_intervals, query_intervals)
assert all( t[0].tStrand == '+' for t in EPO ), "all target strands should be +"
return EPO | python | def loadChains(path):
"name says it."
EPO = epo.Chain._parse_file(path, True)
## convert coordinates w.r.t the forward strand (into slices)
## compute cummulative intervals
for i in range( len(EPO) ):
ch, S, T, Q = EPO[i]
if ch.tStrand == '-':
ch = ch._replace(tEnd = ch.tSize - ch.tStart,
tStart = ch.tSize - ch.tEnd)
if ch.qStrand == '-':
ch = ch._replace(qEnd = ch.qSize - ch.qStart,
qStart = ch.qSize - ch.qEnd)
EPO[i] = (ch,
epo.cummulative_intervals(S, T),
epo.cummulative_intervals(S, Q)
)
##now each element of epo is (chain_header, target_intervals, query_intervals)
assert all( t[0].tStrand == '+' for t in EPO ), "all target strands should be +"
return EPO | [
"def",
"loadChains",
"(",
"path",
")",
":",
"EPO",
"=",
"epo",
".",
"Chain",
".",
"_parse_file",
"(",
"path",
",",
"True",
")",
"## convert coordinates w.r.t the forward strand (into slices)",
"## compute cummulative intervals",
"for",
"i",
"in",
"range",
"(",
"len"... | name says it. | [
"name",
"says",
"it",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bnMapper.py#L228-L248 |
20,384 | bxlab/bx-python | scripts/bnMapper.py | loadFeatures | def loadFeatures(path, opt):
"""
Load features. For BED, only BED4 columns are loaded.
For narrowPeak, all columns are loaded.
"""
log.info("loading from %s ..." % path)
data = []
if opt.in_format == "BED":
with open(path) as fd:
for line in fd:
cols = line.split()
data.append( (cols[0], int(cols[1]), int(cols[2]), cols[3]) )
data = np.array(data, dtype=elem_t)
else:
with open(path) as fd:
for line in fd:
cols = line.split()
data.append( (cols[0], int(cols[1]), int(cols[2]), cols[3], int(cols[4]),
cols[5], float(cols[6]), float(cols[7]), float(cols[8]),
int(cols[-1])+int(cols[1])) )
data = np.array(data, dtype=narrowPeak_t)
return data | python | def loadFeatures(path, opt):
log.info("loading from %s ..." % path)
data = []
if opt.in_format == "BED":
with open(path) as fd:
for line in fd:
cols = line.split()
data.append( (cols[0], int(cols[1]), int(cols[2]), cols[3]) )
data = np.array(data, dtype=elem_t)
else:
with open(path) as fd:
for line in fd:
cols = line.split()
data.append( (cols[0], int(cols[1]), int(cols[2]), cols[3], int(cols[4]),
cols[5], float(cols[6]), float(cols[7]), float(cols[8]),
int(cols[-1])+int(cols[1])) )
data = np.array(data, dtype=narrowPeak_t)
return data | [
"def",
"loadFeatures",
"(",
"path",
",",
"opt",
")",
":",
"log",
".",
"info",
"(",
"\"loading from %s ...\"",
"%",
"path",
")",
"data",
"=",
"[",
"]",
"if",
"opt",
".",
"in_format",
"==",
"\"BED\"",
":",
"with",
"open",
"(",
"path",
")",
"as",
"fd",
... | Load features. For BED, only BED4 columns are loaded.
For narrowPeak, all columns are loaded. | [
"Load",
"features",
".",
"For",
"BED",
"only",
"BED4",
"columns",
"are",
"loaded",
".",
"For",
"narrowPeak",
"all",
"columns",
"are",
"loaded",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bnMapper.py#L250-L272 |
20,385 | bxlab/bx-python | scripts/bnMapper.py | GIntervalTree.add | def add(self, chrom, element):
"""insert an element. use this method as the IntervalTree one.
this will simply call the IntervalTree.add method on the right tree
:param chrom: chromosome
:param element: the argument of IntervalTree.insert_interval
:return: None
"""
self._trees.setdefault(chrom, IntervalTree()).insert_interval( element ) | python | def add(self, chrom, element):
self._trees.setdefault(chrom, IntervalTree()).insert_interval( element ) | [
"def",
"add",
"(",
"self",
",",
"chrom",
",",
"element",
")",
":",
"self",
".",
"_trees",
".",
"setdefault",
"(",
"chrom",
",",
"IntervalTree",
"(",
")",
")",
".",
"insert_interval",
"(",
"element",
")"
] | insert an element. use this method as the IntervalTree one.
this will simply call the IntervalTree.add method on the right tree
:param chrom: chromosome
:param element: the argument of IntervalTree.insert_interval
:return: None | [
"insert",
"an",
"element",
".",
"use",
"this",
"method",
"as",
"the",
"IntervalTree",
"one",
".",
"this",
"will",
"simply",
"call",
"the",
"IntervalTree",
".",
"add",
"method",
"on",
"the",
"right",
"tree"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bnMapper.py#L38-L47 |
20,386 | bxlab/bx-python | scripts/bnMapper.py | GIntervalTree.find | def find(self, chrom, start, end):
"""find the intersecting elements
:param chrom: chromosome
:param start: start
:param end: end
:return: a list of intersecting elements"""
tree = self._trees.get( chrom, None )
if tree:
return tree.find( start, end )
#return always a list
return [] | python | def find(self, chrom, start, end):
tree = self._trees.get( chrom, None )
if tree:
return tree.find( start, end )
#return always a list
return [] | [
"def",
"find",
"(",
"self",
",",
"chrom",
",",
"start",
",",
"end",
")",
":",
"tree",
"=",
"self",
".",
"_trees",
".",
"get",
"(",
"chrom",
",",
"None",
")",
"if",
"tree",
":",
"return",
"tree",
".",
"find",
"(",
"start",
",",
"end",
")",
"#ret... | find the intersecting elements
:param chrom: chromosome
:param start: start
:param end: end
:return: a list of intersecting elements | [
"find",
"the",
"intersecting",
"elements"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/bnMapper.py#L49-L61 |
20,387 | bxlab/bx-python | lib/bx/motif/pwm.py | BaseMatrix.create_from_other | def create_from_other( Class, other, values=None ):
"""
Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided
"""
m = Class()
m.alphabet = other.alphabet
m.sorted_alphabet = other.sorted_alphabet
m.char_to_index = other.char_to_index
if values is not None:
m.values = values
else:
m.values = other.values
return m | python | def create_from_other( Class, other, values=None ):
m = Class()
m.alphabet = other.alphabet
m.sorted_alphabet = other.sorted_alphabet
m.char_to_index = other.char_to_index
if values is not None:
m.values = values
else:
m.values = other.values
return m | [
"def",
"create_from_other",
"(",
"Class",
",",
"other",
",",
"values",
"=",
"None",
")",
":",
"m",
"=",
"Class",
"(",
")",
"m",
".",
"alphabet",
"=",
"other",
".",
"alphabet",
"m",
".",
"sorted_alphabet",
"=",
"other",
".",
"sorted_alphabet",
"m",
".",... | Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided | [
"Create",
"a",
"new",
"Matrix",
"with",
"attributes",
"taken",
"from",
"other",
"but",
"with",
"the",
"values",
"taken",
"from",
"values",
"if",
"provided"
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/pwm.py#L51-L64 |
20,388 | bxlab/bx-python | lib/bx/motif/pwm.py | FrequencyMatrix.to_logodds_scoring_matrix | def to_logodds_scoring_matrix( self, background=None, correction=DEFAULT_CORRECTION ):
"""
Create a standard logodds scoring matrix.
"""
alphabet_size = len( self.alphabet )
if background is None:
background = ones( alphabet_size, float32 ) / alphabet_size
# Row totals as a one column array
totals = numpy.sum( self.values, 1 )[:,newaxis]
values = log2( maximum( self.values, correction ) ) \
- log2( totals ) \
- log2( maximum( background, correction ) )
return ScoringMatrix.create_from_other( self, values.astype( float32 ) ) | python | def to_logodds_scoring_matrix( self, background=None, correction=DEFAULT_CORRECTION ):
alphabet_size = len( self.alphabet )
if background is None:
background = ones( alphabet_size, float32 ) / alphabet_size
# Row totals as a one column array
totals = numpy.sum( self.values, 1 )[:,newaxis]
values = log2( maximum( self.values, correction ) ) \
- log2( totals ) \
- log2( maximum( background, correction ) )
return ScoringMatrix.create_from_other( self, values.astype( float32 ) ) | [
"def",
"to_logodds_scoring_matrix",
"(",
"self",
",",
"background",
"=",
"None",
",",
"correction",
"=",
"DEFAULT_CORRECTION",
")",
":",
"alphabet_size",
"=",
"len",
"(",
"self",
".",
"alphabet",
")",
"if",
"background",
"is",
"None",
":",
"background",
"=",
... | Create a standard logodds scoring matrix. | [
"Create",
"a",
"standard",
"logodds",
"scoring",
"matrix",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/pwm.py#L95-L107 |
20,389 | bxlab/bx-python | lib/bx/motif/pwm.py | ScoringMatrix.score_string | def score_string( self, string ):
"""
Score each valid position in `string` using this scoring matrix.
Positions which were not scored are set to nan.
"""
rval = zeros( len( string ), float32 )
rval[:] = nan
_pwm.score_string( self.values, self.char_to_index, string, rval )
return rval | python | def score_string( self, string ):
rval = zeros( len( string ), float32 )
rval[:] = nan
_pwm.score_string( self.values, self.char_to_index, string, rval )
return rval | [
"def",
"score_string",
"(",
"self",
",",
"string",
")",
":",
"rval",
"=",
"zeros",
"(",
"len",
"(",
"string",
")",
",",
"float32",
")",
"rval",
"[",
":",
"]",
"=",
"nan",
"_pwm",
".",
"score_string",
"(",
"self",
".",
"values",
",",
"self",
".",
... | Score each valid position in `string` using this scoring matrix.
Positions which were not scored are set to nan. | [
"Score",
"each",
"valid",
"position",
"in",
"string",
"using",
"this",
"scoring",
"matrix",
".",
"Positions",
"which",
"were",
"not",
"scored",
"are",
"set",
"to",
"nan",
"."
] | 09cb725284803df90a468d910f2274628d8647de | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/pwm.py#L131-L139 |
20,390 | jborean93/ntlm-auth | ntlm_auth/compute_response.py | ComputeResponse._calc_resp | def _calc_resp(password_hash, server_challenge):
"""
Generate the LM response given a 16-byte password hash and the
challenge from the CHALLENGE_MESSAGE
:param password_hash: A 16-byte password hash
:param server_challenge: A random 8-byte response generated by the
server in the CHALLENGE_MESSAGE
:return res: A 24-byte buffer to contain the LM response upon return
"""
# padding with zeros to make the hash 21 bytes long
password_hash += b'\x00' * (21 - len(password_hash))
res = b''
dobj = DES(DES.key56_to_key64(password_hash[0:7]))
res = res + dobj.encrypt(server_challenge[0:8])
dobj = DES(DES.key56_to_key64(password_hash[7:14]))
res = res + dobj.encrypt(server_challenge[0:8])
dobj = DES(DES.key56_to_key64(password_hash[14:21]))
res = res + dobj.encrypt(server_challenge[0:8])
return res | python | def _calc_resp(password_hash, server_challenge):
# padding with zeros to make the hash 21 bytes long
password_hash += b'\x00' * (21 - len(password_hash))
res = b''
dobj = DES(DES.key56_to_key64(password_hash[0:7]))
res = res + dobj.encrypt(server_challenge[0:8])
dobj = DES(DES.key56_to_key64(password_hash[7:14]))
res = res + dobj.encrypt(server_challenge[0:8])
dobj = DES(DES.key56_to_key64(password_hash[14:21]))
res = res + dobj.encrypt(server_challenge[0:8])
return res | [
"def",
"_calc_resp",
"(",
"password_hash",
",",
"server_challenge",
")",
":",
"# padding with zeros to make the hash 21 bytes long",
"password_hash",
"+=",
"b'\\x00'",
"*",
"(",
"21",
"-",
"len",
"(",
"password_hash",
")",
")",
"res",
"=",
"b''",
"dobj",
"=",
"DES... | Generate the LM response given a 16-byte password hash and the
challenge from the CHALLENGE_MESSAGE
:param password_hash: A 16-byte password hash
:param server_challenge: A random 8-byte response generated by the
server in the CHALLENGE_MESSAGE
:return res: A 24-byte buffer to contain the LM response upon return | [
"Generate",
"the",
"LM",
"response",
"given",
"a",
"16",
"-",
"byte",
"password",
"hash",
"and",
"the",
"challenge",
"from",
"the",
"CHALLENGE_MESSAGE"
] | 2c7cd81516d9bfd42e8ff473a534d876b21ebb38 | https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/compute_response.py#L433-L455 |
20,391 | jborean93/ntlm-auth | ntlm_auth/des.py | DES.encrypt | def encrypt(self, data, pad=True):
"""
DES encrypts the data based on the key it was initialised with.
:param data: The bytes string to encrypt
:param pad: Whether to right pad data with \x00 to a multiple of 8
:return: The encrypted bytes string
"""
encrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8 and pad:
block += b"\x00" * (8 - block_length)
elif block_length != 8:
raise ValueError("DES encryption must be a multiple of 8 "
"bytes")
encrypted_data += self._encode_block(block)
return encrypted_data | python | def encrypt(self, data, pad=True):
encrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8 and pad:
block += b"\x00" * (8 - block_length)
elif block_length != 8:
raise ValueError("DES encryption must be a multiple of 8 "
"bytes")
encrypted_data += self._encode_block(block)
return encrypted_data | [
"def",
"encrypt",
"(",
"self",
",",
"data",
",",
"pad",
"=",
"True",
")",
":",
"encrypted_data",
"=",
"b\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"8",
")",
":",
"block",
"=",
"data",
"[",
"i",
":",
"i",
"+... | DES encrypts the data based on the key it was initialised with.
:param data: The bytes string to encrypt
:param pad: Whether to right pad data with \x00 to a multiple of 8
:return: The encrypted bytes string | [
"DES",
"encrypts",
"the",
"data",
"based",
"on",
"the",
"key",
"it",
"was",
"initialised",
"with",
"."
] | 2c7cd81516d9bfd42e8ff473a534d876b21ebb38 | https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/des.py#L150-L169 |
20,392 | jborean93/ntlm-auth | ntlm_auth/des.py | DES.decrypt | def decrypt(self, data):
"""
DES decrypts the data based on the key it was initialised with.
:param data: The encrypted bytes string to decrypt
:return: The decrypted bytes string
"""
decrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8:
raise ValueError("DES decryption must be a multiple of 8 "
"bytes")
decrypted_data += self._decode_block(block)
return decrypted_data | python | def decrypt(self, data):
decrypted_data = b""
for i in range(0, len(data), 8):
block = data[i:i + 8]
block_length = len(block)
if block_length != 8:
raise ValueError("DES decryption must be a multiple of 8 "
"bytes")
decrypted_data += self._decode_block(block)
return decrypted_data | [
"def",
"decrypt",
"(",
"self",
",",
"data",
")",
":",
"decrypted_data",
"=",
"b\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"8",
")",
":",
"block",
"=",
"data",
"[",
"i",
":",
"i",
"+",
"8",
"]",
"block_length"... | DES decrypts the data based on the key it was initialised with.
:param data: The encrypted bytes string to decrypt
:return: The decrypted bytes string | [
"DES",
"decrypts",
"the",
"data",
"based",
"on",
"the",
"key",
"it",
"was",
"initialised",
"with",
"."
] | 2c7cd81516d9bfd42e8ff473a534d876b21ebb38 | https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/des.py#L171-L188 |
20,393 | jborean93/ntlm-auth | ntlm_auth/des.py | DES.key56_to_key64 | def key56_to_key64(key):
"""
This takes in an a bytes string of 7 bytes and converts it to a bytes
string of 8 bytes with the odd parity bit being set to every 8 bits,
For example
b"\x01\x02\x03\x04\x05\x06\x07"
00000001 00000010 00000011 00000100 00000101 00000110 00000111
is converted to
b"\x01\x80\x80\x61\x40\x29\x19\x0E"
00000001 10000000 10000000 01100001 01000000 00101001 00011001 00001110
https://crypto.stackexchange.com/questions/15799/des-with-actual-7-byte-key
:param key: 7-byte string sized key
:return: 8-byte string with the parity bits sets from the 7-byte string
"""
if len(key) != 7:
raise ValueError("DES 7-byte key is not 7 bytes in length, "
"actual: %d" % len(key))
new_key = b""
for i in range(0, 8):
if i == 0:
new_value = struct.unpack("B", key[i:i+1])[0]
elif i == 7:
new_value = struct.unpack("B", key[6:7])[0]
new_value = (new_value << 1) & 0xFF
else:
new_value = struct.unpack("B", key[i - 1:i])[0]
next_value = struct.unpack("B", key[i:i + 1])[0]
new_value = ((new_value << (8 - i)) & 0xFF) | next_value >> i
# clear the last bit so the count isn't off
new_value = new_value & ~(1 << 0)
# set the last bit if the number of set bits are even
new_value = new_value | int(not DES.bit_count(new_value) & 0x1)
new_key += struct.pack("B", new_value)
return new_key | python | def key56_to_key64(key):
if len(key) != 7:
raise ValueError("DES 7-byte key is not 7 bytes in length, "
"actual: %d" % len(key))
new_key = b""
for i in range(0, 8):
if i == 0:
new_value = struct.unpack("B", key[i:i+1])[0]
elif i == 7:
new_value = struct.unpack("B", key[6:7])[0]
new_value = (new_value << 1) & 0xFF
else:
new_value = struct.unpack("B", key[i - 1:i])[0]
next_value = struct.unpack("B", key[i:i + 1])[0]
new_value = ((new_value << (8 - i)) & 0xFF) | next_value >> i
# clear the last bit so the count isn't off
new_value = new_value & ~(1 << 0)
# set the last bit if the number of set bits are even
new_value = new_value | int(not DES.bit_count(new_value) & 0x1)
new_key += struct.pack("B", new_value)
return new_key | [
"def",
"key56_to_key64",
"(",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
"!=",
"7",
":",
"raise",
"ValueError",
"(",
"\"DES 7-byte key is not 7 bytes in length, \"",
"\"actual: %d\"",
"%",
"len",
"(",
"key",
")",
")",
"new_key",
"=",
"b\"\"",
"for",
"i",... | This takes in an a bytes string of 7 bytes and converts it to a bytes
string of 8 bytes with the odd parity bit being set to every 8 bits,
For example
b"\x01\x02\x03\x04\x05\x06\x07"
00000001 00000010 00000011 00000100 00000101 00000110 00000111
is converted to
b"\x01\x80\x80\x61\x40\x29\x19\x0E"
00000001 10000000 10000000 01100001 01000000 00101001 00011001 00001110
https://crypto.stackexchange.com/questions/15799/des-with-actual-7-byte-key
:param key: 7-byte string sized key
:return: 8-byte string with the parity bits sets from the 7-byte string | [
"This",
"takes",
"in",
"an",
"a",
"bytes",
"string",
"of",
"7",
"bytes",
"and",
"converts",
"it",
"to",
"a",
"bytes",
"string",
"of",
"8",
"bytes",
"with",
"the",
"odd",
"parity",
"bit",
"being",
"set",
"to",
"every",
"8",
"bits"
] | 2c7cd81516d9bfd42e8ff473a534d876b21ebb38 | https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/des.py#L191-L234 |
20,394 | datawire/quark | quarkc/compiler.py | Check.visit_Method | def visit_Method(self, method):
"""
Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance.
"""
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should already be the resolved version.
result = []
for param in method.params:
resolved_param = texpr(param.resolved.type, param.resolved.bindings, extra_bindings)
result.append(resolved_param.id)
return result
def get_return_type(method, extra_bindings):
# The Method should already be the resolved version.
return texpr(method.type.resolved.type, method.type.resolved.bindings,
extra_bindings).id
def signature(method, return_type, params):
return "%s %s(%s)" % (return_type, method.name.text, ", ".join(params))
# Ensure the method has the same signature as matching methods on parent
# interfaces:
interfaces = list(t for t in method.clazz.bases if isinstance(t.resolved.type, Interface))
for interface in interfaces:
interfaceTypeExpr = interface.resolved
for definition in interfaceTypeExpr.type.definitions:
if definition.name.text == method.name.text:
resolved_definition = definition.resolved.type
method_params = get_params(resolved_method, method.clazz.resolved.bindings)
definition_params = get_params(resolved_definition, interfaceTypeExpr.bindings)
method_return = get_return_type(resolved_method, method.clazz.resolved.bindings)
definition_return = get_return_type(resolved_definition, interfaceTypeExpr.bindings)
if method_params != definition_params or method_return != definition_return:
self.errors.append(
"%s: method signature '%s' on %s does not match method '%s' on interface %s" % (
lineinfo(method), signature(resolved_method, method_return, method_params),
method.clazz.resolved.type.id,
signature(resolved_definition, definition_return, definition_params),
interface.resolved.type.id)) | python | def visit_Method(self, method):
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should already be the resolved version.
result = []
for param in method.params:
resolved_param = texpr(param.resolved.type, param.resolved.bindings, extra_bindings)
result.append(resolved_param.id)
return result
def get_return_type(method, extra_bindings):
# The Method should already be the resolved version.
return texpr(method.type.resolved.type, method.type.resolved.bindings,
extra_bindings).id
def signature(method, return_type, params):
return "%s %s(%s)" % (return_type, method.name.text, ", ".join(params))
# Ensure the method has the same signature as matching methods on parent
# interfaces:
interfaces = list(t for t in method.clazz.bases if isinstance(t.resolved.type, Interface))
for interface in interfaces:
interfaceTypeExpr = interface.resolved
for definition in interfaceTypeExpr.type.definitions:
if definition.name.text == method.name.text:
resolved_definition = definition.resolved.type
method_params = get_params(resolved_method, method.clazz.resolved.bindings)
definition_params = get_params(resolved_definition, interfaceTypeExpr.bindings)
method_return = get_return_type(resolved_method, method.clazz.resolved.bindings)
definition_return = get_return_type(resolved_definition, interfaceTypeExpr.bindings)
if method_params != definition_params or method_return != definition_return:
self.errors.append(
"%s: method signature '%s' on %s does not match method '%s' on interface %s" % (
lineinfo(method), signature(resolved_method, method_return, method_params),
method.clazz.resolved.type.id,
signature(resolved_definition, definition_return, definition_params),
interface.resolved.type.id)) | [
"def",
"visit_Method",
"(",
"self",
",",
"method",
")",
":",
"resolved_method",
"=",
"method",
".",
"resolved",
".",
"type",
"def",
"get_params",
"(",
"method",
",",
"extra_bindings",
")",
":",
"# The Method should already be the resolved version.",
"result",
"=",
... | Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance. | [
"Ensure",
"method",
"has",
"the",
"same",
"signature",
"matching",
"method",
"on",
"parent",
"interface",
"."
] | df0058a148b077c0aff535eb6ee382605c556273 | https://github.com/datawire/quark/blob/df0058a148b077c0aff535eb6ee382605c556273/quarkc/compiler.py#L743-L786 |
20,395 | datawire/quark | quarkc/docmaker.py | get_doc | def get_doc(node):
"""
Return a node's documentation as a string, pulling from annotations
or constructing a simple fake as needed.
"""
res = " ".join(get_doc_annotations(node))
if not res:
res = "(%s)" % node.__class__.__name__.lower()
return res | python | def get_doc(node):
res = " ".join(get_doc_annotations(node))
if not res:
res = "(%s)" % node.__class__.__name__.lower()
return res | [
"def",
"get_doc",
"(",
"node",
")",
":",
"res",
"=",
"\" \"",
".",
"join",
"(",
"get_doc_annotations",
"(",
"node",
")",
")",
"if",
"not",
"res",
":",
"res",
"=",
"\"(%s)\"",
"%",
"node",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"... | Return a node's documentation as a string, pulling from annotations
or constructing a simple fake as needed. | [
"Return",
"a",
"node",
"s",
"documentation",
"as",
"a",
"string",
"pulling",
"from",
"annotations",
"or",
"constructing",
"a",
"simple",
"fake",
"as",
"needed",
"."
] | df0058a148b077c0aff535eb6ee382605c556273 | https://github.com/datawire/quark/blob/df0058a148b077c0aff535eb6ee382605c556273/quarkc/docmaker.py#L75-L83 |
20,396 | datawire/quark | quarkc/docmaker.py | get_code | def get_code(node, coder=Coder()):
"""
Return a node's code
"""
return cgi.escape(str(coder.code(node)), quote=True) | python | def get_code(node, coder=Coder()):
return cgi.escape(str(coder.code(node)), quote=True) | [
"def",
"get_code",
"(",
"node",
",",
"coder",
"=",
"Coder",
"(",
")",
")",
":",
"return",
"cgi",
".",
"escape",
"(",
"str",
"(",
"coder",
".",
"code",
"(",
"node",
")",
")",
",",
"quote",
"=",
"True",
")"
] | Return a node's code | [
"Return",
"a",
"node",
"s",
"code"
] | df0058a148b077c0aff535eb6ee382605c556273 | https://github.com/datawire/quark/blob/df0058a148b077c0aff535eb6ee382605c556273/quarkc/docmaker.py#L86-L90 |
20,397 | datawire/quark | quarkc/lib/quark_ws4py_fixup.py | WebSocketWSGIHandler.setup_environ | def setup_environ(self):
"""
Setup the environ dictionary and add the
`'ws4py.socket'` key. Its associated value
is the real socket underlying socket.
"""
SimpleHandler.setup_environ(self)
self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input'])
self.http_version = self.environ['SERVER_PROTOCOL'].rsplit('/')[-1] | python | def setup_environ(self):
SimpleHandler.setup_environ(self)
self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input'])
self.http_version = self.environ['SERVER_PROTOCOL'].rsplit('/')[-1] | [
"def",
"setup_environ",
"(",
"self",
")",
":",
"SimpleHandler",
".",
"setup_environ",
"(",
"self",
")",
"self",
".",
"environ",
"[",
"'ws4py.socket'",
"]",
"=",
"get_connection",
"(",
"self",
".",
"environ",
"[",
"'wsgi.input'",
"]",
")",
"self",
".",
"htt... | Setup the environ dictionary and add the
`'ws4py.socket'` key. Its associated value
is the real socket underlying socket. | [
"Setup",
"the",
"environ",
"dictionary",
"and",
"add",
"the",
"ws4py",
".",
"socket",
"key",
".",
"Its",
"associated",
"value",
"is",
"the",
"real",
"socket",
"underlying",
"socket",
"."
] | df0058a148b077c0aff535eb6ee382605c556273 | https://github.com/datawire/quark/blob/df0058a148b077c0aff535eb6ee382605c556273/quarkc/lib/quark_ws4py_fixup.py#L21-L29 |
20,398 | datawire/quark | quarkc/lib/quark_ws4py_fixup.py | WebSocketWSGIRequestHandler.handle | def handle(self):
"""
Unfortunately the base class forces us
to override the whole method to actually provide our wsgi handler.
"""
self.raw_requestline = self.rfile.readline()
if not self.parse_request(): # An error code has been sent, just exit
return
# next line is where we'd have expect a configuration key somehow
handler = self.WebSocketWSGIHandler(
self.rfile, self.wfile, self.get_stderr(), self.get_environ()
)
handler.request_handler = self # backpointer for logging
handler.run(self.server.get_app()) | python | def handle(self):
self.raw_requestline = self.rfile.readline()
if not self.parse_request(): # An error code has been sent, just exit
return
# next line is where we'd have expect a configuration key somehow
handler = self.WebSocketWSGIHandler(
self.rfile, self.wfile, self.get_stderr(), self.get_environ()
)
handler.request_handler = self # backpointer for logging
handler.run(self.server.get_app()) | [
"def",
"handle",
"(",
"self",
")",
":",
"self",
".",
"raw_requestline",
"=",
"self",
".",
"rfile",
".",
"readline",
"(",
")",
"if",
"not",
"self",
".",
"parse_request",
"(",
")",
":",
"# An error code has been sent, just exit",
"return",
"# next line is where we... | Unfortunately the base class forces us
to override the whole method to actually provide our wsgi handler. | [
"Unfortunately",
"the",
"base",
"class",
"forces",
"us",
"to",
"override",
"the",
"whole",
"method",
"to",
"actually",
"provide",
"our",
"wsgi",
"handler",
"."
] | df0058a148b077c0aff535eb6ee382605c556273 | https://github.com/datawire/quark/blob/df0058a148b077c0aff535eb6ee382605c556273/quarkc/lib/quark_ws4py_fixup.py#L62-L76 |
20,399 | chrisb2/pi_ina219 | ina219.py | INA219.configure | def configure(self, voltage_range=RANGE_32V, gain=GAIN_AUTO,
bus_adc=ADC_12BIT, shunt_adc=ADC_12BIT):
""" Configures and calibrates how the INA219 will take measurements.
Arguments:
voltage_range -- The full scale voltage range, this is either 16V
or 32V represented by one of the following constants;
RANGE_16V, RANGE_32V (default).
gain -- The gain which controls the maximum range of the shunt
voltage represented by one of the following constants;
GAIN_1_40MV, GAIN_2_80MV, GAIN_4_160MV,
GAIN_8_320MV, GAIN_AUTO (default).
bus_adc -- The bus ADC resolution (9, 10, 11, or 12-bit) or
set the number of samples used when averaging results
represent by one of the following constants; ADC_9BIT,
ADC_10BIT, ADC_11BIT, ADC_12BIT (default),
ADC_2SAMP, ADC_4SAMP, ADC_8SAMP, ADC_16SAMP,
ADC_32SAMP, ADC_64SAMP, ADC_128SAMP
shunt_adc -- The shunt ADC resolution (9, 10, 11, or 12-bit) or
set the number of samples used when averaging results
represent by one of the following constants; ADC_9BIT,
ADC_10BIT, ADC_11BIT, ADC_12BIT (default),
ADC_2SAMP, ADC_4SAMP, ADC_8SAMP, ADC_16SAMP,
ADC_32SAMP, ADC_64SAMP, ADC_128SAMP
"""
self.__validate_voltage_range(voltage_range)
self._voltage_range = voltage_range
if self._max_expected_amps is not None:
if gain == self.GAIN_AUTO:
self._auto_gain_enabled = True
self._gain = self._determine_gain(self._max_expected_amps)
else:
self._gain = gain
else:
if gain != self.GAIN_AUTO:
self._gain = gain
else:
self._auto_gain_enabled = True
self._gain = self.GAIN_1_40MV
logging.info('gain set to %.2fV' % self.__GAIN_VOLTS[self._gain])
logging.debug(
self.__LOG_MSG_1 %
(self._shunt_ohms, self.__BUS_RANGE[voltage_range],
self.__GAIN_VOLTS[self._gain],
self.__max_expected_amps_to_string(self._max_expected_amps),
bus_adc, shunt_adc))
self._calibrate(
self.__BUS_RANGE[voltage_range], self.__GAIN_VOLTS[self._gain],
self._max_expected_amps)
self._configure(voltage_range, self._gain, bus_adc, shunt_adc) | python | def configure(self, voltage_range=RANGE_32V, gain=GAIN_AUTO,
bus_adc=ADC_12BIT, shunt_adc=ADC_12BIT):
self.__validate_voltage_range(voltage_range)
self._voltage_range = voltage_range
if self._max_expected_amps is not None:
if gain == self.GAIN_AUTO:
self._auto_gain_enabled = True
self._gain = self._determine_gain(self._max_expected_amps)
else:
self._gain = gain
else:
if gain != self.GAIN_AUTO:
self._gain = gain
else:
self._auto_gain_enabled = True
self._gain = self.GAIN_1_40MV
logging.info('gain set to %.2fV' % self.__GAIN_VOLTS[self._gain])
logging.debug(
self.__LOG_MSG_1 %
(self._shunt_ohms, self.__BUS_RANGE[voltage_range],
self.__GAIN_VOLTS[self._gain],
self.__max_expected_amps_to_string(self._max_expected_amps),
bus_adc, shunt_adc))
self._calibrate(
self.__BUS_RANGE[voltage_range], self.__GAIN_VOLTS[self._gain],
self._max_expected_amps)
self._configure(voltage_range, self._gain, bus_adc, shunt_adc) | [
"def",
"configure",
"(",
"self",
",",
"voltage_range",
"=",
"RANGE_32V",
",",
"gain",
"=",
"GAIN_AUTO",
",",
"bus_adc",
"=",
"ADC_12BIT",
",",
"shunt_adc",
"=",
"ADC_12BIT",
")",
":",
"self",
".",
"__validate_voltage_range",
"(",
"voltage_range",
")",
"self",
... | Configures and calibrates how the INA219 will take measurements.
Arguments:
voltage_range -- The full scale voltage range, this is either 16V
or 32V represented by one of the following constants;
RANGE_16V, RANGE_32V (default).
gain -- The gain which controls the maximum range of the shunt
voltage represented by one of the following constants;
GAIN_1_40MV, GAIN_2_80MV, GAIN_4_160MV,
GAIN_8_320MV, GAIN_AUTO (default).
bus_adc -- The bus ADC resolution (9, 10, 11, or 12-bit) or
set the number of samples used when averaging results
represent by one of the following constants; ADC_9BIT,
ADC_10BIT, ADC_11BIT, ADC_12BIT (default),
ADC_2SAMP, ADC_4SAMP, ADC_8SAMP, ADC_16SAMP,
ADC_32SAMP, ADC_64SAMP, ADC_128SAMP
shunt_adc -- The shunt ADC resolution (9, 10, 11, or 12-bit) or
set the number of samples used when averaging results
represent by one of the following constants; ADC_9BIT,
ADC_10BIT, ADC_11BIT, ADC_12BIT (default),
ADC_2SAMP, ADC_4SAMP, ADC_8SAMP, ADC_16SAMP,
ADC_32SAMP, ADC_64SAMP, ADC_128SAMP | [
"Configures",
"and",
"calibrates",
"how",
"the",
"INA219",
"will",
"take",
"measurements",
"."
] | 2caeb8a387286ac3504905a0d2d478370a691339 | https://github.com/chrisb2/pi_ina219/blob/2caeb8a387286ac3504905a0d2d478370a691339/ina219.py#L113-L166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.