repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.name | def name(self, value):
"""Set name and generate the slug."""
self._name = value
# generate slug
if not self.slug:
self.slug = KnwKB.generate_slug(value) | python | def name(self, value):
"""Set name and generate the slug."""
self._name = value
# generate slug
if not self.slug:
self.slug = KnwKB.generate_slug(value) | [
"def",
"name",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_name",
"=",
"value",
"# generate slug",
"if",
"not",
"self",
".",
"slug",
":",
"self",
".",
"slug",
"=",
"KnwKB",
".",
"generate_slug",
"(",
"value",
")"
] | Set name and generate the slug. | [
"Set",
"name",
"and",
"generate",
"the",
"slug",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L64-L69 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.kbtype | def kbtype(self, value):
"""Set kbtype."""
if value is None:
# set the default value
return
# or set one of the available values
kbtype = value[0] if len(value) > 0 else 'w'
if kbtype not in ['t', 'd', 'w']:
raise ValueError('unknown type "{val... | python | def kbtype(self, value):
"""Set kbtype."""
if value is None:
# set the default value
return
# or set one of the available values
kbtype = value[0] if len(value) > 0 else 'w'
if kbtype not in ['t', 'd', 'w']:
raise ValueError('unknown type "{val... | [
"def",
"kbtype",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"# set the default value",
"return",
"# or set one of the available values",
"kbtype",
"=",
"value",
"[",
"0",
"]",
"if",
"len",
"(",
"value",
")",
">",
"0",
"else",
"'... | Set kbtype. | [
"Set",
"kbtype",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L89-L100 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.to_dict | def to_dict(self):
"""Return a dict representation of KnwKB."""
mydict = {'id': self.id, 'name': self.name,
'description': self.description,
'kbtype': self.kbtype}
if self.kbtype == 'd':
mydict.update((self.kbdefs.to_dict() if self.kbdefs else {}) ... | python | def to_dict(self):
"""Return a dict representation of KnwKB."""
mydict = {'id': self.id, 'name': self.name,
'description': self.description,
'kbtype': self.kbtype}
if self.kbtype == 'd':
mydict.update((self.kbdefs.to_dict() if self.kbdefs else {}) ... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"mydict",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'kbtype'",
":",
"self",
".",
"kbtype",
"}",
"if",
"se... | Return a dict representation of KnwKB. | [
"Return",
"a",
"dict",
"representation",
"of",
"KnwKB",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L106-L114 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.get_kbr_items | def get_kbr_items(self, searchkey="", searchvalue="", searchtype='s'):
"""
Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param sear... | python | def get_kbr_items(self, searchkey="", searchvalue="", searchtype='s'):
"""
Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param sear... | [
"def",
"get_kbr_items",
"(",
"self",
",",
"searchkey",
"=",
"\"\"",
",",
"searchvalue",
"=",
"\"\"",
",",
"searchtype",
"=",
"'s'",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"The function is deprecated. Please use the \"",
"\"`KnwKBRVAL.query_k... | Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param searchtype s=substring, e=exact, sw=startswith
:return a list of dictionaries [{'key'=>... | [
"Return",
"dicts",
"of",
"key",
"and",
"value",
"from",
"a",
"knowledge",
"base",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L116-L146 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.get_kbr_values | def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
"""
Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param sea... | python | def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
"""
Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param sea... | [
"def",
"get_kbr_values",
"(",
"self",
",",
"searchkey",
"=",
"\"\"",
",",
"searchvalue",
"=",
"\"\"",
",",
"searchtype",
"=",
"'s'",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"The function is deprecated. Please use the \"",
"\"`KnwKBRVAL.query_... | Return dicts of 'key' and 'value' from a knowledge base.
:param kb_name the name of the knowledge base
:param searchkey search using this key
:param searchvalue search using this value
:param searchtype s=substring, e=exact, sw=startswith
:return a list of dictionaries [{'key'=>... | [
"Return",
"dicts",
"of",
"key",
"and",
"value",
"from",
"a",
"knowledge",
"base",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L148-L177 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.set_dyn_config | def set_dyn_config(self, field, expression, collection=None):
"""Set dynamic configuration."""
if self.kbdefs:
# update
self.kbdefs.output_tag = field
self.kbdefs.search_expression = expression
self.kbdefs.collection = collection
db.session.mer... | python | def set_dyn_config(self, field, expression, collection=None):
"""Set dynamic configuration."""
if self.kbdefs:
# update
self.kbdefs.output_tag = field
self.kbdefs.search_expression = expression
self.kbdefs.collection = collection
db.session.mer... | [
"def",
"set_dyn_config",
"(",
"self",
",",
"field",
",",
"expression",
",",
"collection",
"=",
"None",
")",
":",
"if",
"self",
".",
"kbdefs",
":",
"# update",
"self",
".",
"kbdefs",
".",
"output_tag",
"=",
"field",
"self",
".",
"kbdefs",
".",
"search_exp... | Set dynamic configuration. | [
"Set",
"dynamic",
"configuration",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L180-L192 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.generate_slug | def generate_slug(name):
"""Generate a slug for the knowledge.
:param name: text to slugify
:return: slugified text
"""
slug = slugify(name)
i = KnwKB.query.filter(db.or_(
KnwKB.slug.like(slug),
KnwKB.slug.like(slug + '-%'),
)).count()
... | python | def generate_slug(name):
"""Generate a slug for the knowledge.
:param name: text to slugify
:return: slugified text
"""
slug = slugify(name)
i = KnwKB.query.filter(db.or_(
KnwKB.slug.like(slug),
KnwKB.slug.like(slug + '-%'),
)).count()
... | [
"def",
"generate_slug",
"(",
"name",
")",
":",
"slug",
"=",
"slugify",
"(",
"name",
")",
"i",
"=",
"KnwKB",
".",
"query",
".",
"filter",
"(",
"db",
".",
"or_",
"(",
"KnwKB",
".",
"slug",
".",
"like",
"(",
"slug",
")",
",",
"KnwKB",
".",
"slug",
... | Generate a slug for the knowledge.
:param name: text to slugify
:return: slugified text | [
"Generate",
"a",
"slug",
"for",
"the",
"knowledge",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L195-L208 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKB.query_exists | def query_exists(filters):
"""Return True if a kb with the given filters exists.
E.g: KnwKB.query_exists(KnwKB.name.like('FAQ'))
:param filters: filter for sqlalchemy
:return: True if kb exists
"""
return db.session.query(
KnwKB.query.filter(
... | python | def query_exists(filters):
"""Return True if a kb with the given filters exists.
E.g: KnwKB.query_exists(KnwKB.name.like('FAQ'))
:param filters: filter for sqlalchemy
:return: True if kb exists
"""
return db.session.query(
KnwKB.query.filter(
... | [
"def",
"query_exists",
"(",
"filters",
")",
":",
"return",
"db",
".",
"session",
".",
"query",
"(",
"KnwKB",
".",
"query",
".",
"filter",
"(",
"filters",
")",
".",
"exists",
"(",
")",
")",
".",
"scalar",
"(",
")"
] | Return True if a kb with the given filters exists.
E.g: KnwKB.query_exists(KnwKB.name.like('FAQ'))
:param filters: filter for sqlalchemy
:return: True if kb exists | [
"Return",
"True",
"if",
"a",
"kb",
"with",
"the",
"given",
"filters",
"exists",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L220-L230 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKBDDEF.to_dict | def to_dict(self):
"""Return a dict representation of KnwKBDDEF."""
return {'field': self.output_tag,
'expression': self.search_expression,
'coll_id': self.id_collection,
'collection': self.collection.name
if self.collection else None} | python | def to_dict(self):
"""Return a dict representation of KnwKBDDEF."""
return {'field': self.output_tag,
'expression': self.search_expression,
'coll_id': self.id_collection,
'collection': self.collection.name
if self.collection else None} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'field'",
":",
"self",
".",
"output_tag",
",",
"'expression'",
":",
"self",
".",
"search_expression",
",",
"'coll_id'",
":",
"self",
".",
"id_collection",
",",
"'collection'",
":",
"self",
".",
"coll... | Return a dict representation of KnwKBDDEF. | [
"Return",
"a",
"dict",
"representation",
"of",
"KnwKBDDEF",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L269-L275 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKBRVAL.query_kb_mappings | def query_kb_mappings(kbid, sortby="to", key="", value="",
match_type="s"):
"""Return a list of all mappings from the given kb, ordered by key.
If key given, give only those with left side (mapFrom) = key.
If value given, give only those with right side (mapTo) = value... | python | def query_kb_mappings(kbid, sortby="to", key="", value="",
match_type="s"):
"""Return a list of all mappings from the given kb, ordered by key.
If key given, give only those with left side (mapFrom) = key.
If value given, give only those with right side (mapTo) = value... | [
"def",
"query_kb_mappings",
"(",
"kbid",
",",
"sortby",
"=",
"\"to\"",
",",
"key",
"=",
"\"\"",
",",
"value",
"=",
"\"\"",
",",
"match_type",
"=",
"\"s\"",
")",
":",
"# query",
"query",
"=",
"KnwKBRVAL",
".",
"query",
".",
"filter",
"(",
"KnwKBRVAL",
"... | Return a list of all mappings from the given kb, ordered by key.
If key given, give only those with left side (mapFrom) = key.
If value given, give only those with right side (mapTo) = value.
:param kb_name: knowledge base name. if "", return all
:param sortby: the sorting criteria ('f... | [
"Return",
"a",
"list",
"of",
"all",
"mappings",
"from",
"the",
"given",
"kb",
"ordered",
"by",
"key",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L305-L344 |
inveniosoftware-attic/invenio-knowledge | invenio_knowledge/models.py | KnwKBRVAL.to_dict | def to_dict(self):
"""Return a dict representation of KnwKBRVAL."""
# FIXME remove 'id' dependency from invenio modules
return {'id': self.m_key + "_" + str(self.id_knwKB),
'key': self.m_key,
'value': self.m_value,
'kbid': self.kb.id if self.kb els... | python | def to_dict(self):
"""Return a dict representation of KnwKBRVAL."""
# FIXME remove 'id' dependency from invenio modules
return {'id': self.m_key + "_" + str(self.id_knwKB),
'key': self.m_key,
'value': self.m_value,
'kbid': self.kb.id if self.kb els... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"# FIXME remove 'id' dependency from invenio modules",
"return",
"{",
"'id'",
":",
"self",
".",
"m_key",
"+",
"\"_\"",
"+",
"str",
"(",
"self",
".",
"id_knwKB",
")",
",",
"'key'",
":",
"self",
".",
"m_key",
",",
"'v... | Return a dict representation of KnwKBRVAL. | [
"Return",
"a",
"dict",
"representation",
"of",
"KnwKBRVAL",
"."
] | train | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/models.py#L346-L353 |
tBaxter/tango-shared-core | build/lib/tango_shared/templatetags/social_tags.py | social_links | def social_links(context, object, user=None, authed=False, downable=False, vote_down_msg=None):
"""
Outputs social links. At minimum, this will be Facebook and Twitter.
But if possible, it will also output voting and watchlist links.
Usage:
{% social_links object %}
{% social_links object user ... | python | def social_links(context, object, user=None, authed=False, downable=False, vote_down_msg=None):
"""
Outputs social links. At minimum, this will be Facebook and Twitter.
But if possible, it will also output voting and watchlist links.
Usage:
{% social_links object %}
{% social_links object user ... | [
"def",
"social_links",
"(",
"context",
",",
"object",
",",
"user",
"=",
"None",
",",
"authed",
"=",
"False",
",",
"downable",
"=",
"False",
",",
"vote_down_msg",
"=",
"None",
")",
":",
"# check if voting available",
"voting",
"=",
"False",
"if",
"hasattr",
... | Outputs social links. At minimum, this will be Facebook and Twitter.
But if possible, it will also output voting and watchlist links.
Usage:
{% social_links object %}
{% social_links object user %}
{% social_links object user authenticated_request %} | [
"Outputs",
"social",
"links",
".",
"At",
"minimum",
"this",
"will",
"be",
"Facebook",
"and",
"Twitter",
".",
"But",
"if",
"possible",
"it",
"will",
"also",
"output",
"voting",
"and",
"watchlist",
"links",
"."
] | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/social_tags.py#L9-L34 |
ErikBjare/pyzenobase | pyzenobase/zenobase_event.py | ZenobaseEvent.clean_data | def clean_data(self):
"""Ensures data is Zenobase compatible and patches it if possible,
if cleaning is not possible it'll raise an appropriate exception"""
# TODO: Do the same for duration/timedelta
if "timestamp" in self:
self._check_timestamp()
if type(self["t... | python | def clean_data(self):
"""Ensures data is Zenobase compatible and patches it if possible,
if cleaning is not possible it'll raise an appropriate exception"""
# TODO: Do the same for duration/timedelta
if "timestamp" in self:
self._check_timestamp()
if type(self["t... | [
"def",
"clean_data",
"(",
"self",
")",
":",
"# TODO: Do the same for duration/timedelta",
"if",
"\"timestamp\"",
"in",
"self",
":",
"self",
".",
"_check_timestamp",
"(",
")",
"if",
"type",
"(",
"self",
"[",
"\"timestamp\"",
"]",
")",
"==",
"list",
":",
"def",
... | Ensures data is Zenobase compatible and patches it if possible,
if cleaning is not possible it'll raise an appropriate exception | [
"Ensures",
"data",
"is",
"Zenobase",
"compatible",
"and",
"patches",
"it",
"if",
"possible",
"if",
"cleaning",
"is",
"not",
"possible",
"it",
"ll",
"raise",
"an",
"appropriate",
"exception"
] | train | https://github.com/ErikBjare/pyzenobase/blob/eb0572c7441a350bf5578bc5287f3be53d32ea19/pyzenobase/zenobase_event.py#L23-L45 |
shi-cong/PYSTUDY | PYSTUDY/middleware/rabbitmqlib.py | _RabbitmqTask.run | def run(self):
"""
线程启动
:return:
"""
try:
super().run()
except Exception as e:
print(trace_info())
finally:
if not self.no_ack:
# 如果为True,任务结束后需要确认
self.ch.basic_ack(delivery_tag=self.method.deliv... | python | def run(self):
"""
线程启动
:return:
"""
try:
super().run()
except Exception as e:
print(trace_info())
finally:
if not self.no_ack:
# 如果为True,任务结束后需要确认
self.ch.basic_ack(delivery_tag=self.method.deliv... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"super",
"(",
")",
".",
"run",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"trace_info",
"(",
")",
")",
"finally",
":",
"if",
"not",
"self",
".",
"no_ack",
":",
"# 如果为True,任务结束后需要确... | 线程启动
:return: | [
"线程启动",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/middleware/rabbitmqlib.py#L59-L71 |
shi-cong/PYSTUDY | PYSTUDY/middleware/rabbitmqlib.py | RabbitmqCustomerMS.send_task | def send_task(self, body):
"""
发送任务到任务队列
:param body: 消息
:return:
"""
self.ch.basic_publish(exchange='', routing_key=self.task_queue,
properties=pika.BasicProperties(delivery_mode=2), body=body) | python | def send_task(self, body):
"""
发送任务到任务队列
:param body: 消息
:return:
"""
self.ch.basic_publish(exchange='', routing_key=self.task_queue,
properties=pika.BasicProperties(delivery_mode=2), body=body) | [
"def",
"send_task",
"(",
"self",
",",
"body",
")",
":",
"self",
".",
"ch",
".",
"basic_publish",
"(",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"self",
".",
"task_queue",
",",
"properties",
"=",
"pika",
".",
"BasicProperties",
"(",
"delivery_mode",
... | 发送任务到任务队列
:param body: 消息
:return: | [
"发送任务到任务队列",
":",
"param",
"body",
":",
"消息",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/middleware/rabbitmqlib.py#L98-L105 |
shi-cong/PYSTUDY | PYSTUDY/middleware/rabbitmqlib.py | RabbitmqCustomerMS.store_data | def store_data(self, data):
"""
存储数据到存储队列
:param data: 数据
:return:
"""
self.ch.basic_publish(exchange='', routing_key=self.store_queue,
properties=pika.BasicProperties(delivery_mode=2), body=data) | python | def store_data(self, data):
"""
存储数据到存储队列
:param data: 数据
:return:
"""
self.ch.basic_publish(exchange='', routing_key=self.store_queue,
properties=pika.BasicProperties(delivery_mode=2), body=data) | [
"def",
"store_data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"ch",
".",
"basic_publish",
"(",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"self",
".",
"store_queue",
",",
"properties",
"=",
"pika",
".",
"BasicProperties",
"(",
"delivery_mode",... | 存储数据到存储队列
:param data: 数据
:return: | [
"存储数据到存储队列",
":",
"param",
"data",
":",
"数据",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/middleware/rabbitmqlib.py#L107-L114 |
shi-cong/PYSTUDY | PYSTUDY/middleware/rabbitmqlib.py | RabbitmqCustomerMS.serv_forever | def serv_forever(self, func):
"""
启动消费者服务程序
:param func: 回调函数
:return:
"""
# 如果任务队列不为空则声明队列
if self.task_queue:
self.ch.queue_declare(
queue=self.task_queue, durable=self.durable)
if self.store_queue:
self.ch.queue_d... | python | def serv_forever(self, func):
"""
启动消费者服务程序
:param func: 回调函数
:return:
"""
# 如果任务队列不为空则声明队列
if self.task_queue:
self.ch.queue_declare(
queue=self.task_queue, durable=self.durable)
if self.store_queue:
self.ch.queue_d... | [
"def",
"serv_forever",
"(",
"self",
",",
"func",
")",
":",
"# 如果任务队列不为空则声明队列",
"if",
"self",
".",
"task_queue",
":",
"self",
".",
"ch",
".",
"queue_declare",
"(",
"queue",
"=",
"self",
".",
"task_queue",
",",
"durable",
"=",
"self",
".",
"durable",
")",
... | 启动消费者服务程序
:param func: 回调函数
:return: | [
"启动消费者服务程序",
":",
"param",
"func",
":",
"回调函数",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/middleware/rabbitmqlib.py#L116-L154 |
shi-cong/PYSTUDY | PYSTUDY/middleware/rabbitmqlib.py | RabbitmqProducter.produce | def produce(self, func):
"""
启动生产者
:param func: 生产者回调函数
:return:
"""
# 声明队列
if not self.task_queue:
self.ch.queue_declare(queue=self.task_queue, durable=self.durable)
func(self) | python | def produce(self, func):
"""
启动生产者
:param func: 生产者回调函数
:return:
"""
# 声明队列
if not self.task_queue:
self.ch.queue_declare(queue=self.task_queue, durable=self.durable)
func(self) | [
"def",
"produce",
"(",
"self",
",",
"func",
")",
":",
"# 声明队列",
"if",
"not",
"self",
".",
"task_queue",
":",
"self",
".",
"ch",
".",
"queue_declare",
"(",
"queue",
"=",
"self",
".",
"task_queue",
",",
"durable",
"=",
"self",
".",
"durable",
")",
"fun... | 启动生产者
:param func: 生产者回调函数
:return: | [
"启动生产者",
":",
"param",
"func",
":",
"生产者回调函数",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/middleware/rabbitmqlib.py#L260-L269 |
mattupstate/cubric | cubric/utils.py | render | def render(obj):
"""Convienently render strings with the fabric context"""
def get_v(v):
return v % env if isinstance(v, basestring) else v
if isinstance(obj, types.StringType):
return obj % env
elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType):
rv = []
... | python | def render(obj):
"""Convienently render strings with the fabric context"""
def get_v(v):
return v % env if isinstance(v, basestring) else v
if isinstance(obj, types.StringType):
return obj % env
elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType):
rv = []
... | [
"def",
"render",
"(",
"obj",
")",
":",
"def",
"get_v",
"(",
"v",
")",
":",
"return",
"v",
"%",
"env",
"if",
"isinstance",
"(",
"v",
",",
"basestring",
")",
"else",
"v",
"if",
"isinstance",
"(",
"obj",
",",
"types",
".",
"StringType",
")",
":",
"r... | Convienently render strings with the fabric context | [
"Convienently",
"render",
"strings",
"with",
"the",
"fabric",
"context"
] | train | https://github.com/mattupstate/cubric/blob/a648ce00e4467cd14d71e754240ef6c1f87a34b5/cubric/utils.py#L105-L121 |
cdeboever3/cdpybio | cdpybio/moodsext.py | _filter_variant_motif_res | def _filter_variant_motif_res(
motif_res,
variant_start,
variant_end,
motif_length,
seq,
):
"""
Remove MOODS motif hits that don't overlap the variant of interest.
Parameters
----------
motif_res : list
Result from MOODS search like [(21, 3.947748787969809), (-38... | python | def _filter_variant_motif_res(
motif_res,
variant_start,
variant_end,
motif_length,
seq,
):
"""
Remove MOODS motif hits that don't overlap the variant of interest.
Parameters
----------
motif_res : list
Result from MOODS search like [(21, 3.947748787969809), (-38... | [
"def",
"_filter_variant_motif_res",
"(",
"motif_res",
",",
"variant_start",
",",
"variant_end",
",",
"motif_length",
",",
"seq",
",",
")",
":",
"import",
"MOODS",
"remove",
"=",
"[",
"]",
"for",
"r",
"in",
"motif_res",
":",
"motif_start",
"=",
"r",
"[",
"0... | Remove MOODS motif hits that don't overlap the variant of interest.
Parameters
----------
motif_res : list
Result from MOODS search like [(21, 3.947748787969809), (-38,
3.979759977155675)].
variant_start : int
Relative start position of the allele string in seq (not... | [
"Remove",
"MOODS",
"motif",
"hits",
"that",
"don",
"t",
"overlap",
"the",
"variant",
"of",
"interest",
".",
"Parameters",
"----------",
"motif_res",
":",
"list",
"Result",
"from",
"MOODS",
"search",
"like",
"[",
"(",
"21",
"3",
".",
"947748787969809",
")",
... | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/moodsext.py#L3-L54 |
cdeboever3/cdpybio | cdpybio/moodsext.py | find_motif_disruptions | def find_motif_disruptions(
position,
ref,
alt,
genome_fasta,
matrices,
):
"""
Determine whether there is a difference between the ref and alt
alleles for TF binding. Requires samtools in your path.
Parameters
----------
position : str
Zero based genomic coor... | python | def find_motif_disruptions(
position,
ref,
alt,
genome_fasta,
matrices,
):
"""
Determine whether there is a difference between the ref and alt
alleles for TF binding. Requires samtools in your path.
Parameters
----------
position : str
Zero based genomic coor... | [
"def",
"find_motif_disruptions",
"(",
"position",
",",
"ref",
",",
"alt",
",",
"genome_fasta",
",",
"matrices",
",",
")",
":",
"import",
"subprocess",
"import",
"MOODS",
"# import pybedtools as pbt",
"max_motif_length",
"=",
"max",
"(",
"[",
"x",
".",
"shape",
... | Determine whether there is a difference between the ref and alt
alleles for TF binding. Requires samtools in your path.
Parameters
----------
position : str
Zero based genomic coordinates of the reference allele of the form
chrom:start-end (chr5:100-101 for a SNV for instance). The ... | [
"Determine",
"whether",
"there",
"is",
"a",
"difference",
"between",
"the",
"ref",
"and",
"alt",
"alleles",
"for",
"TF",
"binding",
".",
"Requires",
"samtools",
"in",
"your",
"path",
".",
"Parameters",
"----------",
"position",
":",
"str",
"Zero",
"based",
"... | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/moodsext.py#L56-L153 |
jcalogovic/lightning | stormstats/misc.py | read_wwln | def read_wwln(file):
"""Read WWLN file"""
tmp = pd.read_csv(file, parse_dates=True, header=None,
names=['date', 'time', 'lat', 'lon', 'err', '#sta'])
# Generate a list of datetime objects with time to miliseconds
list_dts = []
for dvals, tvals, in zip(tmp['date'], tmp['time']):... | python | def read_wwln(file):
"""Read WWLN file"""
tmp = pd.read_csv(file, parse_dates=True, header=None,
names=['date', 'time', 'lat', 'lon', 'err', '#sta'])
# Generate a list of datetime objects with time to miliseconds
list_dts = []
for dvals, tvals, in zip(tmp['date'], tmp['time']):... | [
"def",
"read_wwln",
"(",
"file",
")",
":",
"tmp",
"=",
"pd",
".",
"read_csv",
"(",
"file",
",",
"parse_dates",
"=",
"True",
",",
"header",
"=",
"None",
",",
"names",
"=",
"[",
"'date'",
",",
"'time'",
",",
"'lat'",
",",
"'lon'",
",",
"'err'",
",",
... | Read WWLN file | [
"Read",
"WWLN",
"file"
] | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L15-L26 |
jcalogovic/lightning | stormstats/misc.py | wwln_to_geopandas | def wwln_to_geopandas(file):
"""Read data from Blitzorg first using pandas.read_csv for convienence, and
then convert lat, lon points to a shaleply geometry POINT type.
Finally put this gemoetry into a geopandas dataframe and return it."""
tmp = pd.read_csv(file, parse_dates=True, header=None,
... | python | def wwln_to_geopandas(file):
"""Read data from Blitzorg first using pandas.read_csv for convienence, and
then convert lat, lon points to a shaleply geometry POINT type.
Finally put this gemoetry into a geopandas dataframe and return it."""
tmp = pd.read_csv(file, parse_dates=True, header=None,
... | [
"def",
"wwln_to_geopandas",
"(",
"file",
")",
":",
"tmp",
"=",
"pd",
".",
"read_csv",
"(",
"file",
",",
"parse_dates",
"=",
"True",
",",
"header",
"=",
"None",
",",
"names",
"=",
"[",
"'date'",
",",
"'time'",
",",
"'lat'",
",",
"'lon'",
",",
"'err'",... | Read data from Blitzorg first using pandas.read_csv for convienence, and
then convert lat, lon points to a shaleply geometry POINT type.
Finally put this gemoetry into a geopandas dataframe and return it. | [
"Read",
"data",
"from",
"Blitzorg",
"first",
"using",
"pandas",
".",
"read_csv",
"for",
"convienence",
"and",
"then",
"convert",
"lat",
"lon",
"points",
"to",
"a",
"shaleply",
"geometry",
"POINT",
"type",
".",
"Finally",
"put",
"this",
"gemoetry",
"into",
"a... | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L29-L40 |
jcalogovic/lightning | stormstats/misc.py | gen_listfiles | def gen_listfiles(ext, data_path=current_path, start_date=None, end_date=None):
"""**Generate list of files in data directory**
Using a specified data path and extension generate list of files in data
directory. If start_date and end_date aren't specified, all files in the
data directory are selected.
... | python | def gen_listfiles(ext, data_path=current_path, start_date=None, end_date=None):
"""**Generate list of files in data directory**
Using a specified data path and extension generate list of files in data
directory. If start_date and end_date aren't specified, all files in the
data directory are selected.
... | [
"def",
"gen_listfiles",
"(",
"ext",
",",
"data_path",
"=",
"current_path",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
")",
":",
"# make list of all files in data directory with certain extension ext",
"listfiles",
"=",
"[",
"fn",
"for",
"fn",
"in"... | **Generate list of files in data directory**
Using a specified data path and extension generate list of files in data
directory. If start_date and end_date aren't specified, all files in the
data directory are selected.
:paramter data_path: string
:parameter ext: string
:parameter start_date: ... | [
"**",
"Generate",
"list",
"of",
"files",
"in",
"data",
"directory",
"**"
] | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L43-L78 |
jcalogovic/lightning | stormstats/misc.py | count_lightning | def count_lightning(datain, time_step):
"""**Count lightning strikes detected within a defined time_step**
Generate time intervals according to the time_step defined and count
lightning strikes in these intervals. Statistics are also calculated for
lightning detection errors and the number of stations ... | python | def count_lightning(datain, time_step):
"""**Count lightning strikes detected within a defined time_step**
Generate time intervals according to the time_step defined and count
lightning strikes in these intervals. Statistics are also calculated for
lightning detection errors and the number of stations ... | [
"def",
"count_lightning",
"(",
"datain",
",",
"time_step",
")",
":",
"if",
"(",
"1440",
"%",
"time_step",
"==",
"0",
")",
":",
"# check if time_step is multiple of 1 day",
"i",
"=",
"0",
"# run for loop for all time steps in one day",
"for",
"time_interval",
"in",
"... | **Count lightning strikes detected within a defined time_step**
Generate time intervals according to the time_step defined and count
lightning strikes in these intervals. Statistics are also calculated for
lightning detection errors and the number of stations and added to an
output dataframe. Time stam... | [
"**",
"Count",
"lightning",
"strikes",
"detected",
"within",
"a",
"defined",
"time_step",
"**"
] | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L81-L131 |
jcalogovic/lightning | stormstats/misc.py | gen_stats | def gen_stats(datain):
"""**Calculate lightning statitics and return a dictionary**
Using a raw data in certain time interval calculate mean, std, min, max value for detection
error or number of stations.
:paramter datain: vector with detection error or number of stations
:Example:
>>> gen_s... | python | def gen_stats(datain):
"""**Calculate lightning statitics and return a dictionary**
Using a raw data in certain time interval calculate mean, std, min, max value for detection
error or number of stations.
:paramter datain: vector with detection error or number of stations
:Example:
>>> gen_s... | [
"def",
"gen_stats",
"(",
"datain",
")",
":",
"tmp_dic",
"=",
"{",
"}",
"tmp_dic",
"[",
"'count'",
"]",
"=",
"len",
"(",
"datain",
")",
"# if there is no lightning strikes set nan values for all stats parameters",
"if",
"(",
"tmp_dic",
"[",
"'count'",
"]",
"==",
... | **Calculate lightning statitics and return a dictionary**
Using a raw data in certain time interval calculate mean, std, min, max value for detection
error or number of stations.
:paramter datain: vector with detection error or number of stations
:Example:
>>> gen_stats(lighning_data['#sta']) | [
"**",
"Calculate",
"lightning",
"statitics",
"and",
"return",
"a",
"dictionary",
"**"
] | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L134-L159 |
jcalogovic/lightning | stormstats/misc.py | gen_time_intervals | def gen_time_intervals(start, end, delta):
"""Create time intervals with timedelta periods using datetime for start
and end
"""
curr = start
while curr < end:
yield curr
curr += delta | python | def gen_time_intervals(start, end, delta):
"""Create time intervals with timedelta periods using datetime for start
and end
"""
curr = start
while curr < end:
yield curr
curr += delta | [
"def",
"gen_time_intervals",
"(",
"start",
",",
"end",
",",
"delta",
")",
":",
"curr",
"=",
"start",
"while",
"curr",
"<",
"end",
":",
"yield",
"curr",
"curr",
"+=",
"delta"
] | Create time intervals with timedelta periods using datetime for start
and end | [
"Create",
"time",
"intervals",
"with",
"timedelta",
"periods",
"using",
"datetime",
"for",
"start",
"and",
"end"
] | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L162-L169 |
jcalogovic/lightning | stormstats/misc.py | extract_date | def extract_date(value):
"""
Convert timestamp to datetime and set everything to zero except a date
"""
dtime = value.to_datetime()
dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) -
timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond... | python | def extract_date(value):
"""
Convert timestamp to datetime and set everything to zero except a date
"""
dtime = value.to_datetime()
dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) -
timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond... | [
"def",
"extract_date",
"(",
"value",
")",
":",
"dtime",
"=",
"value",
".",
"to_datetime",
"(",
")",
"dtime",
"=",
"(",
"dtime",
"-",
"timedelta",
"(",
"hours",
"=",
"dtime",
".",
"hour",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"dtime",
".",
"minu... | Convert timestamp to datetime and set everything to zero except a date | [
"Convert",
"timestamp",
"to",
"datetime",
"and",
"set",
"everything",
"to",
"zero",
"except",
"a",
"date"
] | train | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L172-L179 |
krukas/Trionyx | trionyx/trionyx/middleware.py | LoginRequiredMiddleware.process_request | def process_request(self, request):
"""Check if user is logged in"""
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(re... | python | def process_request(self, request):
"""Check if user is logged in"""
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(re... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"assert",
"hasattr",
"(",
"request",
",",
"'user'",
")",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"path",
"=",
"request",
".",
"path_info",
".",
"lstrip"... | Check if user is logged in | [
"Check",
"if",
"user",
"is",
"logged",
"in"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/middleware.py#L32-L38 |
MacHu-GWU/angora-project | angora/dataIO/js.py | dump_js | def dump_js(js, abspath, precision=None,
fastmode=False, replace=False, compress=False, enable_verbose=True):
"""Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``sa... | python | def dump_js(js, abspath, precision=None,
fastmode=False, replace=False, compress=False, enable_verbose=True):
"""Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``sa... | [
"def",
"dump_js",
"(",
"js",
",",
"abspath",
",",
"precision",
"=",
"None",
",",
"fastmode",
"=",
"False",
",",
"replace",
"=",
"False",
",",
"compress",
"=",
"False",
",",
"enable_verbose",
"=",
"True",
")",
":",
"abspath",
"=",
"str",
"(",
"abspath",... | Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz``
(for compressed json).
:type abspath: string
:param ... | [
"Dump",
"Json",
"serializable",
"object",
"to",
"file",
".",
"Provides",
"multiple",
"choice",
"to",
"customize",
"the",
"behavior",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/js.py#L149-L286 |
MacHu-GWU/angora-project | angora/dataIO/js.py | js2str | def js2str(js, sort_keys=True, indent=4):
"""Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
}
**中文文... | python | def js2str(js, sort_keys=True, indent=4):
"""Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
}
**中文文... | [
"def",
"js2str",
"(",
"js",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"js",
",",
"sort_keys",
"=",
"sort_keys",
",",
"indent",
"=",
"indent",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\... | Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
}
**中文文档**
将可Json化的Python对象转化成格式化的字符串。 | [
"Encode",
"js",
"to",
"nicely",
"formatted",
"human",
"readable",
"string",
".",
"(",
"utf",
"-",
"8",
"encoding",
")"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/js.py#L367-L385 |
MacHu-GWU/angora-project | angora/dataIO/js.py | prt_js | def prt_js(js, sort_keys=True, indent=4):
"""Print Json in pretty format.
There's a standard module pprint, can pretty print python dict and list.
But it doesn't support sorted key. That why we need this func.
Usage::
>>> from weatherlab.lib.dataIO.js import prt_js
>>> prt_js({"a": 1, ... | python | def prt_js(js, sort_keys=True, indent=4):
"""Print Json in pretty format.
There's a standard module pprint, can pretty print python dict and list.
But it doesn't support sorted key. That why we need this func.
Usage::
>>> from weatherlab.lib.dataIO.js import prt_js
>>> prt_js({"a": 1, ... | [
"def",
"prt_js",
"(",
"js",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
":",
"print",
"(",
"js2str",
"(",
"js",
",",
"sort_keys",
",",
"indent",
")",
")"
] | Print Json in pretty format.
There's a standard module pprint, can pretty print python dict and list.
But it doesn't support sorted key. That why we need this func.
Usage::
>>> from weatherlab.lib.dataIO.js import prt_js
>>> prt_js({"a": 1, "b": 2})
{
"a": 1,
... | [
"Print",
"Json",
"in",
"pretty",
"format",
".",
"There",
"s",
"a",
"standard",
"module",
"pprint",
"can",
"pretty",
"print",
"python",
"dict",
"and",
"list",
".",
"But",
"it",
"doesn",
"t",
"support",
"sorted",
"key",
".",
"That",
"why",
"we",
"need",
... | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/js.py#L388-L406 |
MacHu-GWU/angora-project | angora/crawler/downloader.py | string_SizeInBytes | def string_SizeInBytes(size_in_bytes):
"""Make ``size in bytes`` human readable.
Doesn"t support size greater than 1000PB.
Usage::
>>> from __future__ import print_function
>>> from weatherlab.lib.filesystem.windowsexplorer import string_SizeInBytes
>>> print(string_SizeInBytes(100... | python | def string_SizeInBytes(size_in_bytes):
"""Make ``size in bytes`` human readable.
Doesn"t support size greater than 1000PB.
Usage::
>>> from __future__ import print_function
>>> from weatherlab.lib.filesystem.windowsexplorer import string_SizeInBytes
>>> print(string_SizeInBytes(100... | [
"def",
"string_SizeInBytes",
"(",
"size_in_bytes",
")",
":",
"res",
",",
"by",
"=",
"divmod",
"(",
"size_in_bytes",
",",
"1024",
")",
"res",
",",
"kb",
"=",
"divmod",
"(",
"res",
",",
"1024",
")",
"res",
",",
"mb",
"=",
"divmod",
"(",
"res",
",",
"... | Make ``size in bytes`` human readable.
Doesn"t support size greater than 1000PB.
Usage::
>>> from __future__ import print_function
>>> from weatherlab.lib.filesystem.windowsexplorer import string_SizeInBytes
>>> print(string_SizeInBytes(100))
100 B
>>> print(string_Size... | [
"Make",
"size",
"in",
"bytes",
"human",
"readable",
".",
"Doesn",
"t",
"support",
"size",
"greater",
"than",
"1000PB",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/crawler/downloader.py#L25-L63 |
MacHu-GWU/angora-project | angora/crawler/downloader.py | download_url | def download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True):
"""A simple url binary content download function with progress info.
Warning: this function will silently overwrite existing file.
"""
msg = Messenger()
if enable_verbose:
msg.on()
else:
msg.off()... | python | def download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True):
"""A simple url binary content download function with progress info.
Warning: this function will silently overwrite existing file.
"""
msg = Messenger()
if enable_verbose:
msg.on()
else:
msg.off()... | [
"def",
"download_url",
"(",
"url",
",",
"save_as",
",",
"iter_size",
"=",
"_default_iter_size",
",",
"enable_verbose",
"=",
"True",
")",
":",
"msg",
"=",
"Messenger",
"(",
")",
"if",
"enable_verbose",
":",
"msg",
".",
"on",
"(",
")",
"else",
":",
"msg",
... | A simple url binary content download function with progress info.
Warning: this function will silently overwrite existing file. | [
"A",
"simple",
"url",
"binary",
"content",
"download",
"function",
"with",
"progress",
"info",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/crawler/downloader.py#L66-L98 |
Vito2015/pyextend | pyextend/formula/geo/geohash.py | decode | def decode(hashcode, delta=False):
"""
decode a hashcode and get center coordinate, and distance between center and outer border
"""
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 90.0/(1 << lat_length)
longitude_delta = 180.... | python | def decode(hashcode, delta=False):
"""
decode a hashcode and get center coordinate, and distance between center and outer border
"""
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 90.0/(1 << lat_length)
longitude_delta = 180.... | [
"def",
"decode",
"(",
"hashcode",
",",
"delta",
"=",
"False",
")",
":",
"lat",
",",
"lon",
",",
"lat_length",
",",
"lon_length",
"=",
"_decode_c2i",
"(",
"hashcode",
")",
"if",
"hasattr",
"(",
"float",
",",
"\"fromhex\"",
")",
":",
"latitude_delta",
"=",... | decode a hashcode and get center coordinate, and distance between center and outer border | [
"decode",
"a",
"hashcode",
"and",
"get",
"center",
"coordinate",
"and",
"distance",
"between",
"center",
"and",
"outer",
"border"
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/geo/geohash.py#L152-L180 |
Vito2015/pyextend | pyextend/formula/geo/geohash.py | bbox | def bbox(hashcode):
"""
decode a hashcode and get north, south, east and west border.
"""
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 180.0/(1 << lat_length)
longitude_delta = 360.0/(1 << lon_length)
latitude = _int... | python | def bbox(hashcode):
"""
decode a hashcode and get north, south, east and west border.
"""
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 180.0/(1 << lat_length)
longitude_delta = 360.0/(1 << lon_length)
latitude = _int... | [
"def",
"bbox",
"(",
"hashcode",
")",
":",
"lat",
",",
"lon",
",",
"lat_length",
",",
"lon_length",
"=",
"_decode_c2i",
"(",
"hashcode",
")",
"if",
"hasattr",
"(",
"float",
",",
"\"fromhex\"",
")",
":",
"latitude_delta",
"=",
"180.0",
"/",
"(",
"1",
"<<... | decode a hashcode and get north, south, east and west border. | [
"decode",
"a",
"hashcode",
"and",
"get",
"north",
"south",
"east",
"and",
"west",
"border",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/geo/geohash.py#L189-L217 |
littlemo/moear-api-common | moear_api_common/utils/kindlegen.py | find_kindlegen_prog | def find_kindlegen_prog(path=None):
'''
获取kindlegen程序路径
该方法会检索系统 ``PATH`` 路径,查找包含 ``kindlegen`` 文件的路径,
并返回该文件的绝对路径。若不存在则返回 ``None``
.. attention::
检索 ``PATH`` 路径前,会优先寻找指定路径,并在检索到第一个符合文件后立刻返回
:param str path: 关键字参数,若传入,则优先检测该路径下是否存在 kindlegen 程序
:return: kindlegen的绝对路径
:rtype:... | python | def find_kindlegen_prog(path=None):
'''
获取kindlegen程序路径
该方法会检索系统 ``PATH`` 路径,查找包含 ``kindlegen`` 文件的路径,
并返回该文件的绝对路径。若不存在则返回 ``None``
.. attention::
检索 ``PATH`` 路径前,会优先寻找指定路径,并在检索到第一个符合文件后立刻返回
:param str path: 关键字参数,若传入,则优先检测该路径下是否存在 kindlegen 程序
:return: kindlegen的绝对路径
:rtype:... | [
"def",
"find_kindlegen_prog",
"(",
"path",
"=",
"None",
")",
":",
"try",
":",
"kindlegen_prog",
"=",
"'kindlegen'",
"# search in current directory and PATH to find kinglegen",
"path_list",
"=",
"[",
"path",
"]",
"path_list",
".",
"extend",
"(",
"os",
".",
"getenv",
... | 获取kindlegen程序路径
该方法会检索系统 ``PATH`` 路径,查找包含 ``kindlegen`` 文件的路径,
并返回该文件的绝对路径。若不存在则返回 ``None``
.. attention::
检索 ``PATH`` 路径前,会优先寻找指定路径,并在检索到第一个符合文件后立刻返回
:param str path: 关键字参数,若传入,则优先检测该路径下是否存在 kindlegen 程序
:return: kindlegen的绝对路径
:rtype: str | [
"获取kindlegen程序路径"
] | train | https://github.com/littlemo/moear-api-common/blob/2a89a052d92592dd8e67bd50ec2fadc0219ac5d0/moear_api_common/utils/kindlegen.py#L4-L32 |
rsalmaso/django-fluo | fluo/admin/nested.py | NestedModelAdmin.save_formset | def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
for form in formset.forms:
if hasattr(form, 'nested_formsets') and form not in formset.deleted_forms:
for nested_formset in... | python | def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
for form in formset.forms:
if hasattr(form, 'nested_formsets') and form not in formset.deleted_forms:
for nested_formset in... | [
"def",
"save_formset",
"(",
"self",
",",
"request",
",",
"form",
",",
"formset",
",",
"change",
")",
":",
"formset",
".",
"save",
"(",
")",
"for",
"form",
"in",
"formset",
".",
"forms",
":",
"if",
"hasattr",
"(",
"form",
",",
"'nested_formsets'",
")",
... | Given an inline formset save it to the database. | [
"Given",
"an",
"inline",
"formset",
"save",
"it",
"to",
"the",
"database",
"."
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/admin/nested.py#L72-L81 |
rsalmaso/django-fluo | fluo/admin/nested.py | NestedModelAdmin.all_valid_with_nesting | def all_valid_with_nesting(self, formsets):
"Recursively validate all nested formsets"
if not all_valid(formsets):
return False
for formset in formsets:
if not formset.is_bound:
pass
for form in formset:
if hasattr(form, 'neste... | python | def all_valid_with_nesting(self, formsets):
"Recursively validate all nested formsets"
if not all_valid(formsets):
return False
for formset in formsets:
if not formset.is_bound:
pass
for form in formset:
if hasattr(form, 'neste... | [
"def",
"all_valid_with_nesting",
"(",
"self",
",",
"formsets",
")",
":",
"if",
"not",
"all_valid",
"(",
"formsets",
")",
":",
"return",
"False",
"for",
"formset",
"in",
"formsets",
":",
"if",
"not",
"formset",
".",
"is_bound",
":",
"pass",
"for",
"form",
... | Recursively validate all nested formsets | [
"Recursively",
"validate",
"all",
"nested",
"formsets"
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/admin/nested.py#L161-L178 |
nsavch/python-xonotic-db | xon_db/__init__.py | XonoticDB.parse_line | def parse_line(self, line: str):
"""
Parse a line from database
:param line: line to parse
"""
for i in KEYPAIR_RE.finditer(line):
key = i.group(1)
value = urllib.parse.unquote(i.group(2))
self[key] = value | python | def parse_line(self, line: str):
"""
Parse a line from database
:param line: line to parse
"""
for i in KEYPAIR_RE.finditer(line):
key = i.group(1)
value = urllib.parse.unquote(i.group(2))
self[key] = value | [
"def",
"parse_line",
"(",
"self",
",",
"line",
":",
"str",
")",
":",
"for",
"i",
"in",
"KEYPAIR_RE",
".",
"finditer",
"(",
"line",
")",
":",
"key",
"=",
"i",
".",
"group",
"(",
"1",
")",
"value",
"=",
"urllib",
".",
"parse",
".",
"unquote",
"(",
... | Parse a line from database
:param line: line to parse | [
"Parse",
"a",
"line",
"from",
"database",
":",
"param",
"line",
":",
"line",
"to",
"parse"
] | train | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/__init__.py#L40-L48 |
nsavch/python-xonotic-db | xon_db/__init__.py | XonoticDB.save | def save(self, file_path):
"""
Write database to a file. If a file with the specified name exists it's backed up
:param file_path: file path
"""
if os.path.isfile(file_path):
with open(self.get_backup_file_name(file_path), 'w') as d:
with open(file_pat... | python | def save(self, file_path):
"""
Write database to a file. If a file with the specified name exists it's backed up
:param file_path: file path
"""
if os.path.isfile(file_path):
with open(self.get_backup_file_name(file_path), 'w') as d:
with open(file_pat... | [
"def",
"save",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"self",
".",
"get_backup_file_name",
"(",
"file_path",
")",
",",
"'w'",
")",
"as",
"d",
":",
"with",
"o... | Write database to a file. If a file with the specified name exists it's backed up
:param file_path: file path | [
"Write",
"database",
"to",
"a",
"file",
".",
"If",
"a",
"file",
"with",
"the",
"specified",
"name",
"exists",
"it",
"s",
"backed",
"up",
":",
"param",
"file_path",
":",
"file",
"path"
] | train | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/__init__.py#L78-L95 |
nsavch/python-xonotic-db | xon_db/__init__.py | XonoticDB.filter | def filter(self, key_pattern='*', is_regex=False):
"""
Filter database key by pattern
:param key_pattern: pattern (either glob or regex)
:param is_regex: should be True if the pattern is regex
:return: iterator of (key, value) pairs
"""
if is_regex:
if... | python | def filter(self, key_pattern='*', is_regex=False):
"""
Filter database key by pattern
:param key_pattern: pattern (either glob or regex)
:param is_regex: should be True if the pattern is regex
:return: iterator of (key, value) pairs
"""
if is_regex:
if... | [
"def",
"filter",
"(",
"self",
",",
"key_pattern",
"=",
"'*'",
",",
"is_regex",
"=",
"False",
")",
":",
"if",
"is_regex",
":",
"if",
"isinstance",
"(",
"key_pattern",
",",
"str",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"key_pattern",
")",
"... | Filter database key by pattern
:param key_pattern: pattern (either glob or regex)
:param is_regex: should be True if the pattern is regex
:return: iterator of (key, value) pairs | [
"Filter",
"database",
"key",
"by",
"pattern",
":",
"param",
"key_pattern",
":",
"pattern",
"(",
"either",
"glob",
"or",
"regex",
")",
":",
"param",
"is_regex",
":",
"should",
"be",
"True",
"if",
"the",
"pattern",
"is",
"regex",
":",
"return",
":",
"itera... | train | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/__init__.py#L97-L113 |
nsavch/python-xonotic-db | xon_db/__init__.py | XonoticDB.remove_cts_record | def remove_cts_record(self, map, position):
"""
Remove a CTS record
:param map:
:param position:
:return:
"""
def _key1(pos):
return '%s/cts100record/crypto_idfp%s' % (map, pos)
def _key2(pos):
return '%s/cts100record/time%s' % (ma... | python | def remove_cts_record(self, map, position):
"""
Remove a CTS record
:param map:
:param position:
:return:
"""
def _key1(pos):
return '%s/cts100record/crypto_idfp%s' % (map, pos)
def _key2(pos):
return '%s/cts100record/time%s' % (ma... | [
"def",
"remove_cts_record",
"(",
"self",
",",
"map",
",",
"position",
")",
":",
"def",
"_key1",
"(",
"pos",
")",
":",
"return",
"'%s/cts100record/crypto_idfp%s'",
"%",
"(",
"map",
",",
"pos",
")",
"def",
"_key2",
"(",
"pos",
")",
":",
"return",
"'%s/cts1... | Remove a CTS record
:param map:
:param position:
:return: | [
"Remove",
"a",
"CTS",
"record",
":",
"param",
"map",
":",
":",
"param",
"position",
":",
":",
"return",
":"
] | train | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/__init__.py#L115-L136 |
nsavch/python-xonotic-db | xon_db/__init__.py | XonoticDB.remove_all_cts_records_by | def remove_all_cts_records_by(self, crypto_idfp):
"""
Remove all CTS records from the specified player
:param crypto_idfp:
:return:
"""
regex = re.compile('(.+)/cts100record/crypto_idfp(\d+)')
to_remove = []
for k, v in self.filter(regex, is_regex=True):
... | python | def remove_all_cts_records_by(self, crypto_idfp):
"""
Remove all CTS records from the specified player
:param crypto_idfp:
:return:
"""
regex = re.compile('(.+)/cts100record/crypto_idfp(\d+)')
to_remove = []
for k, v in self.filter(regex, is_regex=True):
... | [
"def",
"remove_all_cts_records_by",
"(",
"self",
",",
"crypto_idfp",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"'(.+)/cts100record/crypto_idfp(\\d+)'",
")",
"to_remove",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"filter",
"(",
"regex",... | Remove all CTS records from the specified player
:param crypto_idfp:
:return: | [
"Remove",
"all",
"CTS",
"records",
"from",
"the",
"specified",
"player",
":",
"param",
"crypto_idfp",
":",
":",
"return",
":"
] | train | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/__init__.py#L138-L151 |
nsavch/python-xonotic-db | xon_db/__init__.py | XonoticDB.merge_cts_records | def merge_cts_records(self, crypto_idfp, crypto_idfp_list):
"""
Merge all CTS records (including speed) of each player in crypto_idfp_list with records of crypto_idfp
:param crypto_idfp: Target player, who will now own all records of players in crypto_idfp_list
:param crypto_idfp_list: L... | python | def merge_cts_records(self, crypto_idfp, crypto_idfp_list):
"""
Merge all CTS records (including speed) of each player in crypto_idfp_list with records of crypto_idfp
:param crypto_idfp: Target player, who will now own all records of players in crypto_idfp_list
:param crypto_idfp_list: L... | [
"def",
"merge_cts_records",
"(",
"self",
",",
"crypto_idfp",
",",
"crypto_idfp_list",
")",
":",
"self",
".",
"__merge_cts_times",
"(",
"crypto_idfp",
",",
"crypto_idfp_list",
")",
"self",
".",
"__merge_cts_speeds",
"(",
"crypto_idfp",
",",
"crypto_idfp_list",
")",
... | Merge all CTS records (including speed) of each player in crypto_idfp_list with records of crypto_idfp
:param crypto_idfp: Target player, who will now own all records of players in crypto_idfp_list
:param crypto_idfp_list: List of crypto_idfp
:return: | [
"Merge",
"all",
"CTS",
"records",
"(",
"including",
"speed",
")",
"of",
"each",
"player",
"in",
"crypto_idfp_list",
"with",
"records",
"of",
"crypto_idfp",
":",
"param",
"crypto_idfp",
":",
"Target",
"player",
"who",
"will",
"now",
"own",
"all",
"records",
"... | train | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/__init__.py#L189-L201 |
jalanb/pysyte | pysyte/scripts.py | parse_args | def parse_args(add_args, docstring):
"""Parse out command line arguments"""
def run_args():
"""Run any global methods eponymous with args"""
valuable_args = {k for k, v in args.__dict__.items() if v}
arg_methods = {globals()[a] for a in valuable_args if a in globals()}
if not ar... | python | def parse_args(add_args, docstring):
"""Parse out command line arguments"""
def run_args():
"""Run any global methods eponymous with args"""
valuable_args = {k for k, v in args.__dict__.items() if v}
arg_methods = {globals()[a] for a in valuable_args if a in globals()}
if not ar... | [
"def",
"parse_args",
"(",
"add_args",
",",
"docstring",
")",
":",
"def",
"run_args",
"(",
")",
":",
"\"\"\"Run any global methods eponymous with args\"\"\"",
"valuable_args",
"=",
"{",
"k",
"for",
"k",
",",
"v",
"in",
"args",
".",
"__dict__",
".",
"items",
"("... | Parse out command line arguments | [
"Parse",
"out",
"command",
"line",
"arguments"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/scripts.py#L28-L54 |
jalanb/pysyte | pysyte/scripts.py | main | def main(method, add_args, version=None,
docstring=None, error_stream=sys.stderr):
"""Run the method as a script
Add a '--version' argument
Call add_args(parser) to add any more
Parse sys.argv
call method(args)
Catch any exceptions
exit on SystemExit or KeyboardError
O... | python | def main(method, add_args, version=None,
docstring=None, error_stream=sys.stderr):
"""Run the method as a script
Add a '--version' argument
Call add_args(parser) to add any more
Parse sys.argv
call method(args)
Catch any exceptions
exit on SystemExit or KeyboardError
O... | [
"def",
"main",
"(",
"method",
",",
"add_args",
",",
"version",
"=",
"None",
",",
"docstring",
"=",
"None",
",",
"error_stream",
"=",
"sys",
".",
"stderr",
")",
":",
"if",
"version",
":",
"_versions",
".",
"append",
"(",
"version",
")",
"try",
":",
"a... | Run the method as a script
Add a '--version' argument
Call add_args(parser) to add any more
Parse sys.argv
call method(args)
Catch any exceptions
exit on SystemExit or KeyboardError
Others:
If version is less then 1, reraise them
Else print them to the error... | [
"Run",
"the",
"method",
"as",
"a",
"script"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/scripts.py#L58-L93 |
mouse-reeve/word-builder | wordbuilder/WordBuilder.py | WordBuilder.ingest | def ingest(self, corpus_file):
''' load and parse a pre-formatted and cleaned text file. Garbage in, garbage out '''
corpus = open(corpus_file)
total_letters = 0
total_words = 0
shortest_word = 100
for word in corpus.readlines():
# clean word
word ... | python | def ingest(self, corpus_file):
''' load and parse a pre-formatted and cleaned text file. Garbage in, garbage out '''
corpus = open(corpus_file)
total_letters = 0
total_words = 0
shortest_word = 100
for word in corpus.readlines():
# clean word
word ... | [
"def",
"ingest",
"(",
"self",
",",
"corpus_file",
")",
":",
"corpus",
"=",
"open",
"(",
"corpus_file",
")",
"total_letters",
"=",
"0",
"total_words",
"=",
"0",
"shortest_word",
"=",
"100",
"for",
"word",
"in",
"corpus",
".",
"readlines",
"(",
")",
":",
... | load and parse a pre-formatted and cleaned text file. Garbage in, garbage out | [
"load",
"and",
"parse",
"a",
"pre",
"-",
"formatted",
"and",
"cleaned",
"text",
"file",
".",
"Garbage",
"in",
"garbage",
"out"
] | train | https://github.com/mouse-reeve/word-builder/blob/5b73f847faeaa06851cfe63438f549706aee3d15/wordbuilder/WordBuilder.py#L23-L54 |
mouse-reeve/word-builder | wordbuilder/WordBuilder.py | WordBuilder.get_word | def get_word(self, word=None):
''' creates a new word '''
word = word if not word == None else self.initial
if not self.terminal in word:
if len(word) > self.average_word_length and \
self.terminal in self.links[word[-self.chunk_size:]] \
and r... | python | def get_word(self, word=None):
''' creates a new word '''
word = word if not word == None else self.initial
if not self.terminal in word:
if len(word) > self.average_word_length and \
self.terminal in self.links[word[-self.chunk_size:]] \
and r... | [
"def",
"get_word",
"(",
"self",
",",
"word",
"=",
"None",
")",
":",
"word",
"=",
"word",
"if",
"not",
"word",
"==",
"None",
"else",
"self",
".",
"initial",
"if",
"not",
"self",
".",
"terminal",
"in",
"word",
":",
"if",
"len",
"(",
"word",
")",
">... | creates a new word | [
"creates",
"a",
"new",
"word"
] | train | https://github.com/mouse-reeve/word-builder/blob/5b73f847faeaa06851cfe63438f549706aee3d15/wordbuilder/WordBuilder.py#L57-L71 |
diffeo/rejester | rejester/run.py | existing_path | def existing_path(string):
'''"Convert" a string to a string that is a path to an existing file.'''
if not os.path.exists(string):
msg = 'path {0!r} does not exist'.format(string)
raise argparse.ArgumentTypeError(msg)
return string | python | def existing_path(string):
'''"Convert" a string to a string that is a path to an existing file.'''
if not os.path.exists(string):
msg = 'path {0!r} does not exist'.format(string)
raise argparse.ArgumentTypeError(msg)
return string | [
"def",
"existing_path",
"(",
"string",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"string",
")",
":",
"msg",
"=",
"'path {0!r} does not exist'",
".",
"format",
"(",
"string",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg"... | "Convert" a string to a string that is a path to an existing file. | [
"Convert",
"a",
"string",
"to",
"a",
"string",
"that",
"is",
"a",
"path",
"to",
"an",
"existing",
"file",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L198-L203 |
diffeo/rejester | rejester/run.py | absolute_path | def absolute_path(string):
'''"Convert" a string to a string that is an absolute existing path.'''
if not os.path.isabs(string):
msg = '{0!r} is not an absolute path'.format(string)
raise argparse.ArgumentTypeError(msg)
if not os.path.exists(os.path.dirname(string)):
msg = 'path {0!r... | python | def absolute_path(string):
'''"Convert" a string to a string that is an absolute existing path.'''
if not os.path.isabs(string):
msg = '{0!r} is not an absolute path'.format(string)
raise argparse.ArgumentTypeError(msg)
if not os.path.exists(os.path.dirname(string)):
msg = 'path {0!r... | [
"def",
"absolute_path",
"(",
"string",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"string",
")",
":",
"msg",
"=",
"'{0!r} is not an absolute path'",
".",
"format",
"(",
"string",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"m... | "Convert" a string to a string that is an absolute existing path. | [
"Convert",
"a",
"string",
"to",
"a",
"string",
"that",
"is",
"an",
"absolute",
"existing",
"path",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L210-L218 |
diffeo/rejester | rejester/run.py | Manager.task_master | def task_master(self):
"""A `TaskMaster` object for manipulating work"""
if self._task_master is None:
self._task_master = build_task_master(self.config)
return self._task_master | python | def task_master(self):
"""A `TaskMaster` object for manipulating work"""
if self._task_master is None:
self._task_master = build_task_master(self.config)
return self._task_master | [
"def",
"task_master",
"(",
"self",
")",
":",
"if",
"self",
".",
"_task_master",
"is",
"None",
":",
"self",
".",
"_task_master",
"=",
"build_task_master",
"(",
"self",
".",
"config",
")",
"return",
"self",
".",
"_task_master"
] | A `TaskMaster` object for manipulating work | [
"A",
"TaskMaster",
"object",
"for",
"manipulating",
"work"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L240-L244 |
diffeo/rejester | rejester/run.py | Manager._add_work_spec_args | def _add_work_spec_args(self, parser):
'''Add ``--work-spec`` to an :mod:`argparse` `parser`.'''
parser.add_argument('-w', '--work-spec', dest='work_spec_path',
metavar='FILE', type=existing_path,
required=True,
help='pa... | python | def _add_work_spec_args(self, parser):
'''Add ``--work-spec`` to an :mod:`argparse` `parser`.'''
parser.add_argument('-w', '--work-spec', dest='work_spec_path',
metavar='FILE', type=existing_path,
required=True,
help='pa... | [
"def",
"_add_work_spec_args",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-w'",
",",
"'--work-spec'",
",",
"dest",
"=",
"'work_spec_path'",
",",
"metavar",
"=",
"'FILE'",
",",
"type",
"=",
"existing_path",
",",
"required",
"="... | Add ``--work-spec`` to an :mod:`argparse` `parser`. | [
"Add",
"--",
"work",
"-",
"spec",
"to",
"an",
":",
"mod",
":",
"argparse",
"parser",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L246-L251 |
diffeo/rejester | rejester/run.py | Manager._get_work_spec | def _get_work_spec(self, args):
'''Get the contents of the work spec from the arguments.'''
with open(args.work_spec_path) as f:
return yaml.load(f) | python | def _get_work_spec(self, args):
'''Get the contents of the work spec from the arguments.'''
with open(args.work_spec_path) as f:
return yaml.load(f) | [
"def",
"_get_work_spec",
"(",
"self",
",",
"args",
")",
":",
"with",
"open",
"(",
"args",
".",
"work_spec_path",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"load",
"(",
"f",
")"
] | Get the contents of the work spec from the arguments. | [
"Get",
"the",
"contents",
"of",
"the",
"work",
"spec",
"from",
"the",
"arguments",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L252-L255 |
diffeo/rejester | rejester/run.py | Manager._add_work_spec_name_args | def _add_work_spec_name_args(self, parser):
'''Add either ``--work-spec`` or ``--work-spec-name`` to an
:mod:`argparse` `parser`.'''
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-w', '--work-spec', dest='work_spec_path',
metava... | python | def _add_work_spec_name_args(self, parser):
'''Add either ``--work-spec`` or ``--work-spec-name`` to an
:mod:`argparse` `parser`.'''
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-w', '--work-spec', dest='work_spec_path',
metava... | [
"def",
"_add_work_spec_name_args",
"(",
"self",
",",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"'-w'",
",",
"'--work-spec'",
",",
"dest",
"=",
"'work_s... | Add either ``--work-spec`` or ``--work-spec-name`` to an
:mod:`argparse` `parser`. | [
"Add",
"either",
"--",
"work",
"-",
"spec",
"or",
"--",
"work",
"-",
"spec",
"-",
"name",
"to",
"an",
":",
"mod",
":",
"argparse",
"parser",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L257-L265 |
diffeo/rejester | rejester/run.py | Manager._get_work_spec_name | def _get_work_spec_name(self, args):
'''Get the name of the work spec from the arguments.
This assumes :meth:`_add_work_spec_name_args` has been called,
but will also work if just :meth:`_add_work_spec_args` was
called instead.
'''
if getattr(args, 'work_spec_name', Non... | python | def _get_work_spec_name(self, args):
'''Get the name of the work spec from the arguments.
This assumes :meth:`_add_work_spec_name_args` has been called,
but will also work if just :meth:`_add_work_spec_args` was
called instead.
'''
if getattr(args, 'work_spec_name', Non... | [
"def",
"_get_work_spec_name",
"(",
"self",
",",
"args",
")",
":",
"if",
"getattr",
"(",
"args",
",",
"'work_spec_name'",
",",
"None",
")",
":",
"return",
"args",
".",
"work_spec_name",
"return",
"self",
".",
"_get_work_spec",
"(",
"args",
")",
"[",
"'name'... | Get the name of the work spec from the arguments.
This assumes :meth:`_add_work_spec_name_args` has been called,
but will also work if just :meth:`_add_work_spec_args` was
called instead. | [
"Get",
"the",
"name",
"of",
"the",
"work",
"spec",
"from",
"the",
"arguments",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L267-L277 |
diffeo/rejester | rejester/run.py | Manager._read_work_units_file | def _read_work_units_file(self, work_units_fh):
'''work_units_fh is iterable on lines (could actually be ['{}',...])
'''
count = 0
for line in work_units_fh:
if not line:
continue
line = line.strip()
if not line:
continu... | python | def _read_work_units_file(self, work_units_fh):
'''work_units_fh is iterable on lines (could actually be ['{}',...])
'''
count = 0
for line in work_units_fh:
if not line:
continue
line = line.strip()
if not line:
continu... | [
"def",
"_read_work_units_file",
"(",
"self",
",",
"work_units_fh",
")",
":",
"count",
"=",
"0",
"for",
"line",
"in",
"work_units_fh",
":",
"if",
"not",
"line",
":",
"continue",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
":",
"con... | work_units_fh is iterable on lines (could actually be ['{}',...]) | [
"work_units_fh",
"is",
"iterable",
"on",
"lines",
"(",
"could",
"actually",
"be",
"[",
"{}",
"...",
"]",
")"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L279-L299 |
diffeo/rejester | rejester/run.py | Manager.do_load | def do_load(self, args):
'''loads work_units into a namespace for a given work_spec
--work-units file is JSON, one work unit per line, each line a
JSON dict with the one key being the work unit key and the
value being a data dict for the work unit.
'''
work_spec = self.... | python | def do_load(self, args):
'''loads work_units into a namespace for a given work_spec
--work-units file is JSON, one work unit per line, each line a
JSON dict with the one key being the work unit key and the
value being a data dict for the work unit.
'''
work_spec = self.... | [
"def",
"do_load",
"(",
"self",
",",
"args",
")",
":",
"work_spec",
"=",
"self",
".",
"_get_work_spec",
"(",
"args",
")",
"work_spec",
"[",
"'nice'",
"]",
"=",
"args",
".",
"nice",
"self",
".",
"task_master",
".",
"set_work_spec",
"(",
"work_spec",
")",
... | loads work_units into a namespace for a given work_spec
--work-units file is JSON, one work unit per line, each line a
JSON dict with the one key being the work unit key and the
value being a data dict for the work unit. | [
"loads",
"work_units",
"into",
"a",
"namespace",
"for",
"a",
"given",
"work_spec"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L324-L352 |
diffeo/rejester | rejester/run.py | Manager.do_delete | def do_delete(self, args):
'''delete the entire contents of the current namespace'''
namespace = self.config['namespace']
if not args.assume_yes:
response = raw_input('Delete everything in {0!r}? Enter namespace: '
.format(namespace))
if ... | python | def do_delete(self, args):
'''delete the entire contents of the current namespace'''
namespace = self.config['namespace']
if not args.assume_yes:
response = raw_input('Delete everything in {0!r}? Enter namespace: '
.format(namespace))
if ... | [
"def",
"do_delete",
"(",
"self",
",",
"args",
")",
":",
"namespace",
"=",
"self",
".",
"config",
"[",
"'namespace'",
"]",
"if",
"not",
"args",
".",
"assume_yes",
":",
"response",
"=",
"raw_input",
"(",
"'Delete everything in {0!r}? Enter namespace: '",
".",
"... | delete the entire contents of the current namespace | [
"delete",
"the",
"entire",
"contents",
"of",
"the",
"current",
"namespace"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L375-L385 |
diffeo/rejester | rejester/run.py | Manager.do_work_specs | def do_work_specs(self, args):
'''print the names of all of the work specs'''
work_spec_names = [x['name'] for x in self.task_master.iter_work_specs()]
work_spec_names.sort()
for name in work_spec_names:
self.stdout.write('{0}\n'.format(name)) | python | def do_work_specs(self, args):
'''print the names of all of the work specs'''
work_spec_names = [x['name'] for x in self.task_master.iter_work_specs()]
work_spec_names.sort()
for name in work_spec_names:
self.stdout.write('{0}\n'.format(name)) | [
"def",
"do_work_specs",
"(",
"self",
",",
"args",
")",
":",
"work_spec_names",
"=",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"self",
".",
"task_master",
".",
"iter_work_specs",
"(",
")",
"]",
"work_spec_names",
".",
"sort",
"(",
")",
"for",
"nam... | print the names of all of the work specs | [
"print",
"the",
"names",
"of",
"all",
"of",
"the",
"work",
"specs"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L389-L394 |
diffeo/rejester | rejester/run.py | Manager.do_work_spec | def do_work_spec(self, args):
'''dump the contents of an existing work spec'''
work_spec_name = self._get_work_spec_name(args)
spec = self.task_master.get_work_spec(work_spec_name)
if args.json:
self.stdout.write(json.dumps(spec, indent=4, sort_keys=True) +
... | python | def do_work_spec(self, args):
'''dump the contents of an existing work spec'''
work_spec_name = self._get_work_spec_name(args)
spec = self.task_master.get_work_spec(work_spec_name)
if args.json:
self.stdout.write(json.dumps(spec, indent=4, sort_keys=True) +
... | [
"def",
"do_work_spec",
"(",
"self",
",",
"args",
")",
":",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"spec",
"=",
"self",
".",
"task_master",
".",
"get_work_spec",
"(",
"work_spec_name",
")",
"if",
"args",
".",
"json",
":... | dump the contents of an existing work spec | [
"dump",
"the",
"contents",
"of",
"an",
"existing",
"work",
"spec"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L402-L410 |
diffeo/rejester | rejester/run.py | Manager.do_status | def do_status(self, args):
'''print the number of work units in an existing work spec'''
work_spec_name = self._get_work_spec_name(args)
status = self.task_master.status(work_spec_name)
self.stdout.write(json.dumps(status, indent=4, sort_keys=True) +
'\n') | python | def do_status(self, args):
'''print the number of work units in an existing work spec'''
work_spec_name = self._get_work_spec_name(args)
status = self.task_master.status(work_spec_name)
self.stdout.write(json.dumps(status, indent=4, sort_keys=True) +
'\n') | [
"def",
"do_status",
"(",
"self",
",",
"args",
")",
":",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"status",
"=",
"self",
".",
"task_master",
".",
"status",
"(",
"work_spec_name",
")",
"self",
".",
"stdout",
".",
"write",
... | print the number of work units in an existing work spec | [
"print",
"the",
"number",
"of",
"work",
"units",
"in",
"an",
"existing",
"work",
"spec"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L415-L420 |
diffeo/rejester | rejester/run.py | Manager.do_summary | def do_summary(self, args):
'''print a summary of running rejester work'''
assert args.json or args.text or (args.text is None)
do_text = args.text
xd = {}
for ws in self.task_master.iter_work_specs():
name = ws['name']
status = self.task_master.status(na... | python | def do_summary(self, args):
'''print a summary of running rejester work'''
assert args.json or args.text or (args.text is None)
do_text = args.text
xd = {}
for ws in self.task_master.iter_work_specs():
name = ws['name']
status = self.task_master.status(na... | [
"def",
"do_summary",
"(",
"self",
",",
"args",
")",
":",
"assert",
"args",
".",
"json",
"or",
"args",
".",
"text",
"or",
"(",
"args",
".",
"text",
"is",
"None",
")",
"do_text",
"=",
"args",
".",
"text",
"xd",
"=",
"{",
"}",
"for",
"ws",
"in",
"... | print a summary of running rejester work | [
"print",
"a",
"summary",
"of",
"running",
"rejester",
"work"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L427-L457 |
diffeo/rejester | rejester/run.py | Manager.do_work_units | def do_work_units(self, args):
'''list work units that have not yet completed'''
work_spec_name = self._get_work_spec_name(args)
if args.status:
status = args.status.upper()
statusi = getattr(self.task_master, status, None)
if statusi is None:
... | python | def do_work_units(self, args):
'''list work units that have not yet completed'''
work_spec_name = self._get_work_spec_name(args)
if args.status:
status = args.status.upper()
statusi = getattr(self.task_master, status, None)
if statusi is None:
... | [
"def",
"do_work_units",
"(",
"self",
",",
"args",
")",
":",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"if",
"args",
".",
"status",
":",
"status",
"=",
"args",
".",
"status",
".",
"upper",
"(",
")",
"statusi",
"=",
"ge... | list work units that have not yet completed | [
"list",
"work",
"units",
"that",
"have",
"not",
"yet",
"completed"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L470-L497 |
diffeo/rejester | rejester/run.py | Manager.do_work_unit | def do_work_unit(self, args):
'''print basic details about work units'''
work_spec_name = self._get_work_spec_name(args)
for work_unit_name in args.unit:
status = self.task_master.get_work_unit_status(work_spec_name,
work_uni... | python | def do_work_unit(self, args):
'''print basic details about work units'''
work_spec_name = self._get_work_spec_name(args)
for work_unit_name in args.unit:
status = self.task_master.get_work_unit_status(work_spec_name,
work_uni... | [
"def",
"do_work_unit",
"(",
"self",
",",
"args",
")",
":",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"for",
"work_unit_name",
"in",
"args",
".",
"unit",
":",
"status",
"=",
"self",
".",
"task_master",
".",
"get_work_unit_st... | print basic details about work units | [
"print",
"basic",
"details",
"about",
"work",
"units"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L516-L558 |
diffeo/rejester | rejester/run.py | Manager.do_retry | def do_retry(self, args):
'''retry a specific failed job'''
work_spec_name = self._get_work_spec_name(args)
retried = 0
complained = False
try:
if args.all:
while True:
units = self.task_master.get_work_units(
... | python | def do_retry(self, args):
'''retry a specific failed job'''
work_spec_name = self._get_work_spec_name(args)
retried = 0
complained = False
try:
if args.all:
while True:
units = self.task_master.get_work_units(
... | [
"def",
"do_retry",
"(",
"self",
",",
"args",
")",
":",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"retried",
"=",
"0",
"complained",
"=",
"False",
"try",
":",
"if",
"args",
".",
"all",
":",
"while",
"True",
":",
"units... | retry a specific failed job | [
"retry",
"a",
"specific",
"failed",
"job"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L566-L610 |
diffeo/rejester | rejester/run.py | Manager.do_clear | def do_clear(self, args):
'''remove work units from a work spec'''
# Which units?
work_spec_name = self._get_work_spec_name(args)
units = args.unit or None
# What to do?
count = 0
if args.status is None:
all = units is None
count += self.ta... | python | def do_clear(self, args):
'''remove work units from a work spec'''
# Which units?
work_spec_name = self._get_work_spec_name(args)
units = args.unit or None
# What to do?
count = 0
if args.status is None:
all = units is None
count += self.ta... | [
"def",
"do_clear",
"(",
"self",
",",
"args",
")",
":",
"# Which units?",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"units",
"=",
"args",
".",
"unit",
"or",
"None",
"# What to do?",
"count",
"=",
"0",
"if",
"args",
".",
... | remove work units from a work spec | [
"remove",
"work",
"units",
"from",
"a",
"work",
"spec"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L620-L645 |
diffeo/rejester | rejester/run.py | Manager.do_mode | def do_mode(self, args):
'''get or set the global rejester worker mode'''
if args.mode:
mode = { 'idle': self.task_master.IDLE,
'run': self.task_master.RUN,
'terminate': self.task_master.TERMINATE }[args.mode]
self.task_master.set_mode(mo... | python | def do_mode(self, args):
'''get or set the global rejester worker mode'''
if args.mode:
mode = { 'idle': self.task_master.IDLE,
'run': self.task_master.RUN,
'terminate': self.task_master.TERMINATE }[args.mode]
self.task_master.set_mode(mo... | [
"def",
"do_mode",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"mode",
":",
"mode",
"=",
"{",
"'idle'",
":",
"self",
".",
"task_master",
".",
"IDLE",
",",
"'run'",
":",
"self",
".",
"task_master",
".",
"RUN",
",",
"'terminate'",
":",
"sel... | get or set the global rejester worker mode | [
"get",
"or",
"set",
"the",
"global",
"rejester",
"worker",
"mode"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L651-L661 |
diffeo/rejester | rejester/run.py | Manager.do_global_lock | def do_global_lock(self, args):
'''read (or clear) the global lock'''
if args.purge:
self.task_master.registry.force_clear_lock()
else:
owner = self.task_master.registry.read_lock()
if owner:
heartbeat = self.task_master.get_heartbeat(owner)
... | python | def do_global_lock(self, args):
'''read (or clear) the global lock'''
if args.purge:
self.task_master.registry.force_clear_lock()
else:
owner = self.task_master.registry.read_lock()
if owner:
heartbeat = self.task_master.get_heartbeat(owner)
... | [
"def",
"do_global_lock",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"purge",
":",
"self",
".",
"task_master",
".",
"registry",
".",
"force_clear_lock",
"(",
")",
"else",
":",
"owner",
"=",
"self",
".",
"task_master",
".",
"registry",
".",
"... | read (or clear) the global lock | [
"read",
"(",
"or",
"clear",
")",
"the",
"global",
"lock"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L666-L680 |
diffeo/rejester | rejester/run.py | Manager.do_workers | def do_workers(self, args):
'''list all known workers'''
workers = self.task_master.workers(alive=not args.all)
for k in sorted(workers.iterkeys()):
self.stdout.write('{0} ({1})\n'.format(k, workers[k]))
if args.details:
heartbeat = self.task_master.get_he... | python | def do_workers(self, args):
'''list all known workers'''
workers = self.task_master.workers(alive=not args.all)
for k in sorted(workers.iterkeys()):
self.stdout.write('{0} ({1})\n'.format(k, workers[k]))
if args.details:
heartbeat = self.task_master.get_he... | [
"def",
"do_workers",
"(",
"self",
",",
"args",
")",
":",
"workers",
"=",
"self",
".",
"task_master",
".",
"workers",
"(",
"alive",
"=",
"not",
"args",
".",
"all",
")",
"for",
"k",
"in",
"sorted",
"(",
"workers",
".",
"iterkeys",
"(",
")",
")",
":",... | list all known workers | [
"list",
"all",
"known",
"workers"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L687-L695 |
diffeo/rejester | rejester/run.py | Manager.do_run_one | def do_run_one(self, args):
'''run a single job'''
work_spec_names = args.from_work_spec or None
worker = SingleWorker(self.config, task_master=self.task_master, work_spec_names=work_spec_names, max_jobs=args.max_jobs)
worker.register()
rc = False
starttime = time.time()
... | python | def do_run_one(self, args):
'''run a single job'''
work_spec_names = args.from_work_spec or None
worker = SingleWorker(self.config, task_master=self.task_master, work_spec_names=work_spec_names, max_jobs=args.max_jobs)
worker.register()
rc = False
starttime = time.time()
... | [
"def",
"do_run_one",
"(",
"self",
",",
"args",
")",
":",
"work_spec_names",
"=",
"args",
".",
"from_work_spec",
"or",
"None",
"worker",
"=",
"SingleWorker",
"(",
"self",
".",
"config",
",",
"task_master",
"=",
"self",
".",
"task_master",
",",
"work_spec_name... | run a single job | [
"run",
"a",
"single",
"job"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run.py#L702-L726 |
se-esss-litterbox/Pynac | Pynac/Core.py | make_phase_space_list | def make_phase_space_list():
"""
Extract all the phase space information (due to ``EMIT`` commands in the input
file), and create a list of PhaseSpace objects. The primary purpose of this
is for interactive explorations of the data produced during Pynac simulations.
"""
with open('dynac.short')... | python | def make_phase_space_list():
"""
Extract all the phase space information (due to ``EMIT`` commands in the input
file), and create a list of PhaseSpace objects. The primary purpose of this
is for interactive explorations of the data produced during Pynac simulations.
"""
with open('dynac.short')... | [
"def",
"make_phase_space_list",
"(",
")",
":",
"with",
"open",
"(",
"'dynac.short'",
")",
"as",
"f",
":",
"data_str",
"=",
"''",
".",
"join",
"(",
"line",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
")",
"data_str_array",
"=",
"data_str",
"."... | Extract all the phase space information (due to ``EMIT`` commands in the input
file), and create a list of PhaseSpace objects. The primary purpose of this
is for interactive explorations of the data produced during Pynac simulations. | [
"Extract",
"all",
"the",
"phase",
"space",
"information",
"(",
"due",
"to",
"EMIT",
"commands",
"in",
"the",
"input",
"file",
")",
"and",
"create",
"a",
"list",
"of",
"PhaseSpace",
"objects",
".",
"The",
"primary",
"purpose",
"of",
"this",
"is",
"for",
"... | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L652-L663 |
se-esss-litterbox/Pynac | Pynac/Core.py | get_number_of_particles | def get_number_of_particles():
"""
Queries the ``dynac.short`` file for the number of particles used in the
simulation.
"""
with open('dynac.short') as f:
data_str = ''.join(line for line in f.readlines())
num_of_parts = int(data_str.split('Simulation with')[1].strip().split()[0])
... | python | def get_number_of_particles():
"""
Queries the ``dynac.short`` file for the number of particles used in the
simulation.
"""
with open('dynac.short') as f:
data_str = ''.join(line for line in f.readlines())
num_of_parts = int(data_str.split('Simulation with')[1].strip().split()[0])
... | [
"def",
"get_number_of_particles",
"(",
")",
":",
"with",
"open",
"(",
"'dynac.short'",
")",
"as",
"f",
":",
"data_str",
"=",
"''",
".",
"join",
"(",
"line",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
")",
"num_of_parts",
"=",
"int",
"(",
"... | Queries the ``dynac.short`` file for the number of particles used in the
simulation. | [
"Queries",
"the",
"dynac",
".",
"short",
"file",
"for",
"the",
"number",
"of",
"particles",
"used",
"in",
"the",
"simulation",
"."
] | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L666-L674 |
se-esss-litterbox/Pynac | Pynac/Core.py | multi_process_pynac | def multi_process_pynac(file_list, pynac_func, num_iters=100, max_workers=8):
"""
Use a ProcessPool from the ``concurrent.futures`` module to execute ``num_iters``
number of instances of ``pynac_func``. This function takes advantage of ``do_single_dynac_process``
and ``pynac_in_sub_directory``.
"""... | python | def multi_process_pynac(file_list, pynac_func, num_iters=100, max_workers=8):
"""
Use a ProcessPool from the ``concurrent.futures`` module to execute ``num_iters``
number of instances of ``pynac_func``. This function takes advantage of ``do_single_dynac_process``
and ``pynac_in_sub_directory``.
"""... | [
"def",
"multi_process_pynac",
"(",
"file_list",
",",
"pynac_func",
",",
"num_iters",
"=",
"100",
",",
"max_workers",
"=",
"8",
")",
":",
"with",
"ProcessPoolExecutor",
"(",
"max_workers",
"=",
"max_workers",
")",
"as",
"executor",
":",
"tasks",
"=",
"[",
"ex... | Use a ProcessPool from the ``concurrent.futures`` module to execute ``num_iters``
number of instances of ``pynac_func``. This function takes advantage of ``do_single_dynac_process``
and ``pynac_in_sub_directory``. | [
"Use",
"a",
"ProcessPool",
"from",
"the",
"concurrent",
".",
"futures",
"module",
"to",
"execute",
"num_iters",
"number",
"of",
"instances",
"of",
"pynac_func",
".",
"This",
"function",
"takes",
"advantage",
"of",
"do_single_dynac_process",
"and",
"pynac_in_sub_dire... | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L694-L706 |
se-esss-litterbox/Pynac | Pynac/Core.py | pynac_in_sub_directory | def pynac_in_sub_directory(num, file_list):
"""
A context manager to create a new directory, move the files listed in ``file_list``
to that directory, and change to that directory before handing control back to
context. The closing action is to change back to the original directory.
... | python | def pynac_in_sub_directory(num, file_list):
"""
A context manager to create a new directory, move the files listed in ``file_list``
to that directory, and change to that directory before handing control back to
context. The closing action is to change back to the original directory.
... | [
"def",
"pynac_in_sub_directory",
"(",
"num",
",",
"file_list",
")",
":",
"print",
"(",
"'Running %d'",
"%",
"num",
")",
"new_dir",
"=",
"'dynacProc_%04d'",
"%",
"num",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"new_dir",
")",
":",
"shutil",
".",
"rmtre... | A context manager to create a new directory, move the files listed in ``file_list``
to that directory, and change to that directory before handing control back to
context. The closing action is to change back to the original directory.
The directory name is based on the ``num`` input, and if i... | [
"A",
"context",
"manager",
"to",
"create",
"a",
"new",
"directory",
"move",
"the",
"files",
"listed",
"in",
"file_list",
"to",
"that",
"directory",
"and",
"change",
"to",
"that",
"directory",
"before",
"handing",
"control",
"back",
"to",
"context",
".",
"The... | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L723-L746 |
se-esss-litterbox/Pynac | Pynac/Core.py | Pynac.run | def run(self):
"""
Run the simulation in the current directory.
"""
self._start_dynac_proc(stdin=subp.PIPE, stdout=subp.PIPE)
str2write = self.name + '\r\n'
if self._DEBUG:
with open('pynacrun.log', 'a') as f:
f.write(str2write)
self.dy... | python | def run(self):
"""
Run the simulation in the current directory.
"""
self._start_dynac_proc(stdin=subp.PIPE, stdout=subp.PIPE)
str2write = self.name + '\r\n'
if self._DEBUG:
with open('pynacrun.log', 'a') as f:
f.write(str2write)
self.dy... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_start_dynac_proc",
"(",
"stdin",
"=",
"subp",
".",
"PIPE",
",",
"stdout",
"=",
"subp",
".",
"PIPE",
")",
"str2write",
"=",
"self",
".",
"name",
"+",
"'\\r\\n'",
"if",
"self",
".",
"_DEBUG",
":",
"... | Run the simulation in the current directory. | [
"Run",
"the",
"simulation",
"in",
"the",
"current",
"directory",
"."
] | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L73-L107 |
se-esss-litterbox/Pynac | Pynac/Core.py | Pynac.get_x_inds | def get_x_inds(self, *dynac_type):
"""
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
"""
return [i for i, x in e... | python | def get_x_inds(self, *dynac_type):
"""
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
"""
return [i for i, x in e... | [
"def",
"get_x_inds",
"(",
"self",
",",
"*",
"dynac_type",
")",
":",
"return",
"[",
"i",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"self",
".",
"lattice",
")",
"for",
"y",
"in",
"dynac_type",
"if",
"dynac_from_ele",
"(",
"x",
")",
"==",
"y",
"]"... | Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list. | [
"Return",
"the",
"indices",
"into",
"the",
"lattice",
"list",
"attribute",
"of",
"elements",
"whose",
"Dynac",
"type",
"matches",
"the",
"input",
"string",
".",
"Multiple",
"input",
"strings",
"can",
"be",
"given",
"either",
"as",
"a",
"comma",
"-",
"separat... | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L109-L115 |
se-esss-litterbox/Pynac | Pynac/Core.py | Pynac.get_x_objs | def get_x_objs(self, *dynac_type):
"""
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
"""
return [i for i in self... | python | def get_x_objs(self, *dynac_type):
"""
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
"""
return [i for i in self... | [
"def",
"get_x_objs",
"(",
"self",
",",
"*",
"dynac_type",
")",
":",
"return",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"lattice",
"for",
"y",
"in",
"dynac_type",
"if",
"dynac_from_ele",
"(",
"i",
")",
"==",
"y",
"]"
] | Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list. | [
"Return",
"the",
"indices",
"into",
"the",
"lattice",
"list",
"attribute",
"of",
"elements",
"whose",
"Dynac",
"type",
"matches",
"the",
"input",
"string",
".",
"Multiple",
"input",
"strings",
"can",
"be",
"given",
"either",
"as",
"a",
"comma",
"-",
"separat... | train | https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Core.py#L117-L123 |
edeposit/edeposit.amqp.ltp | src/edeposit/amqp/ltp/settings.py | _substitute_globals | def _substitute_globals(config_dict):
"""
Set global variables to values defined in `config_dict`.
Args:
config_dict (dict): dict with data, which are used to set `globals`.
Note:
`config_dict` have to be dictionary, or it is ignored. Also all
variables, that are not already in... | python | def _substitute_globals(config_dict):
"""
Set global variables to values defined in `config_dict`.
Args:
config_dict (dict): dict with data, which are used to set `globals`.
Note:
`config_dict` have to be dictionary, or it is ignored. Also all
variables, that are not already in... | [
"def",
"_substitute_globals",
"(",
"config_dict",
")",
":",
"constants",
"=",
"_get_all_constants",
"(",
")",
"if",
"type",
"(",
"config_dict",
")",
"!=",
"dict",
":",
"return",
"for",
"key",
",",
"val",
"in",
"config_dict",
".",
"iteritems",
"(",
")",
":"... | Set global variables to values defined in `config_dict`.
Args:
config_dict (dict): dict with data, which are used to set `globals`.
Note:
`config_dict` have to be dictionary, or it is ignored. Also all
variables, that are not already in globals, or are not types defined in
:att... | [
"Set",
"global",
"variables",
"to",
"values",
"defined",
"in",
"config_dict",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/settings.py#L69-L89 |
edeposit/edeposit.amqp.ltp | src/edeposit/amqp/ltp/settings.py | _read_from_paths | def _read_from_paths():
"""
Try to read data from configuration paths ($HOME/_SETTINGS_PATH,
/etc/_SETTINGS_PATH).
"""
home = os.environ.get("HOME", "/")
home_path = os.path.join(home, _SETTINGS_PATH)
etc_path = os.path.join("/etc", _SETTINGS_PATH)
read_path = None
if home and os.pa... | python | def _read_from_paths():
"""
Try to read data from configuration paths ($HOME/_SETTINGS_PATH,
/etc/_SETTINGS_PATH).
"""
home = os.environ.get("HOME", "/")
home_path = os.path.join(home, _SETTINGS_PATH)
etc_path = os.path.join("/etc", _SETTINGS_PATH)
read_path = None
if home and os.pa... | [
"def",
"_read_from_paths",
"(",
")",
":",
"home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"HOME\"",
",",
"\"/\"",
")",
"home_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"_SETTINGS_PATH",
")",
"etc_path",
"=",
"os",
".",
"path"... | Try to read data from configuration paths ($HOME/_SETTINGS_PATH,
/etc/_SETTINGS_PATH). | [
"Try",
"to",
"read",
"data",
"from",
"configuration",
"paths",
"(",
"$HOME",
"/",
"_SETTINGS_PATH",
"/",
"etc",
"/",
"_SETTINGS_PATH",
")",
"."
] | train | https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/settings.py#L92-L111 |
mariocesar/pengbot | src/pengbot/adapters/web/adapter.py | wsgi_handler | def wsgi_handler(func):
"""
Set a instance method to be call as a wsgi application, adding common
behavior and using webob.Request for practical use.
@wsgi_handler
def handle_verify_token(self, request):
pass
:param func:
:return:
"""
@wraps(func)
def inner(*args):
... | python | def wsgi_handler(func):
"""
Set a instance method to be call as a wsgi application, adding common
behavior and using webob.Request for practical use.
@wsgi_handler
def handle_verify_token(self, request):
pass
:param func:
:return:
"""
@wraps(func)
def inner(*args):
... | [
"def",
"wsgi_handler",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
")",
":",
"self",
",",
"environ",
",",
"start_response",
",",
"",
"*",
"args",
"=",
"args",
"request",
"=",
"Request",
"(",
"environ",
"... | Set a instance method to be call as a wsgi application, adding common
behavior and using webob.Request for practical use.
@wsgi_handler
def handle_verify_token(self, request):
pass
:param func:
:return: | [
"Set",
"a",
"instance",
"method",
"to",
"be",
"call",
"as",
"a",
"wsgi",
"application",
"adding",
"common",
"behavior",
"and",
"using",
"webob",
".",
"Request",
"for",
"practical",
"use",
"."
] | train | https://github.com/mariocesar/pengbot/blob/070854f92ac1314ee56f7f6cb9d27430b8f0fda8/src/pengbot/adapters/web/adapter.py#L13-L39 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate.format | def format(self, format_target, remove_obsolete=True):
""" Changes the internal self.format_string_object format target based on input. Also checks to see if input
is an entry in the config file in case we want to switch to a preexisting config format.
:param format_target: str, input for ... | python | def format(self, format_target, remove_obsolete=True):
""" Changes the internal self.format_string_object format target based on input. Also checks to see if input
is an entry in the config file in case we want to switch to a preexisting config format.
:param format_target: str, input for ... | [
"def",
"format",
"(",
"self",
",",
"format_target",
",",
"remove_obsolete",
"=",
"True",
")",
":",
"original_format",
",",
"original_format_order",
"=",
"(",
"self",
".",
"format",
",",
"self",
".",
"format_order",
")",
"try",
":",
"format_target",
"=",
"sel... | Changes the internal self.format_string_object format target based on input. Also checks to see if input
is an entry in the config file in case we want to switch to a preexisting config format.
:param format_target: str, input for the new format type. All strings will be the new tokens.
:... | [
"Changes",
"the",
"internal",
"self",
".",
"format_string_object",
"format",
"target",
"based",
"on",
"input",
".",
"Also",
"checks",
"to",
"see",
"if",
"input",
"is",
"an",
"entry",
"in",
"the",
"config",
"file",
"in",
"case",
"we",
"want",
"to",
"switch"... | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L77-L94 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate.initialize_format_options | def initialize_format_options(self, format_target=''):
""" First attempts to use format_target as a config path or gets the default format
if it's invalid or is empty.
:param format_target: (str, list(str)), can be either a query path to a format
... | python | def initialize_format_options(self, format_target=''):
""" First attempts to use format_target as a config path or gets the default format
if it's invalid or is empty.
:param format_target: (str, list(str)), can be either a query path to a format
... | [
"def",
"initialize_format_options",
"(",
"self",
",",
"format_target",
"=",
"''",
")",
":",
"try",
":",
"if",
"format_target",
":",
"self",
".",
"format",
"=",
"format_target",
"else",
":",
"raise",
"errors",
".",
"FormatError",
"except",
"errors",
".",
"For... | First attempts to use format_target as a config path or gets the default format
if it's invalid or is empty.
:param format_target: (str, list(str)), can be either a query path to a format
or in format of a naming string the sections should be spaced a... | [
"First",
"attempts",
"to",
"use",
"format_target",
"as",
"a",
"config",
"path",
"or",
"gets",
"the",
"default",
"format",
"if",
"it",
"s",
"invalid",
"or",
"is",
"empty",
"."
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L107-L122 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate.initialize_options | def initialize_options(cls):
""" Stores options from the config file
"""
cls.CONFIG_OPTIONS = cls.CFG.get(cls.CONFIG_PATH, return_type=dict) | python | def initialize_options(cls):
""" Stores options from the config file
"""
cls.CONFIG_OPTIONS = cls.CFG.get(cls.CONFIG_PATH, return_type=dict) | [
"def",
"initialize_options",
"(",
"cls",
")",
":",
"cls",
".",
"CONFIG_OPTIONS",
"=",
"cls",
".",
"CFG",
".",
"get",
"(",
"cls",
".",
"CONFIG_PATH",
",",
"return_type",
"=",
"dict",
")"
] | Stores options from the config file | [
"Stores",
"options",
"from",
"the",
"config",
"file"
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L125-L129 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate.get | def get(self, **kwargs):
"""Gets the string of the current name of the object
Returns (string): the name of the object
"""
old_state = self.state.copy()
self.merge_dict(kwargs)
result = rendering.InputRenderer.render_nomenclative(self)
self.merge_dict(old_state)
... | python | def get(self, **kwargs):
"""Gets the string of the current name of the object
Returns (string): the name of the object
"""
old_state = self.state.copy()
self.merge_dict(kwargs)
result = rendering.InputRenderer.render_nomenclative(self)
self.merge_dict(old_state)
... | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"old_state",
"=",
"self",
".",
"state",
".",
"copy",
"(",
")",
"self",
".",
"merge_dict",
"(",
"kwargs",
")",
"result",
"=",
"rendering",
".",
"InputRenderer",
".",
"render_nomenclative",
"(... | Gets the string of the current name of the object
Returns (string): the name of the object | [
"Gets",
"the",
"string",
"of",
"the",
"current",
"name",
"of",
"the",
"object",
"Returns",
"(",
"string",
")",
":",
"the",
"name",
"of",
"the",
"object"
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L131-L139 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate.merge_dict | def merge_dict(self, *args, **kwargs):
""" Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs th... | python | def merge_dict(self, *args, **kwargs):
""" Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs th... | [
"def",
"merge_dict",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"input_dict",
"=",
"self",
".",
"_convert_input",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"input_dict",
":",
"self",
".",
"_sift_and_init_configs",
"("... | Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs that represent token:value pairs | [
"Takes",
"variable",
"inputs",
"compiles",
"them",
"into",
"a",
"dictionary",
"then",
"merges",
"it",
"to",
"the",
"current",
"nomenclate",
"s",
"state"
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L141-L150 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate.get_token_settings | def get_token_settings(cls, token, default=None):
""" Get the value for a specific token as a dictionary or replace with default
:param token: str, token to query the nomenclate for
:param default: object, substitution if the token is not found
:return: (dict, object, None), token setti... | python | def get_token_settings(cls, token, default=None):
""" Get the value for a specific token as a dictionary or replace with default
:param token: str, token to query the nomenclate for
:param default: object, substitution if the token is not found
:return: (dict, object, None), token setti... | [
"def",
"get_token_settings",
"(",
"cls",
",",
"token",
",",
"default",
"=",
"None",
")",
":",
"setting_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"cls",
".",
"__dict__",
")",
":",
"if",
"'%s_'",
"%",
"token",
"in",
"key... | Get the value for a specific token as a dictionary or replace with default
:param token: str, token to query the nomenclate for
:param default: object, substitution if the token is not found
:return: (dict, object, None), token setting dictionary or default | [
"Get",
"the",
"value",
"for",
"a",
"specific",
"token",
"as",
"a",
"dictionary",
"or",
"replace",
"with",
"default"
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L153-L165 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate._update_tokens_from_swap_format | def _update_tokens_from_swap_format(self, original_format, original_format_order, remove_obsolete=True):
""" Updates tokens based on a swap format call that will maintain synchronicity between token_dict and attrs
If there was an accidental setting already set to one of the attrs that should now be ... | python | def _update_tokens_from_swap_format(self, original_format, original_format_order, remove_obsolete=True):
""" Updates tokens based on a swap format call that will maintain synchronicity between token_dict and attrs
If there was an accidental setting already set to one of the attrs that should now be ... | [
"def",
"_update_tokens_from_swap_format",
"(",
"self",
",",
"original_format",
",",
"original_format_order",
",",
"remove_obsolete",
"=",
"True",
")",
":",
"old_format_order",
"=",
"[",
"_",
".",
"lower",
"(",
")",
"for",
"_",
"in",
"original_format_order",
"]",
... | Updates tokens based on a swap format call that will maintain synchronicity between token_dict and attrs
If there was an accidental setting already set to one of the attrs that should now be a token attr due
to the format swap, we wipe it and add a new TokenAttr to the Nomenclate attribute.
... | [
"Updates",
"tokens",
"based",
"on",
"a",
"swap",
"format",
"call",
"that",
"will",
"maintain",
"synchronicity",
"between",
"token_dict",
"and",
"attrs",
"If",
"there",
"was",
"an",
"accidental",
"setting",
"already",
"set",
"to",
"one",
"of",
"the",
"attrs",
... | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L167-L195 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate._convert_input | def _convert_input(self, *args, **kwargs):
""" Takes variable inputs
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs that represent token:value pairs
:return: dict, combined dictionary of a... | python | def _convert_input(self, *args, **kwargs):
""" Takes variable inputs
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs that represent token:value pairs
:return: dict, combined dictionary of a... | [
"def",
"_convert_input",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"arg",
".",
"state",
"if",
"isinstance",
"(",
"arg",
",",
"Nomenclate",
")",
"else",
"arg",
"for",
"arg",
"in",
"args",
"]",
"input_dict",
... | Takes variable inputs
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs that represent token:value pairs
:return: dict, combined dictionary of all inputs | [
"Takes",
"variable",
"inputs"
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L197-L206 |
AndresMWeber/Nomenclate | nomenclate/core/nomenclature.py | Nomenclate._sift_and_init_configs | def _sift_and_init_configs(self, input_dict):
""" Removes all key/v for keys that exist in the overall config and activates them.
Used to weed out config keys from tokens in a given input.
"""
configs = {}
for k, v in iteritems(input_dict):
if (k not in map(str.lo... | python | def _sift_and_init_configs(self, input_dict):
""" Removes all key/v for keys that exist in the overall config and activates them.
Used to weed out config keys from tokens in a given input.
"""
configs = {}
for k, v in iteritems(input_dict):
if (k not in map(str.lo... | [
"def",
"_sift_and_init_configs",
"(",
"self",
",",
"input_dict",
")",
":",
"configs",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"input_dict",
")",
":",
"if",
"(",
"k",
"not",
"in",
"map",
"(",
"str",
".",
"lower",
",",
"self",
".... | Removes all key/v for keys that exist in the overall config and activates them.
Used to weed out config keys from tokens in a given input. | [
"Removes",
"all",
"key",
"/",
"v",
"for",
"keys",
"that",
"exist",
"in",
"the",
"overall",
"config",
"and",
"activates",
"them",
".",
"Used",
"to",
"weed",
"out",
"config",
"keys",
"from",
"tokens",
"in",
"a",
"given",
"input",
"."
] | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nomenclature.py#L208-L226 |
hiddes/custom | custom/CustomCarry/custom.py | change_custom_seed | def change_custom_seed(seed):
"""
change CustomCarry seed
example:
change_custom_seed([1,2,3]) # then CustomCarry.SEED_LIST == '123' is True
:param seed:
:return:
"""
if isinstance(seed, (basestring, list, tuple)):
seed = Seed(seed)
if isinstance(seed, Seed):
CustomC... | python | def change_custom_seed(seed):
"""
change CustomCarry seed
example:
change_custom_seed([1,2,3]) # then CustomCarry.SEED_LIST == '123' is True
:param seed:
:return:
"""
if isinstance(seed, (basestring, list, tuple)):
seed = Seed(seed)
if isinstance(seed, Seed):
CustomC... | [
"def",
"change_custom_seed",
"(",
"seed",
")",
":",
"if",
"isinstance",
"(",
"seed",
",",
"(",
"basestring",
",",
"list",
",",
"tuple",
")",
")",
":",
"seed",
"=",
"Seed",
"(",
"seed",
")",
"if",
"isinstance",
"(",
"seed",
",",
"Seed",
")",
":",
"C... | change CustomCarry seed
example:
change_custom_seed([1,2,3]) # then CustomCarry.SEED_LIST == '123' is True
:param seed:
:return: | [
"change",
"CustomCarry",
"seed",
"example",
":",
"change_custom_seed",
"(",
"[",
"1",
"2",
"3",
"]",
")",
"#",
"then",
"CustomCarry",
".",
"SEED_LIST",
"==",
"123",
"is",
"True",
":",
"param",
"seed",
":",
":",
"return",
":"
] | train | https://github.com/hiddes/custom/blob/29a9931b21b1a1b84b25542bcf11fae735f973fd/custom/CustomCarry/custom.py#L115-L126 |
smbapps/isolcss | isolcss/parser.py | matchiter | def matchiter(r, s, flags=0):
"""
Yields contiguous MatchObjects of r in s.
Raises ValueError if r eventually doesn't match contiguously.
"""
if isinstance(r, basestring):
r = re.compile(r, flags)
i = 0
while s:
m = r.match(s)
g = m and m.group(0)
if not m or ... | python | def matchiter(r, s, flags=0):
"""
Yields contiguous MatchObjects of r in s.
Raises ValueError if r eventually doesn't match contiguously.
"""
if isinstance(r, basestring):
r = re.compile(r, flags)
i = 0
while s:
m = r.match(s)
g = m and m.group(0)
if not m or ... | [
"def",
"matchiter",
"(",
"r",
",",
"s",
",",
"flags",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"r",
",",
"basestring",
")",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"r",
",",
"flags",
")",
"i",
"=",
"0",
"while",
"s",
":",
"m",
"=",
"r... | Yields contiguous MatchObjects of r in s.
Raises ValueError if r eventually doesn't match contiguously. | [
"Yields",
"contiguous",
"MatchObjects",
"of",
"r",
"in",
"s",
".",
"Raises",
"ValueError",
"if",
"r",
"eventually",
"doesn",
"t",
"match",
"contiguously",
"."
] | train | https://github.com/smbapps/isolcss/blob/1613dfd297f64292af1216855b6d096f2bed82fe/isolcss/parser.py#L131-L146 |
smbapps/isolcss | isolcss/parser.py | matchall | def matchall(r, s, flags=0):
"""
Returns the list of contiguous string matches of r in s,
or None if r does not successively match the entire s.
"""
try:
return [m.group(0) for m in matchiter(r, s, flags)]
except ValueError:
return None | python | def matchall(r, s, flags=0):
"""
Returns the list of contiguous string matches of r in s,
or None if r does not successively match the entire s.
"""
try:
return [m.group(0) for m in matchiter(r, s, flags)]
except ValueError:
return None | [
"def",
"matchall",
"(",
"r",
",",
"s",
",",
"flags",
"=",
"0",
")",
":",
"try",
":",
"return",
"[",
"m",
".",
"group",
"(",
"0",
")",
"for",
"m",
"in",
"matchiter",
"(",
"r",
",",
"s",
",",
"flags",
")",
"]",
"except",
"ValueError",
":",
"ret... | Returns the list of contiguous string matches of r in s,
or None if r does not successively match the entire s. | [
"Returns",
"the",
"list",
"of",
"contiguous",
"string",
"matches",
"of",
"r",
"in",
"s",
"or",
"None",
"if",
"r",
"does",
"not",
"successively",
"match",
"the",
"entire",
"s",
"."
] | train | https://github.com/smbapps/isolcss/blob/1613dfd297f64292af1216855b6d096f2bed82fe/isolcss/parser.py#L149-L157 |
diffeo/yakonfig | yakonfig/configurable.py | check_subconfig | def check_subconfig(config, name, sub):
"""Validate the configuration of an object within this.
This calls :meth:`Configurable.check_config` or equivalent on `sub`.
A dictionary configuration for `sub` is required in `config`.
>>> def check_config(config, name):
... for sub in sub_modules:
... | python | def check_subconfig(config, name, sub):
"""Validate the configuration of an object within this.
This calls :meth:`Configurable.check_config` or equivalent on `sub`.
A dictionary configuration for `sub` is required in `config`.
>>> def check_config(config, name):
... for sub in sub_modules:
... | [
"def",
"check_subconfig",
"(",
"config",
",",
"name",
",",
"sub",
")",
":",
"subname",
"=",
"sub",
".",
"config_name",
"subconfig",
"=",
"config",
".",
"setdefault",
"(",
"subname",
",",
"{",
"}",
")",
"if",
"not",
"isinstance",
"(",
"subconfig",
",",
... | Validate the configuration of an object within this.
This calls :meth:`Configurable.check_config` or equivalent on `sub`.
A dictionary configuration for `sub` is required in `config`.
>>> def check_config(config, name):
... for sub in sub_modules:
... check_subconfig(config, name, sub)... | [
"Validate",
"the",
"configuration",
"of",
"an",
"object",
"within",
"this",
"."
] | train | https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/configurable.py#L299-L323 |
pacificclimate/cfmeta | cfmeta/cmip5file.py | get_cmor_fp_meta | def get_cmor_fp_meta(fp):
"""Processes a CMOR style file path.
Section 3.1 of the `Data Reference Syntax`_ details:
The standard CMIP5 output tool CMOR optionally writes output files
to a directory structure mapping DRS components to directory names as:
<activity>/<product>/<insti... | python | def get_cmor_fp_meta(fp):
"""Processes a CMOR style file path.
Section 3.1 of the `Data Reference Syntax`_ details:
The standard CMIP5 output tool CMOR optionally writes output files
to a directory structure mapping DRS components to directory names as:
<activity>/<product>/<insti... | [
"def",
"get_cmor_fp_meta",
"(",
"fp",
")",
":",
"# Copy metadata list then reverse to start at end of path",
"directory_meta",
"=",
"list",
"(",
"CMIP5_FP_ATTS",
")",
"# Prefer meta extracted from filename",
"meta",
"=",
"get_dir_meta",
"(",
"fp",
",",
"directory_meta",
")"... | Processes a CMOR style file path.
Section 3.1 of the `Data Reference Syntax`_ details:
The standard CMIP5 output tool CMOR optionally writes output files
to a directory structure mapping DRS components to directory names as:
<activity>/<product>/<institute>/<model>/<experiment>/<frequ... | [
"Processes",
"a",
"CMOR",
"style",
"file",
"path",
"."
] | train | https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmip5file.py#L124-L152 |
pacificclimate/cfmeta | cfmeta/cmip5file.py | get_datanode_fp_meta | def get_datanode_fp_meta(fp):
"""Processes a datanode style file path.
Section 3.2 of the `Data Reference Syntax`_ details:
It is recommended that ESGF data nodes should layout datasets
on disk mapping DRS components to directories as:
<activity>/<product>/<institute>/<model>/<exp... | python | def get_datanode_fp_meta(fp):
"""Processes a datanode style file path.
Section 3.2 of the `Data Reference Syntax`_ details:
It is recommended that ESGF data nodes should layout datasets
on disk mapping DRS components to directories as:
<activity>/<product>/<institute>/<model>/<exp... | [
"def",
"get_datanode_fp_meta",
"(",
"fp",
")",
":",
"# Copy metadata list then reverse to start at end of path",
"directory_meta",
"=",
"list",
"(",
"CMIP5_DATANODE_FP_ATTS",
")",
"# Prefer meta extracted from filename",
"meta",
"=",
"get_dir_meta",
"(",
"fp",
",",
"directory... | Processes a datanode style file path.
Section 3.2 of the `Data Reference Syntax`_ details:
It is recommended that ESGF data nodes should layout datasets
on disk mapping DRS components to directories as:
<activity>/<product>/<institute>/<model>/<experiment>/
<frequency>/<mo... | [
"Processes",
"a",
"datanode",
"style",
"file",
"path",
"."
] | train | https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmip5file.py#L154-L183 |
pacificclimate/cfmeta | cfmeta/cmip5file.py | get_cmor_fname_meta | def get_cmor_fname_meta(fname):
"""Processes a CMOR style file name.
Section 3.3 of the `Data Reference Syntax`_ details:
filename = <variable name>_<mip_table>_<model>_<experiment>_
<ensemble_member>[_<temporal_subset>][_<geographical_info>].nc
Temporal subsets are detailed in sectio... | python | def get_cmor_fname_meta(fname):
"""Processes a CMOR style file name.
Section 3.3 of the `Data Reference Syntax`_ details:
filename = <variable name>_<mip_table>_<model>_<experiment>_
<ensemble_member>[_<temporal_subset>][_<geographical_info>].nc
Temporal subsets are detailed in sectio... | [
"def",
"get_cmor_fname_meta",
"(",
"fname",
")",
":",
"if",
"'/'",
"in",
"fname",
":",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fname",
")",
"[",
"1",
"]",
"fname",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"[",
"0",... | Processes a CMOR style file name.
Section 3.3 of the `Data Reference Syntax`_ details:
filename = <variable name>_<mip_table>_<model>_<experiment>_
<ensemble_member>[_<temporal_subset>][_<geographical_info>].nc
Temporal subsets are detailed in section 2.4:
Time instants or period... | [
"Processes",
"a",
"CMOR",
"style",
"file",
"name",
"."
] | train | https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmip5file.py#L185-L244 |
fr33jc/bang | bang/inventory.py | get_ansible_groups | def get_ansible_groups(group_map):
"""
Constructs a list of :class:`ansible.inventory.group.Group` objects from a
map of lists of host strings.
"""
# Some of this logic is cribbed from
# ansible.inventory.script.InventoryScript
all_hosts = {}
group_all = Group('all')
groups = [group... | python | def get_ansible_groups(group_map):
"""
Constructs a list of :class:`ansible.inventory.group.Group` objects from a
map of lists of host strings.
"""
# Some of this logic is cribbed from
# ansible.inventory.script.InventoryScript
all_hosts = {}
group_all = Group('all')
groups = [group... | [
"def",
"get_ansible_groups",
"(",
"group_map",
")",
":",
"# Some of this logic is cribbed from",
"# ansible.inventory.script.InventoryScript",
"all_hosts",
"=",
"{",
"}",
"group_all",
"=",
"Group",
"(",
"'all'",
")",
"groups",
"=",
"[",
"group_all",
"]",
"for",
"gname... | Constructs a list of :class:`ansible.inventory.group.Group` objects from a
map of lists of host strings. | [
"Constructs",
"a",
"list",
"of",
":",
"class",
":",
"ansible",
".",
"inventory",
".",
"group",
".",
"Group",
"objects",
"from",
"a",
"map",
"of",
"lists",
"of",
"host",
"strings",
"."
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/inventory.py#L23-L43 |
za-creature/gulpless | gulpless/reactor.py | Reactor.run | def run(self, once=False):
"""Runs the reactor in the main thread."""
self._once = once
self.start()
while self.running:
try:
time.sleep(1.0)
except KeyboardInterrupt:
self.stop()
self.join() | python | def run(self, once=False):
"""Runs the reactor in the main thread."""
self._once = once
self.start()
while self.running:
try:
time.sleep(1.0)
except KeyboardInterrupt:
self.stop()
self.join() | [
"def",
"run",
"(",
"self",
",",
"once",
"=",
"False",
")",
":",
"self",
".",
"_once",
"=",
"once",
"self",
".",
"start",
"(",
")",
"while",
"self",
".",
"running",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"1.0",
")",
"except",
"KeyboardInterrupt... | Runs the reactor in the main thread. | [
"Runs",
"the",
"reactor",
"in",
"the",
"main",
"thread",
"."
] | train | https://github.com/za-creature/gulpless/blob/fd73907dbe86880086719816bb042233f85121f6/gulpless/reactor.py#L47-L56 |
lewisjared/credkeep | credkeep/util.py | clear_to_enc_filename | def clear_to_enc_filename(fname):
"""
Converts the filename of a cleartext file and convert it to an encrypted filename
:param fname:
:return: filename of encrypted secret file if found, else None
"""
if not fname.lower().endswith('.json'):
raise CredkeepException('Invalid filetype')
... | python | def clear_to_enc_filename(fname):
"""
Converts the filename of a cleartext file and convert it to an encrypted filename
:param fname:
:return: filename of encrypted secret file if found, else None
"""
if not fname.lower().endswith('.json'):
raise CredkeepException('Invalid filetype')
... | [
"def",
"clear_to_enc_filename",
"(",
"fname",
")",
":",
"if",
"not",
"fname",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.json'",
")",
":",
"raise",
"CredkeepException",
"(",
"'Invalid filetype'",
")",
"if",
"fname",
".",
"lower",
"(",
")",
".",
"en... | Converts the filename of a cleartext file and convert it to an encrypted filename
:param fname:
:return: filename of encrypted secret file if found, else None | [
"Converts",
"the",
"filename",
"of",
"a",
"cleartext",
"file",
"and",
"convert",
"it",
"to",
"an",
"encrypted",
"filename"
] | train | https://github.com/lewisjared/credkeep/blob/63638ced094992552a28109b91839bcbbbe9230a/credkeep/util.py#L12-L27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.