repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
helixyte/everest | everest/representers/config.py | RepresenterConfiguration.get_attribute_option | def get_attribute_option(self, attribute, option_name):
"""
Returns the value of the given attribute option for the specified
attribute.
"""
self.__validate_attribute_option_name(option_name)
attribute_key = self.__make_key(attribute)
return self.__attribute_optio... | python | def get_attribute_option(self, attribute, option_name):
"""
Returns the value of the given attribute option for the specified
attribute.
"""
self.__validate_attribute_option_name(option_name)
attribute_key = self.__make_key(attribute)
return self.__attribute_optio... | [
"def",
"get_attribute_option",
"(",
"self",
",",
"attribute",
",",
"option_name",
")",
":",
"self",
".",
"__validate_attribute_option_name",
"(",
"option_name",
")",
"attribute_key",
"=",
"self",
".",
"__make_key",
"(",
"attribute",
")",
"return",
"self",
".",
"... | Returns the value of the given attribute option for the specified
attribute. | [
"Returns",
"the",
"value",
"of",
"the",
"given",
"attribute",
"option",
"for",
"the",
"specified",
"attribute",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/config.py#L126-L133 | train | 58,200 |
helixyte/everest | everest/representers/config.py | RepresenterConfiguration.get_attribute_options | def get_attribute_options(self, attribute=None):
"""
Returns a copy of the mapping options for the given attribute name
or a copy of all mapping options, if no attribute name is provided.
All options that were not explicitly configured are given a default
value of `None`.
... | python | def get_attribute_options(self, attribute=None):
"""
Returns a copy of the mapping options for the given attribute name
or a copy of all mapping options, if no attribute name is provided.
All options that were not explicitly configured are given a default
value of `None`.
... | [
"def",
"get_attribute_options",
"(",
"self",
",",
"attribute",
"=",
"None",
")",
":",
"attribute_key",
"=",
"self",
".",
"__make_key",
"(",
"attribute",
")",
"if",
"attribute_key",
"is",
"None",
":",
"opts",
"=",
"defaultdict",
"(",
"self",
".",
"_default_at... | Returns a copy of the mapping options for the given attribute name
or a copy of all mapping options, if no attribute name is provided.
All options that were not explicitly configured are given a default
value of `None`.
:param tuple attribute_key: attribute name or tuple specifying an
... | [
"Returns",
"a",
"copy",
"of",
"the",
"mapping",
"options",
"for",
"the",
"given",
"attribute",
"name",
"or",
"a",
"copy",
"of",
"all",
"mapping",
"options",
"if",
"no",
"attribute",
"name",
"is",
"provided",
".",
"All",
"options",
"that",
"were",
"not",
... | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/config.py#L135-L155 | train | 58,201 |
helixyte/everest | everest/representers/config.py | RepresenterConfigTraverser.run | def run(self, visitor):
"""
Traverses this representer configuration traverser with the given
visitor.
:param visitor: :class:`RepresenterConfigVisitorBase` instance.
"""
attr_option_map = self.__config.get_attribute_options()
# Sorting the keys results in a dept... | python | def run(self, visitor):
"""
Traverses this representer configuration traverser with the given
visitor.
:param visitor: :class:`RepresenterConfigVisitorBase` instance.
"""
attr_option_map = self.__config.get_attribute_options()
# Sorting the keys results in a dept... | [
"def",
"run",
"(",
"self",
",",
"visitor",
")",
":",
"attr_option_map",
"=",
"self",
".",
"__config",
".",
"get_attribute_options",
"(",
")",
"# Sorting the keys results in a depth-first traversal, which is just",
"# what we want.",
"for",
"(",
"key",
",",
"key_attr_opt... | Traverses this representer configuration traverser with the given
visitor.
:param visitor: :class:`RepresenterConfigVisitorBase` instance. | [
"Traverses",
"this",
"representer",
"configuration",
"traverser",
"with",
"the",
"given",
"visitor",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/config.py#L200-L213 | train | 58,202 |
expert360/cfn-params | cfnparams/resolution.py | with_retry | def with_retry(cls, methods):
"""
Wraps the given list of methods in a class with an exponential-back
retry mechanism.
"""
retry_with_backoff = retry(
retry_on_exception=lambda e: isinstance(e, BotoServerError),
wait_exponential_multiplier=1000,
wait_exponential_max=10000
... | python | def with_retry(cls, methods):
"""
Wraps the given list of methods in a class with an exponential-back
retry mechanism.
"""
retry_with_backoff = retry(
retry_on_exception=lambda e: isinstance(e, BotoServerError),
wait_exponential_multiplier=1000,
wait_exponential_max=10000
... | [
"def",
"with_retry",
"(",
"cls",
",",
"methods",
")",
":",
"retry_with_backoff",
"=",
"retry",
"(",
"retry_on_exception",
"=",
"lambda",
"e",
":",
"isinstance",
"(",
"e",
",",
"BotoServerError",
")",
",",
"wait_exponential_multiplier",
"=",
"1000",
",",
"wait_... | Wraps the given list of methods in a class with an exponential-back
retry mechanism. | [
"Wraps",
"the",
"given",
"list",
"of",
"methods",
"in",
"a",
"class",
"with",
"an",
"exponential",
"-",
"back",
"retry",
"mechanism",
"."
] | f6d9d796b8ce346e9fd916e26ed08958e5356e31 | https://github.com/expert360/cfn-params/blob/f6d9d796b8ce346e9fd916e26ed08958e5356e31/cfnparams/resolution.py#L10-L24 | train | 58,203 |
AtomHash/evernode | evernode/classes/json.py | Json.from_file | def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True) | python | def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True) | [
"def",
"from_file",
"(",
"file_path",
")",
"->",
"dict",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"json_stream",
":",
"return",
"Json",
".",
"parse",
"(",
"json_stream",
",",
"True",
")"
... | Load JSON file | [
"Load",
"JSON",
"file"
] | b2fb91555fb937a3f3eba41db56dee26f9b034be | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/json.py#L55-L58 | train | 58,204 |
AtomHash/evernode | evernode/classes/json.py | Json.safe_values | def safe_values(self, value):
""" Parse non-string values that will not serialize """
# TODO: override-able?
string_val = ""
if isinstance(value, datetime.date):
try:
string_val = value.strftime('{0}{1}{2}'.format(
current_app.config... | python | def safe_values(self, value):
""" Parse non-string values that will not serialize """
# TODO: override-able?
string_val = ""
if isinstance(value, datetime.date):
try:
string_val = value.strftime('{0}{1}{2}'.format(
current_app.config... | [
"def",
"safe_values",
"(",
"self",
",",
"value",
")",
":",
"# TODO: override-able?\r",
"string_val",
"=",
"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
":",
"try",
":",
"string_val",
"=",
"value",
".",
"strftime",
"(",
"'{0}{... | Parse non-string values that will not serialize | [
"Parse",
"non",
"-",
"string",
"values",
"that",
"will",
"not",
"serialize"
] | b2fb91555fb937a3f3eba41db56dee26f9b034be | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/json.py#L73-L91 | train | 58,205 |
AtomHash/evernode | evernode/classes/json.py | Json.camel_case | def camel_case(self, snake_case):
""" Convert snake case to camel case """
components = snake_case.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | python | def camel_case(self, snake_case):
""" Convert snake case to camel case """
components = snake_case.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | [
"def",
"camel_case",
"(",
"self",
",",
"snake_case",
")",
":",
"components",
"=",
"snake_case",
".",
"split",
"(",
"'_'",
")",
"return",
"components",
"[",
"0",
"]",
"+",
"\"\"",
".",
"join",
"(",
"x",
".",
"title",
"(",
")",
"for",
"x",
"in",
"com... | Convert snake case to camel case | [
"Convert",
"snake",
"case",
"to",
"camel",
"case"
] | b2fb91555fb937a3f3eba41db56dee26f9b034be | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/json.py#L93-L96 | train | 58,206 |
AtomHash/evernode | evernode/classes/json.py | Json.__find_object_children | def __find_object_children(self, obj) -> dict:
""" Convert object to flattened object """
if hasattr(obj, 'items') and \
isinstance(obj.items, types.BuiltinFunctionType):
return self.__construct_object(obj)
elif isinstance(obj, (list, tuple, set)):
r... | python | def __find_object_children(self, obj) -> dict:
""" Convert object to flattened object """
if hasattr(obj, 'items') and \
isinstance(obj.items, types.BuiltinFunctionType):
return self.__construct_object(obj)
elif isinstance(obj, (list, tuple, set)):
r... | [
"def",
"__find_object_children",
"(",
"self",
",",
"obj",
")",
"->",
"dict",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'items'",
")",
"and",
"isinstance",
"(",
"obj",
".",
"items",
",",
"types",
".",
"BuiltinFunctionType",
")",
":",
"return",
"self",
".",
... | Convert object to flattened object | [
"Convert",
"object",
"to",
"flattened",
"object"
] | b2fb91555fb937a3f3eba41db56dee26f9b034be | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/json.py#L98-L118 | train | 58,207 |
AtomHash/evernode | evernode/classes/json.py | Json.__iterate_value | def __iterate_value(self, value):
""" Return value for JSON serialization """
if hasattr(value, '__dict__') or isinstance(value, dict):
return self.__find_object_children(value) # go through dict/class
elif isinstance(value, (list, tuple, set)):
return self.__constr... | python | def __iterate_value(self, value):
""" Return value for JSON serialization """
if hasattr(value, '__dict__') or isinstance(value, dict):
return self.__find_object_children(value) # go through dict/class
elif isinstance(value, (list, tuple, set)):
return self.__constr... | [
"def",
"__iterate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__dict__'",
")",
"or",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"self",
".",
"__find_object_children",
"(",
"value",
")",
"# go through... | Return value for JSON serialization | [
"Return",
"value",
"for",
"JSON",
"serialization"
] | b2fb91555fb937a3f3eba41db56dee26f9b034be | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/json.py#L137-L143 | train | 58,208 |
rajeevs1992/pyhealthvault | src/healthvaultlib/objects/vocabularykey.py | VocabularyKey.write_xml | def write_xml(self):
'''
Writes a VocabularyKey Xml as per Healthvault schema.
:returns: lxml.etree.Element representing a single VocabularyKey
'''
key = None
if self. language is not None:
lang = {}
lang['{http://www.w3.org/XML/1998/names... | python | def write_xml(self):
'''
Writes a VocabularyKey Xml as per Healthvault schema.
:returns: lxml.etree.Element representing a single VocabularyKey
'''
key = None
if self. language is not None:
lang = {}
lang['{http://www.w3.org/XML/1998/names... | [
"def",
"write_xml",
"(",
"self",
")",
":",
"key",
"=",
"None",
"if",
"self",
".",
"language",
"is",
"not",
"None",
":",
"lang",
"=",
"{",
"}",
"lang",
"[",
"'{http://www.w3.org/XML/1998/namespace}lang'",
"]",
"=",
"self",
".",
"language",
"key",
"=",
"et... | Writes a VocabularyKey Xml as per Healthvault schema.
:returns: lxml.etree.Element representing a single VocabularyKey | [
"Writes",
"a",
"VocabularyKey",
"Xml",
"as",
"per",
"Healthvault",
"schema",
"."
] | 2b6fa7c1687300bcc2e501368883fbb13dc80495 | https://github.com/rajeevs1992/pyhealthvault/blob/2b6fa7c1687300bcc2e501368883fbb13dc80495/src/healthvaultlib/objects/vocabularykey.py#L34-L67 | train | 58,209 |
rajeevs1992/pyhealthvault | src/healthvaultlib/objects/vocabularykey.py | VocabularyKey.parse_xml | def parse_xml(self, key_xml):
'''
Parse a VocabularyKey from an Xml as per Healthvault
schema.
:param key_xml: lxml.etree.Element representing a single VocabularyKey
'''
xmlutils = XmlUtils(key_xml)
self.name = xmlutils.get_string_by_xpath('name')
... | python | def parse_xml(self, key_xml):
'''
Parse a VocabularyKey from an Xml as per Healthvault
schema.
:param key_xml: lxml.etree.Element representing a single VocabularyKey
'''
xmlutils = XmlUtils(key_xml)
self.name = xmlutils.get_string_by_xpath('name')
... | [
"def",
"parse_xml",
"(",
"self",
",",
"key_xml",
")",
":",
"xmlutils",
"=",
"XmlUtils",
"(",
"key_xml",
")",
"self",
".",
"name",
"=",
"xmlutils",
".",
"get_string_by_xpath",
"(",
"'name'",
")",
"self",
".",
"family",
"=",
"xmlutils",
".",
"get_string_by_x... | Parse a VocabularyKey from an Xml as per Healthvault
schema.
:param key_xml: lxml.etree.Element representing a single VocabularyKey | [
"Parse",
"a",
"VocabularyKey",
"from",
"an",
"Xml",
"as",
"per",
"Healthvault",
"schema",
"."
] | 2b6fa7c1687300bcc2e501368883fbb13dc80495 | https://github.com/rajeevs1992/pyhealthvault/blob/2b6fa7c1687300bcc2e501368883fbb13dc80495/src/healthvaultlib/objects/vocabularykey.py#L69-L82 | train | 58,210 |
kxz/littlebrother | littlebrother/__main__.py | print_and_exit | def print_and_exit(results):
"""Print each result and stop the reactor."""
for success, value in results:
if success:
print value.encode(locale.getpreferredencoding())
else:
value.printTraceback() | python | def print_and_exit(results):
"""Print each result and stop the reactor."""
for success, value in results:
if success:
print value.encode(locale.getpreferredencoding())
else:
value.printTraceback() | [
"def",
"print_and_exit",
"(",
"results",
")",
":",
"for",
"success",
",",
"value",
"in",
"results",
":",
"if",
"success",
":",
"print",
"value",
".",
"encode",
"(",
"locale",
".",
"getpreferredencoding",
"(",
")",
")",
"else",
":",
"value",
".",
"printTr... | Print each result and stop the reactor. | [
"Print",
"each",
"result",
"and",
"stop",
"the",
"reactor",
"."
] | af9ec9af5c0de9a74796bb7e16a6b836286e8b9f | https://github.com/kxz/littlebrother/blob/af9ec9af5c0de9a74796bb7e16a6b836286e8b9f/littlebrother/__main__.py#L15-L21 | train | 58,211 |
brap/brap | brap/compilers/circular_dependency_compiler.py | GraphSorter._topological_sort | def _topological_sort(self):
"""
Kahn's algorithm for Topological Sorting
- Finds cycles in graph
- Computes dependency weight
"""
sorted_graph = []
node_map = self._graph.get_nodes()
nodes = [NodeVisitor(node_map[node]) for node in node_map]
def... | python | def _topological_sort(self):
"""
Kahn's algorithm for Topological Sorting
- Finds cycles in graph
- Computes dependency weight
"""
sorted_graph = []
node_map = self._graph.get_nodes()
nodes = [NodeVisitor(node_map[node]) for node in node_map]
def... | [
"def",
"_topological_sort",
"(",
"self",
")",
":",
"sorted_graph",
"=",
"[",
"]",
"node_map",
"=",
"self",
".",
"_graph",
".",
"get_nodes",
"(",
")",
"nodes",
"=",
"[",
"NodeVisitor",
"(",
"node_map",
"[",
"node",
"]",
")",
"for",
"node",
"in",
"node_m... | Kahn's algorithm for Topological Sorting
- Finds cycles in graph
- Computes dependency weight | [
"Kahn",
"s",
"algorithm",
"for",
"Topological",
"Sorting",
"-",
"Finds",
"cycles",
"in",
"graph",
"-",
"Computes",
"dependency",
"weight"
] | 227d1b6ce2799b7caf1d98d8805e821d19d0969b | https://github.com/brap/brap/blob/227d1b6ce2799b7caf1d98d8805e821d19d0969b/brap/compilers/circular_dependency_compiler.py#L44-L85 | train | 58,212 |
silver-castle/mach9 | mach9/config.py | Config.load_environment_vars | def load_environment_vars(self):
"""
Looks for any MACH9_ prefixed environment variables and applies
them to the configuration if present.
"""
for k, v in os.environ.items():
if k.startswith(MACH9_PREFIX):
_, config_key = k.split(MACH9_PREFIX, 1)
... | python | def load_environment_vars(self):
"""
Looks for any MACH9_ prefixed environment variables and applies
them to the configuration if present.
"""
for k, v in os.environ.items():
if k.startswith(MACH9_PREFIX):
_, config_key = k.split(MACH9_PREFIX, 1)
... | [
"def",
"load_environment_vars",
"(",
"self",
")",
":",
"for",
"k",
",",
"v",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"MACH9_PREFIX",
")",
":",
"_",
",",
"config_key",
"=",
"k",
".",
"split",
"(",
... | Looks for any MACH9_ prefixed environment variables and applies
them to the configuration if present. | [
"Looks",
"for",
"any",
"MACH9_",
"prefixed",
"environment",
"variables",
"and",
"applies",
"them",
"to",
"the",
"configuration",
"if",
"present",
"."
] | 7a623aab3c70d89d36ade6901b6307e115400c5e | https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/config.py#L193-L201 | train | 58,213 |
Jazzer360/python-examine | examine/examine.py | Structure.copy | def copy(self, parent=None):
"""Copies an existing structure and all of it's children"""
new = Structure(None, parent=parent)
new.key = self.key
new.type_ = self.type_
new.val_guaranteed = self.val_guaranteed
new.key_guaranteed = self.key_guaranteed
for child in s... | python | def copy(self, parent=None):
"""Copies an existing structure and all of it's children"""
new = Structure(None, parent=parent)
new.key = self.key
new.type_ = self.type_
new.val_guaranteed = self.val_guaranteed
new.key_guaranteed = self.key_guaranteed
for child in s... | [
"def",
"copy",
"(",
"self",
",",
"parent",
"=",
"None",
")",
":",
"new",
"=",
"Structure",
"(",
"None",
",",
"parent",
"=",
"parent",
")",
"new",
".",
"key",
"=",
"self",
".",
"key",
"new",
".",
"type_",
"=",
"self",
".",
"type_",
"new",
".",
"... | Copies an existing structure and all of it's children | [
"Copies",
"an",
"existing",
"structure",
"and",
"all",
"of",
"it",
"s",
"children"
] | d71dc07ad13ad3859b94456df092d161cdbbdc69 | https://github.com/Jazzer360/python-examine/blob/d71dc07ad13ad3859b94456df092d161cdbbdc69/examine/examine.py#L168-L177 | train | 58,214 |
Jazzer360/python-examine | examine/examine.py | Structure.generation | def generation(self):
"""Returns the number of ancestors that are dictionaries"""
if not self.parent:
return 0
elif self.parent.is_dict:
return 1 + self.parent.generation
else:
return self.parent.generation | python | def generation(self):
"""Returns the number of ancestors that are dictionaries"""
if not self.parent:
return 0
elif self.parent.is_dict:
return 1 + self.parent.generation
else:
return self.parent.generation | [
"def",
"generation",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"0",
"elif",
"self",
".",
"parent",
".",
"is_dict",
":",
"return",
"1",
"+",
"self",
".",
"parent",
".",
"generation",
"else",
":",
"return",
"self",
".",
... | Returns the number of ancestors that are dictionaries | [
"Returns",
"the",
"number",
"of",
"ancestors",
"that",
"are",
"dictionaries"
] | d71dc07ad13ad3859b94456df092d161cdbbdc69 | https://github.com/Jazzer360/python-examine/blob/d71dc07ad13ad3859b94456df092d161cdbbdc69/examine/examine.py#L180-L187 | train | 58,215 |
Jazzer360/python-examine | examine/examine.py | Structure.type_string | def type_string(self):
"""Returns a string representing the type of the structure"""
if self.is_tuple:
subtypes = [item.type_string for item in self.children]
return '{}({})'.format(
'' if self.val_guaranteed else '*',
', '.join(subtypes))
... | python | def type_string(self):
"""Returns a string representing the type of the structure"""
if self.is_tuple:
subtypes = [item.type_string for item in self.children]
return '{}({})'.format(
'' if self.val_guaranteed else '*',
', '.join(subtypes))
... | [
"def",
"type_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_tuple",
":",
"subtypes",
"=",
"[",
"item",
".",
"type_string",
"for",
"item",
"in",
"self",
".",
"children",
"]",
"return",
"'{}({})'",
".",
"format",
"(",
"''",
"if",
"self",
".",
"... | Returns a string representing the type of the structure | [
"Returns",
"a",
"string",
"representing",
"the",
"type",
"of",
"the",
"structure"
] | d71dc07ad13ad3859b94456df092d161cdbbdc69 | https://github.com/Jazzer360/python-examine/blob/d71dc07ad13ad3859b94456df092d161cdbbdc69/examine/examine.py#L190-L204 | train | 58,216 |
crccheck/dj-obj-update | obj_update.py | set_field | def set_field(obj, field_name, value):
"""Fancy setattr with debugging."""
old = getattr(obj, field_name)
field = obj._meta.get_field(field_name)
# is_relation is Django 1.8 only
if field.is_relation:
# If field_name is the `_id` field, then there is no 'pk' attr and
# old/value *is*... | python | def set_field(obj, field_name, value):
"""Fancy setattr with debugging."""
old = getattr(obj, field_name)
field = obj._meta.get_field(field_name)
# is_relation is Django 1.8 only
if field.is_relation:
# If field_name is the `_id` field, then there is no 'pk' attr and
# old/value *is*... | [
"def",
"set_field",
"(",
"obj",
",",
"field_name",
",",
"value",
")",
":",
"old",
"=",
"getattr",
"(",
"obj",
",",
"field_name",
")",
"field",
"=",
"obj",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
"# is_relation is Django 1.8 only",
"if",
"fi... | Fancy setattr with debugging. | [
"Fancy",
"setattr",
"with",
"debugging",
"."
] | 6f43ba88daeec7bb163db0d5dbcd18766dbc18cb | https://github.com/crccheck/dj-obj-update/blob/6f43ba88daeec7bb163db0d5dbcd18766dbc18cb/obj_update.py#L24-L48 | train | 58,217 |
crccheck/dj-obj-update | obj_update.py | obj_update | def obj_update(obj, data: dict, *, update_fields=UNSET, save: bool=True) -> bool:
"""
Fancy way to update `obj` with `data` dict.
Parameters
----------
obj : Django model instance
data
The data to update ``obj`` with
update_fields
Use your ``update_fields`` instead of our ge... | python | def obj_update(obj, data: dict, *, update_fields=UNSET, save: bool=True) -> bool:
"""
Fancy way to update `obj` with `data` dict.
Parameters
----------
obj : Django model instance
data
The data to update ``obj`` with
update_fields
Use your ``update_fields`` instead of our ge... | [
"def",
"obj_update",
"(",
"obj",
",",
"data",
":",
"dict",
",",
"*",
",",
"update_fields",
"=",
"UNSET",
",",
"save",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"for",
"field_name",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
... | Fancy way to update `obj` with `data` dict.
Parameters
----------
obj : Django model instance
data
The data to update ``obj`` with
update_fields
Use your ``update_fields`` instead of our generated one. If you need
an auto_now or auto_now_add field to get updated, set this to... | [
"Fancy",
"way",
"to",
"update",
"obj",
"with",
"data",
"dict",
"."
] | 6f43ba88daeec7bb163db0d5dbcd18766dbc18cb | https://github.com/crccheck/dj-obj-update/blob/6f43ba88daeec7bb163db0d5dbcd18766dbc18cb/obj_update.py#L63-L106 | train | 58,218 |
crccheck/dj-obj-update | obj_update.py | obj_update_or_create | def obj_update_or_create(model, defaults=None, update_fields=UNSET, **kwargs):
"""
Mimic queryset.update_or_create but using obj_update.
"""
obj, created = model.objects.get_or_create(defaults=defaults, **kwargs)
if created:
logger.debug('CREATED %s %s',
model._meta.obje... | python | def obj_update_or_create(model, defaults=None, update_fields=UNSET, **kwargs):
"""
Mimic queryset.update_or_create but using obj_update.
"""
obj, created = model.objects.get_or_create(defaults=defaults, **kwargs)
if created:
logger.debug('CREATED %s %s',
model._meta.obje... | [
"def",
"obj_update_or_create",
"(",
"model",
",",
"defaults",
"=",
"None",
",",
"update_fields",
"=",
"UNSET",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
",",
"created",
"=",
"model",
".",
"objects",
".",
"get_or_create",
"(",
"defaults",
"=",
"defaults",
... | Mimic queryset.update_or_create but using obj_update. | [
"Mimic",
"queryset",
".",
"update_or_create",
"but",
"using",
"obj_update",
"."
] | 6f43ba88daeec7bb163db0d5dbcd18766dbc18cb | https://github.com/crccheck/dj-obj-update/blob/6f43ba88daeec7bb163db0d5dbcd18766dbc18cb/obj_update.py#L109-L121 | train | 58,219 |
dariusbakunas/rawdisk | rawdisk/scheme/common.py | detect_scheme | def detect_scheme(filename):
"""Detects partitioning scheme of the source
Args:
filename (str): path to file or device for detection of \
partitioning scheme.
Returns:
SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN
Raises:
IOError: The file doesn't exist or cannot be opened ... | python | def detect_scheme(filename):
"""Detects partitioning scheme of the source
Args:
filename (str): path to file or device for detection of \
partitioning scheme.
Returns:
SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN
Raises:
IOError: The file doesn't exist or cannot be opened ... | [
"def",
"detect_scheme",
"(",
"filename",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'Detecting partitioning scheme'",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"# L... | Detects partitioning scheme of the source
Args:
filename (str): path to file or device for detection of \
partitioning scheme.
Returns:
SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN
Raises:
IOError: The file doesn't exist or cannot be opened for reading
>>> from rawdisk.sc... | [
"Detects",
"partitioning",
"scheme",
"of",
"the",
"source"
] | 1dc9d0b377fe5da3c406ccec4abc238c54167403 | https://github.com/dariusbakunas/rawdisk/blob/1dc9d0b377fe5da3c406ccec4abc238c54167403/rawdisk/scheme/common.py#L24-L67 | train | 58,220 |
mastro35/tyler | tyler.py | Tyler._has_file_rolled | def _has_file_rolled(self):
"""Check if the file has been rolled"""
# if the size is smaller then before, the file has
# probabilly been rolled
if self._fh:
size = self._getsize_of_current_file()
if size < self.oldsize:
return True
sel... | python | def _has_file_rolled(self):
"""Check if the file has been rolled"""
# if the size is smaller then before, the file has
# probabilly been rolled
if self._fh:
size = self._getsize_of_current_file()
if size < self.oldsize:
return True
sel... | [
"def",
"_has_file_rolled",
"(",
"self",
")",
":",
"# if the size is smaller then before, the file has",
"# probabilly been rolled",
"if",
"self",
".",
"_fh",
":",
"size",
"=",
"self",
".",
"_getsize_of_current_file",
"(",
")",
"if",
"size",
"<",
"self",
".",
"oldsiz... | Check if the file has been rolled | [
"Check",
"if",
"the",
"file",
"has",
"been",
"rolled"
] | 9f26ca4db45308a006f7848fa58079ca28eb9873 | https://github.com/mastro35/tyler/blob/9f26ca4db45308a006f7848fa58079ca28eb9873/tyler.py#L67-L78 | train | 58,221 |
mastro35/tyler | tyler.py | Tyler._open_file | def _open_file(self, filename):
"""Open a file to be tailed"""
if not self._os_is_windows:
self._fh = open(filename, "rb")
self.filename = filename
self._fh.seek(0, os.SEEK_SET)
self.oldsize = 0
return
# if we're in Windows, we need t... | python | def _open_file(self, filename):
"""Open a file to be tailed"""
if not self._os_is_windows:
self._fh = open(filename, "rb")
self.filename = filename
self._fh.seek(0, os.SEEK_SET)
self.oldsize = 0
return
# if we're in Windows, we need t... | [
"def",
"_open_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"_os_is_windows",
":",
"self",
".",
"_fh",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"self",
".",
"filename",
"=",
"filename",
"self",
".",
"_fh",
".",
"se... | Open a file to be tailed | [
"Open",
"a",
"file",
"to",
"be",
"tailed"
] | 9f26ca4db45308a006f7848fa58079ca28eb9873 | https://github.com/mastro35/tyler/blob/9f26ca4db45308a006f7848fa58079ca28eb9873/tyler.py#L80-L112 | train | 58,222 |
mastro35/tyler | tyler.py | Tyler._filehandle | def _filehandle(self):
"""
Return a filehandle to the file being tailed
"""
# if file is opened and it has been rolled we need to close the file
# and then to reopen it
if self._fh and self._has_file_rolled():
try:
self._fh.close()
... | python | def _filehandle(self):
"""
Return a filehandle to the file being tailed
"""
# if file is opened and it has been rolled we need to close the file
# and then to reopen it
if self._fh and self._has_file_rolled():
try:
self._fh.close()
... | [
"def",
"_filehandle",
"(",
"self",
")",
":",
"# if file is opened and it has been rolled we need to close the file",
"# and then to reopen it",
"if",
"self",
".",
"_fh",
"and",
"self",
".",
"_has_file_rolled",
"(",
")",
":",
"try",
":",
"self",
".",
"_fh",
".",
"clo... | Return a filehandle to the file being tailed | [
"Return",
"a",
"filehandle",
"to",
"the",
"file",
"being",
"tailed"
] | 9f26ca4db45308a006f7848fa58079ca28eb9873 | https://github.com/mastro35/tyler/blob/9f26ca4db45308a006f7848fa58079ca28eb9873/tyler.py#L114-L136 | train | 58,223 |
sdcooke/django_bundles | django_bundles/utils/__init__.py | get_class | def get_class(class_string):
"""
Get a class from a dotted string
"""
split_string = class_string.encode('ascii').split('.')
import_path = '.'.join(split_string[:-1])
class_name = split_string[-1]
if class_name:
try:
if import_path:
mod = __import__(impor... | python | def get_class(class_string):
"""
Get a class from a dotted string
"""
split_string = class_string.encode('ascii').split('.')
import_path = '.'.join(split_string[:-1])
class_name = split_string[-1]
if class_name:
try:
if import_path:
mod = __import__(impor... | [
"def",
"get_class",
"(",
"class_string",
")",
":",
"split_string",
"=",
"class_string",
".",
"encode",
"(",
"'ascii'",
")",
".",
"split",
"(",
"'.'",
")",
"import_path",
"=",
"'.'",
".",
"join",
"(",
"split_string",
"[",
":",
"-",
"1",
"]",
")",
"class... | Get a class from a dotted string | [
"Get",
"a",
"class",
"from",
"a",
"dotted",
"string"
] | 2810fc455ec7391283792c1f108f4e8340f5d12f | https://github.com/sdcooke/django_bundles/blob/2810fc455ec7391283792c1f108f4e8340f5d12f/django_bundles/utils/__init__.py#L1-L21 | train | 58,224 |
Yipit/eventlib | eventlib/api.py | _register_handler | def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HANDLER_REGISTRY
if not isinstance(event, basestring):
# If not basestring, it is a BaseEvent subclass.
# Th... | python | def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HANDLER_REGISTRY
if not isinstance(event, basestring):
# If not basestring, it is a BaseEvent subclass.
# Th... | [
"def",
"_register_handler",
"(",
"event",
",",
"fun",
",",
"external",
"=",
"False",
")",
":",
"registry",
"=",
"core",
".",
"HANDLER_REGISTRY",
"if",
"external",
":",
"registry",
"=",
"core",
".",
"EXTERNAL_HANDLER_REGISTRY",
"if",
"not",
"isinstance",
"(",
... | Register a function to be an event handler | [
"Register",
"a",
"function",
"to",
"be",
"an",
"event",
"handler"
] | 0cf29e5251a59fcbfc727af5f5157a3bb03832e2 | https://github.com/Yipit/eventlib/blob/0cf29e5251a59fcbfc727af5f5157a3bb03832e2/eventlib/api.py#L26-L41 | train | 58,225 |
Yipit/eventlib | eventlib/api.py | handler | def handler(param):
"""Decorator that associates a handler to an event class
This decorator works for both methods and functions. Since it only
registers the callable object and returns it without evaluating it.
The name param should be informed in a dotted notation and should
contain two informat... | python | def handler(param):
"""Decorator that associates a handler to an event class
This decorator works for both methods and functions. Since it only
registers the callable object and returns it without evaluating it.
The name param should be informed in a dotted notation and should
contain two informat... | [
"def",
"handler",
"(",
"param",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"basestring",
")",
":",
"return",
"lambda",
"f",
":",
"_register_handler",
"(",
"param",
",",
"f",
")",
"else",
":",
"core",
".",
"HANDLER_METHOD_REGISTRY",
".",
"append",
"... | Decorator that associates a handler to an event class
This decorator works for both methods and functions. Since it only
registers the callable object and returns it without evaluating it.
The name param should be informed in a dotted notation and should
contain two informations: the django app name a... | [
"Decorator",
"that",
"associates",
"a",
"handler",
"to",
"an",
"event",
"class"
] | 0cf29e5251a59fcbfc727af5f5157a3bb03832e2 | https://github.com/Yipit/eventlib/blob/0cf29e5251a59fcbfc727af5f5157a3bb03832e2/eventlib/api.py#L132-L160 | train | 58,226 |
Yipit/eventlib | eventlib/api.py | log | def log(name, data=None):
"""Entry point for the event lib that starts the logging process
This function uses the `name` param to find the event class that
will be processed to log stuff. This name must provide two
informations separated by a dot: the app name and the event class
name. Like this:
... | python | def log(name, data=None):
"""Entry point for the event lib that starts the logging process
This function uses the `name` param to find the event class that
will be processed to log stuff. This name must provide two
informations separated by a dot: the app name and the event class
name. Like this:
... | [
"def",
"log",
"(",
"name",
",",
"data",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"data",
".",
"update",
"(",
"core",
".",
"get_default_values",
"(",
"data",
")",
")",
"# InvalidEventNameError, EventNotFoundError",
"event_cls",
"=",
"core... | Entry point for the event lib that starts the logging process
This function uses the `name` param to find the event class that
will be processed to log stuff. This name must provide two
informations separated by a dot: the app name and the event class
name. Like this:
>>> name = 'deal.ActionLo... | [
"Entry",
"point",
"for",
"the",
"event",
"lib",
"that",
"starts",
"the",
"logging",
"process"
] | 0cf29e5251a59fcbfc727af5f5157a3bb03832e2 | https://github.com/Yipit/eventlib/blob/0cf29e5251a59fcbfc727af5f5157a3bb03832e2/eventlib/api.py#L167-L202 | train | 58,227 |
Yipit/eventlib | eventlib/api.py | BaseEvent.validate_keys | def validate_keys(self, *keys):
"""Validation helper to ensure that keys are present in data
This method makes sure that all of keys received here are
present in the data received from the caller.
It is better to call this method in the `validate()` method of
your event. Not in... | python | def validate_keys(self, *keys):
"""Validation helper to ensure that keys are present in data
This method makes sure that all of keys received here are
present in the data received from the caller.
It is better to call this method in the `validate()` method of
your event. Not in... | [
"def",
"validate_keys",
"(",
"self",
",",
"*",
"keys",
")",
":",
"current_keys",
"=",
"set",
"(",
"self",
".",
"data",
".",
"keys",
"(",
")",
")",
"needed_keys",
"=",
"set",
"(",
"keys",
")",
"if",
"not",
"needed_keys",
".",
"issubset",
"(",
"current... | Validation helper to ensure that keys are present in data
This method makes sure that all of keys received here are
present in the data received from the caller.
It is better to call this method in the `validate()` method of
your event. Not in the `clean()` one, since the first will be... | [
"Validation",
"helper",
"to",
"ensure",
"that",
"keys",
"are",
"present",
"in",
"data"
] | 0cf29e5251a59fcbfc727af5f5157a3bb03832e2 | https://github.com/Yipit/eventlib/blob/0cf29e5251a59fcbfc727af5f5157a3bb03832e2/eventlib/api.py#L89-L108 | train | 58,228 |
brmscheiner/ideogram | ideogram/ideogram.py | addProject | def addProject(gh_link):
''' Adds a github project to the data folder, unzips it, and deletes the zip file.
Returns the project name and the path to the project folder. '''
name = os.path.basename(gh_link)
zipurl = gh_link+"/archive/master.zip"
outzip = os.path.join('temp_data',name+'.zip')
if n... | python | def addProject(gh_link):
''' Adds a github project to the data folder, unzips it, and deletes the zip file.
Returns the project name and the path to the project folder. '''
name = os.path.basename(gh_link)
zipurl = gh_link+"/archive/master.zip"
outzip = os.path.join('temp_data',name+'.zip')
if n... | [
"def",
"addProject",
"(",
"gh_link",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"gh_link",
")",
"zipurl",
"=",
"gh_link",
"+",
"\"/archive/master.zip\"",
"outzip",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'temp_data'",
",",
"name",... | Adds a github project to the data folder, unzips it, and deletes the zip file.
Returns the project name and the path to the project folder. | [
"Adds",
"a",
"github",
"project",
"to",
"the",
"data",
"folder",
"unzips",
"it",
"and",
"deletes",
"the",
"zip",
"file",
".",
"Returns",
"the",
"project",
"name",
"and",
"the",
"path",
"to",
"the",
"project",
"folder",
"."
] | 422bf566c51fd56f7bbb6e75b16d18d52b4c7568 | https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/ideogram.py#L122-L136 | train | 58,229 |
brmscheiner/ideogram | ideogram/ideogram.py | Ideogram.cleanDir | def cleanDir(self):
''' Remove existing json datafiles in the target directory. '''
if os.path.isdir(self.outdir):
baddies = ['tout.json','nout.json','hout.json']
for file in baddies:
filepath = os.path.join(self.outdir,file)
if os.path.isfile(file... | python | def cleanDir(self):
''' Remove existing json datafiles in the target directory. '''
if os.path.isdir(self.outdir):
baddies = ['tout.json','nout.json','hout.json']
for file in baddies:
filepath = os.path.join(self.outdir,file)
if os.path.isfile(file... | [
"def",
"cleanDir",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"outdir",
")",
":",
"baddies",
"=",
"[",
"'tout.json'",
",",
"'nout.json'",
",",
"'hout.json'",
"]",
"for",
"file",
"in",
"baddies",
":",
"filepath",
"... | Remove existing json datafiles in the target directory. | [
"Remove",
"existing",
"json",
"datafiles",
"in",
"the",
"target",
"directory",
"."
] | 422bf566c51fd56f7bbb6e75b16d18d52b4c7568 | https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/ideogram.py#L30-L37 | train | 58,230 |
brmscheiner/ideogram | ideogram/ideogram.py | Ideogram.makeHTML | def makeHTML(self,mustachepath,htmlpath):
'''Write an html file by applying this ideogram's attributes to a mustache template. '''
subs = dict()
if self.title:
subs["title"]=self.title
subs["has_title"]=True
else:
subs["has_title"]=False
subs["... | python | def makeHTML(self,mustachepath,htmlpath):
'''Write an html file by applying this ideogram's attributes to a mustache template. '''
subs = dict()
if self.title:
subs["title"]=self.title
subs["has_title"]=True
else:
subs["has_title"]=False
subs["... | [
"def",
"makeHTML",
"(",
"self",
",",
"mustachepath",
",",
"htmlpath",
")",
":",
"subs",
"=",
"dict",
"(",
")",
"if",
"self",
".",
"title",
":",
"subs",
"[",
"\"title\"",
"]",
"=",
"self",
".",
"title",
"subs",
"[",
"\"has_title\"",
"]",
"=",
"True",
... | Write an html file by applying this ideogram's attributes to a mustache template. | [
"Write",
"an",
"html",
"file",
"by",
"applying",
"this",
"ideogram",
"s",
"attributes",
"to",
"a",
"mustache",
"template",
"."
] | 422bf566c51fd56f7bbb6e75b16d18d52b4c7568 | https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/ideogram.py#L85-L101 | train | 58,231 |
asascience-open/paegan-transport | paegan/transport/particles/particle.py | Particle.age | def age(self, **kwargs):
"""
Age this particle.
parameters (optional, only one allowed):
days (default)
hours
minutes
seconds
"""
if kwargs.get('days', None) is not None:
self._age += kwargs.get('days')
retu... | python | def age(self, **kwargs):
"""
Age this particle.
parameters (optional, only one allowed):
days (default)
hours
minutes
seconds
"""
if kwargs.get('days', None) is not None:
self._age += kwargs.get('days')
retu... | [
"def",
"age",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'days'",
",",
"None",
")",
"is",
"not",
"None",
":",
"self",
".",
"_age",
"+=",
"kwargs",
".",
"get",
"(",
"'days'",
")",
"return",
"if",
"kwargs",
... | Age this particle.
parameters (optional, only one allowed):
days (default)
hours
minutes
seconds | [
"Age",
"this",
"particle",
"."
] | 99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3 | https://github.com/asascience-open/paegan-transport/blob/99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3/paegan/transport/particles/particle.py#L203-L226 | train | 58,232 |
asascience-open/paegan-transport | paegan/transport/particles/particle.py | Particle.normalized_indexes | def normalized_indexes(self, model_timesteps):
"""
This function will normalize the particles locations
to the timestep of the model that was run. This is used
in output, as we should only be outputting the model timestep
that was chosen to be run.
In most cases, the le... | python | def normalized_indexes(self, model_timesteps):
"""
This function will normalize the particles locations
to the timestep of the model that was run. This is used
in output, as we should only be outputting the model timestep
that was chosen to be run.
In most cases, the le... | [
"def",
"normalized_indexes",
"(",
"self",
",",
"model_timesteps",
")",
":",
"# Clean up locations",
"# If duplicate time instances, remove the lower index ",
"clean_locs",
"=",
"[",
"]",
"for",
"i",
",",
"loc",
"in",
"enumerate",
"(",
"self",
".",
"locations",
")",
... | This function will normalize the particles locations
to the timestep of the model that was run. This is used
in output, as we should only be outputting the model timestep
that was chosen to be run.
In most cases, the length of the model_timesteps and the
particle's locations w... | [
"This",
"function",
"will",
"normalize",
"the",
"particles",
"locations",
"to",
"the",
"timestep",
"of",
"the",
"model",
"that",
"was",
"run",
".",
"This",
"is",
"used",
"in",
"output",
"as",
"we",
"should",
"only",
"be",
"outputting",
"the",
"model",
"tim... | 99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3 | https://github.com/asascience-open/paegan-transport/blob/99a7f4ea24f0f42d9b34d1fb0e87ab2c49315bd3/paegan/transport/particles/particle.py#L235-L272 | train | 58,233 |
mamrhein/specification | specification/specification.py | Specification.is_satisfied_by | def is_satisfied_by(self, candidate: Any, **kwds: Any) -> bool:
"""Return True if `candidate` satisfies the specification."""
candidate_name = self._candidate_name
context = self._context
if context:
if candidate_name in kwds:
raise ValueError(f"Candidate name... | python | def is_satisfied_by(self, candidate: Any, **kwds: Any) -> bool:
"""Return True if `candidate` satisfies the specification."""
candidate_name = self._candidate_name
context = self._context
if context:
if candidate_name in kwds:
raise ValueError(f"Candidate name... | [
"def",
"is_satisfied_by",
"(",
"self",
",",
"candidate",
":",
"Any",
",",
"*",
"*",
"kwds",
":",
"Any",
")",
"->",
"bool",
":",
"candidate_name",
"=",
"self",
".",
"_candidate_name",
"context",
"=",
"self",
".",
"_context",
"if",
"context",
":",
"if",
... | Return True if `candidate` satisfies the specification. | [
"Return",
"True",
"if",
"candidate",
"satisfies",
"the",
"specification",
"."
] | a4c09a0d286cda7a04e8a189f12e23edd97f64ea | https://github.com/mamrhein/specification/blob/a4c09a0d286cda7a04e8a189f12e23edd97f64ea/specification/specification.py#L115-L129 | train | 58,234 |
childsish/lhc-python | lhc/graph/graph.py | Graph.add_edge | def add_edge(self, fr, to):
""" Add an edge to the graph. Multiple edges between the same vertices will quietly be ignored. N-partite graphs
can be used to permit multiple edges by partitioning the graph into vertices and edges.
:param fr: The name of the origin vertex.
:param to: The n... | python | def add_edge(self, fr, to):
""" Add an edge to the graph. Multiple edges between the same vertices will quietly be ignored. N-partite graphs
can be used to permit multiple edges by partitioning the graph into vertices and edges.
:param fr: The name of the origin vertex.
:param to: The n... | [
"def",
"add_edge",
"(",
"self",
",",
"fr",
",",
"to",
")",
":",
"fr",
"=",
"self",
".",
"add_vertex",
"(",
"fr",
")",
"to",
"=",
"self",
".",
"add_vertex",
"(",
"to",
")",
"self",
".",
"adjacency",
"[",
"fr",
"]",
".",
"children",
".",
"add",
"... | Add an edge to the graph. Multiple edges between the same vertices will quietly be ignored. N-partite graphs
can be used to permit multiple edges by partitioning the graph into vertices and edges.
:param fr: The name of the origin vertex.
:param to: The name of the destination vertex.
:... | [
"Add",
"an",
"edge",
"to",
"the",
"graph",
".",
"Multiple",
"edges",
"between",
"the",
"same",
"vertices",
"will",
"quietly",
"be",
"ignored",
".",
"N",
"-",
"partite",
"graphs",
"can",
"be",
"used",
"to",
"permit",
"multiple",
"edges",
"by",
"partitioning... | 0a669f46a40a39f24d28665e8b5b606dc7e86beb | https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/graph/graph.py#L85-L96 | train | 58,235 |
rackerlabs/python-lunrclient | lunrclient/storage.py | StorageVolume.clone | def clone(self, source_id, backup_id, size,
volume_id=None, source_host=None):
"""
create a volume then clone the contents of
the backup into the new volume
"""
volume_id = volume_id or str(uuid.uuid4())
return self.http_put('/volumes/%s' % volume_id,
... | python | def clone(self, source_id, backup_id, size,
volume_id=None, source_host=None):
"""
create a volume then clone the contents of
the backup into the new volume
"""
volume_id = volume_id or str(uuid.uuid4())
return self.http_put('/volumes/%s' % volume_id,
... | [
"def",
"clone",
"(",
"self",
",",
"source_id",
",",
"backup_id",
",",
"size",
",",
"volume_id",
"=",
"None",
",",
"source_host",
"=",
"None",
")",
":",
"volume_id",
"=",
"volume_id",
"or",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"return",
"s... | create a volume then clone the contents of
the backup into the new volume | [
"create",
"a",
"volume",
"then",
"clone",
"the",
"contents",
"of",
"the",
"backup",
"into",
"the",
"new",
"volume"
] | f26a450a422600f492480bfa42cbee50a5c7016f | https://github.com/rackerlabs/python-lunrclient/blob/f26a450a422600f492480bfa42cbee50a5c7016f/lunrclient/storage.py#L74-L87 | train | 58,236 |
rackerlabs/python-lunrclient | lunrclient/storage.py | StorageBackup.create | def create(self, volume_id, backup_id=None, timestamp=None):
"""
create a backup of a volume
"""
backup_id = backup_id or str(uuid.uuid4())
timestamp = timestamp or int(time())
return self.http_put('/volumes/%s/backups/%s' % (volume_id, backup_id),
... | python | def create(self, volume_id, backup_id=None, timestamp=None):
"""
create a backup of a volume
"""
backup_id = backup_id or str(uuid.uuid4())
timestamp = timestamp or int(time())
return self.http_put('/volumes/%s/backups/%s' % (volume_id, backup_id),
... | [
"def",
"create",
"(",
"self",
",",
"volume_id",
",",
"backup_id",
"=",
"None",
",",
"timestamp",
"=",
"None",
")",
":",
"backup_id",
"=",
"backup_id",
"or",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"timestamp",
"=",
"timestamp",
"or",
"int",
... | create a backup of a volume | [
"create",
"a",
"backup",
"of",
"a",
"volume"
] | f26a450a422600f492480bfa42cbee50a5c7016f | https://github.com/rackerlabs/python-lunrclient/blob/f26a450a422600f492480bfa42cbee50a5c7016f/lunrclient/storage.py#L123-L130 | train | 58,237 |
ponty/confduino | confduino/boardlist.py | boards | def boards(hwpack='arduino'):
"""read boards from boards.txt.
:param core_package: 'all,'arduino',..
"""
bunch = read_properties(boards_txt(hwpack))
bunch_items = list(bunch.items())
# remove invalid boards
for bid, board in bunch_items:
if 'build' not in board.keys() or 'name' n... | python | def boards(hwpack='arduino'):
"""read boards from boards.txt.
:param core_package: 'all,'arduino',..
"""
bunch = read_properties(boards_txt(hwpack))
bunch_items = list(bunch.items())
# remove invalid boards
for bid, board in bunch_items:
if 'build' not in board.keys() or 'name' n... | [
"def",
"boards",
"(",
"hwpack",
"=",
"'arduino'",
")",
":",
"bunch",
"=",
"read_properties",
"(",
"boards_txt",
"(",
"hwpack",
")",
")",
"bunch_items",
"=",
"list",
"(",
"bunch",
".",
"items",
"(",
")",
")",
"# remove invalid boards",
"for",
"bid",
",",
... | read boards from boards.txt.
:param core_package: 'all,'arduino',.. | [
"read",
"boards",
"from",
"boards",
".",
"txt",
"."
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/boardlist.py#L17-L33 | train | 58,238 |
ponty/confduino | confduino/boardlist.py | board_names | def board_names(hwpack='arduino'):
"""return installed board names."""
ls = list(boards(hwpack).keys())
ls.sort()
return ls | python | def board_names(hwpack='arduino'):
"""return installed board names."""
ls = list(boards(hwpack).keys())
ls.sort()
return ls | [
"def",
"board_names",
"(",
"hwpack",
"=",
"'arduino'",
")",
":",
"ls",
"=",
"list",
"(",
"boards",
"(",
"hwpack",
")",
".",
"keys",
"(",
")",
")",
"ls",
".",
"sort",
"(",
")",
"return",
"ls"
] | return installed board names. | [
"return",
"installed",
"board",
"names",
"."
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/boardlist.py#L36-L40 | train | 58,239 |
ponty/confduino | confduino/boardlist.py | print_boards | def print_boards(hwpack='arduino', verbose=False):
"""print boards from boards.txt."""
if verbose:
pp(boards(hwpack))
else:
print('\n'.join(board_names(hwpack))) | python | def print_boards(hwpack='arduino', verbose=False):
"""print boards from boards.txt."""
if verbose:
pp(boards(hwpack))
else:
print('\n'.join(board_names(hwpack))) | [
"def",
"print_boards",
"(",
"hwpack",
"=",
"'arduino'",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"pp",
"(",
"boards",
"(",
"hwpack",
")",
")",
"else",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"board_names",
"(",
"hwpack",
")... | print boards from boards.txt. | [
"print",
"boards",
"from",
"boards",
".",
"txt",
"."
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/boardlist.py#L44-L49 | train | 58,240 |
ponty/confduino | confduino/libinstall.py | find_lib_dir | def find_lib_dir(root):
"""search for lib dir under root."""
root = path(root)
log.debug('files in dir: %s', root)
for x in root.walkfiles():
log.debug(' %s', x)
# only 1 dir in root? (example: github)
if not len(root.files()) and len(root.dirs()) == 1:
log.debug('go inside roo... | python | def find_lib_dir(root):
"""search for lib dir under root."""
root = path(root)
log.debug('files in dir: %s', root)
for x in root.walkfiles():
log.debug(' %s', x)
# only 1 dir in root? (example: github)
if not len(root.files()) and len(root.dirs()) == 1:
log.debug('go inside roo... | [
"def",
"find_lib_dir",
"(",
"root",
")",
":",
"root",
"=",
"path",
"(",
"root",
")",
"log",
".",
"debug",
"(",
"'files in dir: %s'",
",",
"root",
")",
"for",
"x",
"in",
"root",
".",
"walkfiles",
"(",
")",
":",
"log",
".",
"debug",
"(",
"' %s'",
",... | search for lib dir under root. | [
"search",
"for",
"lib",
"dir",
"under",
"root",
"."
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/libinstall.py#L64-L119 | train | 58,241 |
ponty/confduino | confduino/libinstall.py | move_examples | def move_examples(root, lib_dir):
"""find examples not under lib dir, and move into ``examples``"""
all_pde = files_multi_pattern(root, INO_PATTERNS)
lib_pde = files_multi_pattern(lib_dir, INO_PATTERNS)
stray_pde = all_pde.difference(lib_pde)
if len(stray_pde) and not len(lib_pde):
log.debug... | python | def move_examples(root, lib_dir):
"""find examples not under lib dir, and move into ``examples``"""
all_pde = files_multi_pattern(root, INO_PATTERNS)
lib_pde = files_multi_pattern(lib_dir, INO_PATTERNS)
stray_pde = all_pde.difference(lib_pde)
if len(stray_pde) and not len(lib_pde):
log.debug... | [
"def",
"move_examples",
"(",
"root",
",",
"lib_dir",
")",
":",
"all_pde",
"=",
"files_multi_pattern",
"(",
"root",
",",
"INO_PATTERNS",
")",
"lib_pde",
"=",
"files_multi_pattern",
"(",
"lib_dir",
",",
"INO_PATTERNS",
")",
"stray_pde",
"=",
"all_pde",
".",
"dif... | find examples not under lib dir, and move into ``examples`` | [
"find",
"examples",
"not",
"under",
"lib",
"dir",
"and",
"move",
"into",
"examples"
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/libinstall.py#L130-L143 | train | 58,242 |
ponty/confduino | confduino/libinstall.py | fix_examples_dir | def fix_examples_dir(lib_dir):
"""rename examples dir to ``examples``"""
for x in lib_dir.dirs():
if x.name.lower() == EXAMPLES:
return
for x in lib_dir.dirs():
if x.name.lower() == EXAMPLES:
_fix_dir(x)
return
for x in lib_dir.dirs():
if 'exam... | python | def fix_examples_dir(lib_dir):
"""rename examples dir to ``examples``"""
for x in lib_dir.dirs():
if x.name.lower() == EXAMPLES:
return
for x in lib_dir.dirs():
if x.name.lower() == EXAMPLES:
_fix_dir(x)
return
for x in lib_dir.dirs():
if 'exam... | [
"def",
"fix_examples_dir",
"(",
"lib_dir",
")",
":",
"for",
"x",
"in",
"lib_dir",
".",
"dirs",
"(",
")",
":",
"if",
"x",
".",
"name",
".",
"lower",
"(",
")",
"==",
"EXAMPLES",
":",
"return",
"for",
"x",
"in",
"lib_dir",
".",
"dirs",
"(",
")",
":"... | rename examples dir to ``examples`` | [
"rename",
"examples",
"dir",
"to",
"examples"
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/libinstall.py#L152-L168 | train | 58,243 |
ponty/confduino | confduino/libinstall.py | install_lib | def install_lib(url, replace_existing=False, fix_wprogram=True):
"""install library from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None
"""
d = tmpdir(tmpdir())
f = download(url)
Archive(f).extractall(d)
clean_dir(d)
... | python | def install_lib(url, replace_existing=False, fix_wprogram=True):
"""install library from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None
"""
d = tmpdir(tmpdir())
f = download(url)
Archive(f).extractall(d)
clean_dir(d)
... | [
"def",
"install_lib",
"(",
"url",
",",
"replace_existing",
"=",
"False",
",",
"fix_wprogram",
"=",
"True",
")",
":",
"d",
"=",
"tmpdir",
"(",
"tmpdir",
"(",
")",
")",
"f",
"=",
"download",
"(",
"url",
")",
"Archive",
"(",
"f",
")",
".",
"extractall",... | install library from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None | [
"install",
"library",
"from",
"web",
"or",
"local",
"files",
"system",
"."
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/libinstall.py#L229-L263 | train | 58,244 |
yougov/vr.common | vr/common/models.py | Host._init_supervisor_rpc | def _init_supervisor_rpc(self, rpc_or_port):
'''Initialize supervisor RPC.
Allow passing in an RPC connection, or a port number for
making one.
'''
if isinstance(rpc_or_port, int):
if self.username:
leader = 'http://{self.username}:{self.password}@'
... | python | def _init_supervisor_rpc(self, rpc_or_port):
'''Initialize supervisor RPC.
Allow passing in an RPC connection, or a port number for
making one.
'''
if isinstance(rpc_or_port, int):
if self.username:
leader = 'http://{self.username}:{self.password}@'
... | [
"def",
"_init_supervisor_rpc",
"(",
"self",
",",
"rpc_or_port",
")",
":",
"if",
"isinstance",
"(",
"rpc_or_port",
",",
"int",
")",
":",
"if",
"self",
".",
"username",
":",
"leader",
"=",
"'http://{self.username}:{self.password}@'",
"else",
":",
"leader",
"=",
... | Initialize supervisor RPC.
Allow passing in an RPC connection, or a port number for
making one. | [
"Initialize",
"supervisor",
"RPC",
"."
] | ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4 | https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L113-L131 | train | 58,245 |
yougov/vr.common | vr/common/models.py | Host._init_redis | def _init_redis(redis_spec):
"""
Return a StrictRedis instance or None based on redis_spec.
redis_spec may be None, a Redis URL, or a StrictRedis instance
"""
if not redis_spec:
return
if isinstance(redis_spec, six.string_types):
return redis.Stri... | python | def _init_redis(redis_spec):
"""
Return a StrictRedis instance or None based on redis_spec.
redis_spec may be None, a Redis URL, or a StrictRedis instance
"""
if not redis_spec:
return
if isinstance(redis_spec, six.string_types):
return redis.Stri... | [
"def",
"_init_redis",
"(",
"redis_spec",
")",
":",
"if",
"not",
"redis_spec",
":",
"return",
"if",
"isinstance",
"(",
"redis_spec",
",",
"six",
".",
"string_types",
")",
":",
"return",
"redis",
".",
"StrictRedis",
".",
"from_url",
"(",
"redis_spec",
")",
"... | Return a StrictRedis instance or None based on redis_spec.
redis_spec may be None, a Redis URL, or a StrictRedis instance | [
"Return",
"a",
"StrictRedis",
"instance",
"or",
"None",
"based",
"on",
"redis_spec",
"."
] | ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4 | https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L134-L145 | train | 58,246 |
yougov/vr.common | vr/common/models.py | Velociraptor._get_base | def _get_base():
"""
if 'deploy' resolves in this environment, use the hostname for which
that name resolves.
Override with 'VELOCIRAPTOR_URL'
"""
try:
name, _aliaslist, _addresslist = socket.gethostbyname_ex('deploy')
except socket.gaierror:
... | python | def _get_base():
"""
if 'deploy' resolves in this environment, use the hostname for which
that name resolves.
Override with 'VELOCIRAPTOR_URL'
"""
try:
name, _aliaslist, _addresslist = socket.gethostbyname_ex('deploy')
except socket.gaierror:
... | [
"def",
"_get_base",
"(",
")",
":",
"try",
":",
"name",
",",
"_aliaslist",
",",
"_addresslist",
"=",
"socket",
".",
"gethostbyname_ex",
"(",
"'deploy'",
")",
"except",
"socket",
".",
"gaierror",
":",
"name",
"=",
"'deploy'",
"fallback",
"=",
"'https://{name}/... | if 'deploy' resolves in this environment, use the hostname for which
that name resolves.
Override with 'VELOCIRAPTOR_URL' | [
"if",
"deploy",
"resolves",
"in",
"this",
"environment",
"use",
"the",
"hostname",
"for",
"which",
"that",
"name",
"resolves",
".",
"Override",
"with",
"VELOCIRAPTOR_URL"
] | ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4 | https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L574-L585 | train | 58,247 |
yougov/vr.common | vr/common/models.py | BaseResource.load_all | def load_all(cls, vr, params=None):
"""
Create instances of all objects found
"""
ob_docs = vr.query(cls.base, params)
return [cls(vr, ob) for ob in ob_docs] | python | def load_all(cls, vr, params=None):
"""
Create instances of all objects found
"""
ob_docs = vr.query(cls.base, params)
return [cls(vr, ob) for ob in ob_docs] | [
"def",
"load_all",
"(",
"cls",
",",
"vr",
",",
"params",
"=",
"None",
")",
":",
"ob_docs",
"=",
"vr",
".",
"query",
"(",
"cls",
".",
"base",
",",
"params",
")",
"return",
"[",
"cls",
"(",
"vr",
",",
"ob",
")",
"for",
"ob",
"in",
"ob_docs",
"]"
... | Create instances of all objects found | [
"Create",
"instances",
"of",
"all",
"objects",
"found"
] | ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4 | https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L689-L694 | train | 58,248 |
yougov/vr.common | vr/common/models.py | Swarm.dispatch | def dispatch(self, **changes):
"""
Patch the swarm with changes and then trigger the swarm.
"""
self.patch(**changes)
trigger_url = self._vr._build_url(self.resource_uri, 'swarm/')
resp = self._vr.session.post(trigger_url)
resp.raise_for_status()
try:
... | python | def dispatch(self, **changes):
"""
Patch the swarm with changes and then trigger the swarm.
"""
self.patch(**changes)
trigger_url = self._vr._build_url(self.resource_uri, 'swarm/')
resp = self._vr.session.post(trigger_url)
resp.raise_for_status()
try:
... | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"*",
"changes",
")",
":",
"self",
".",
"patch",
"(",
"*",
"*",
"changes",
")",
"trigger_url",
"=",
"self",
".",
"_vr",
".",
"_build_url",
"(",
"self",
".",
"resource_uri",
",",
"'swarm/'",
")",
"resp",
"=",
... | Patch the swarm with changes and then trigger the swarm. | [
"Patch",
"the",
"swarm",
"with",
"changes",
"and",
"then",
"trigger",
"the",
"swarm",
"."
] | ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4 | https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L738-L749 | train | 58,249 |
yougov/vr.common | vr/common/models.py | Build.assemble | def assemble(self):
"""
Assemble a build
"""
if not self.created:
self.create()
# trigger the build
url = self._vr._build_url(self.resource_uri, 'build/')
resp = self._vr.session.post(url)
resp.raise_for_status() | python | def assemble(self):
"""
Assemble a build
"""
if not self.created:
self.create()
# trigger the build
url = self._vr._build_url(self.resource_uri, 'build/')
resp = self._vr.session.post(url)
resp.raise_for_status() | [
"def",
"assemble",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"created",
":",
"self",
".",
"create",
"(",
")",
"# trigger the build",
"url",
"=",
"self",
".",
"_vr",
".",
"_build_url",
"(",
"self",
".",
"resource_uri",
",",
"'build/'",
")",
"resp... | Assemble a build | [
"Assemble",
"a",
"build"
] | ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4 | https://github.com/yougov/vr.common/blob/ca8ed0c50ba873fc51fdfeeaa25d3b8ec1b54eb4/vr/common/models.py#L782-L791 | train | 58,250 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Connection._get_token | def _get_token(self):
'''
requests an communication token from Grooveshark
'''
self.session.token = self.request(
'getCommunicationToken',
{'secretKey': self.session.secret},
{'uuid': self.session.user,
'session': self.session.session,
... | python | def _get_token(self):
'''
requests an communication token from Grooveshark
'''
self.session.token = self.request(
'getCommunicationToken',
{'secretKey': self.session.secret},
{'uuid': self.session.user,
'session': self.session.session,
... | [
"def",
"_get_token",
"(",
"self",
")",
":",
"self",
".",
"session",
".",
"token",
"=",
"self",
".",
"request",
"(",
"'getCommunicationToken'",
",",
"{",
"'secretKey'",
":",
"self",
".",
"session",
".",
"secret",
"}",
",",
"{",
"'uuid'",
":",
"self",
".... | requests an communication token from Grooveshark | [
"requests",
"an",
"communication",
"token",
"from",
"Grooveshark"
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L100-L113 | train | 58,251 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Connection._request_token | def _request_token(self, method, client):
'''
generates a request token
'''
if time.time() - self.session.time > grooveshark.const.TOKEN_TIMEOUT:
self._get_token()
random_value = self._random_hex()
return random_value + hashlib.sha1((method + ':' + self.sessio... | python | def _request_token(self, method, client):
'''
generates a request token
'''
if time.time() - self.session.time > grooveshark.const.TOKEN_TIMEOUT:
self._get_token()
random_value = self._random_hex()
return random_value + hashlib.sha1((method + ':' + self.sessio... | [
"def",
"_request_token",
"(",
"self",
",",
"method",
",",
"client",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"session",
".",
"time",
">",
"grooveshark",
".",
"const",
".",
"TOKEN_TIMEOUT",
":",
"self",
".",
"_get_token",
"(",
... | generates a request token | [
"generates",
"a",
"request",
"token"
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L115-L122 | train | 58,252 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Connection.request | def request(self, method, parameters, header):
'''
Grooveshark API request
'''
data = json.dumps({
'parameters': parameters,
'method': method,
'header': header})
request = urllib.Request(
'https://grooveshark.com/more.php?%s' % (met... | python | def request(self, method, parameters, header):
'''
Grooveshark API request
'''
data = json.dumps({
'parameters': parameters,
'method': method,
'header': header})
request = urllib.Request(
'https://grooveshark.com/more.php?%s' % (met... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"parameters",
",",
"header",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'parameters'",
":",
"parameters",
",",
"'method'",
":",
"method",
",",
"'header'",
":",
"header",
"}",
")",
"request... | Grooveshark API request | [
"Grooveshark",
"API",
"request"
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L145-L164 | train | 58,253 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Connection.header | def header(self, method, client='htmlshark'):
'''
generates Grooveshark API Json header
'''
return {'token': self._request_token(method, client),
'privacy': 0,
'uuid': self.session.user,
'clientRevision': grooveshark.const.CLIENTS[client]['... | python | def header(self, method, client='htmlshark'):
'''
generates Grooveshark API Json header
'''
return {'token': self._request_token(method, client),
'privacy': 0,
'uuid': self.session.user,
'clientRevision': grooveshark.const.CLIENTS[client]['... | [
"def",
"header",
"(",
"self",
",",
"method",
",",
"client",
"=",
"'htmlshark'",
")",
":",
"return",
"{",
"'token'",
":",
"self",
".",
"_request_token",
"(",
"method",
",",
"client",
")",
",",
"'privacy'",
":",
"0",
",",
"'uuid'",
":",
"self",
".",
"s... | generates Grooveshark API Json header | [
"generates",
"Grooveshark",
"API",
"Json",
"header"
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L166-L176 | train | 58,254 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Client.radio | def radio(self, radio):
'''
Get songs belong to a specific genre.
:param radio: genre to listen to
:rtype: a :class:`Radio` object
Genres:
This list is incomplete because there isn't an English translation for
some genres.
Please look at the sources for... | python | def radio(self, radio):
'''
Get songs belong to a specific genre.
:param radio: genre to listen to
:rtype: a :class:`Radio` object
Genres:
This list is incomplete because there isn't an English translation for
some genres.
Please look at the sources for... | [
"def",
"radio",
"(",
"self",
",",
"radio",
")",
":",
"artists",
"=",
"self",
".",
"connection",
".",
"request",
"(",
"'getArtistsForTagRadio'",
",",
"{",
"'tagID'",
":",
"radio",
"}",
",",
"self",
".",
"connection",
".",
"header",
"(",
"'getArtistsForTagRa... | Get songs belong to a specific genre.
:param radio: genre to listen to
:rtype: a :class:`Radio` object
Genres:
This list is incomplete because there isn't an English translation for
some genres.
Please look at the sources for all possible Tags.
+--------------... | [
"Get",
"songs",
"belong",
"to",
"a",
"specific",
"genre",
"."
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L223-L284 | train | 58,255 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Client.search | def search(self, query, type=SONGS):
'''
Search for songs, artists and albums.
:param query: search string
:param type: type to search for
:rtype: a generator generates :class:`Song`, :class:`Artist` and :class:`Album` objects
Search Types:
+-------------------... | python | def search(self, query, type=SONGS):
'''
Search for songs, artists and albums.
:param query: search string
:param type: type to search for
:rtype: a generator generates :class:`Song`, :class:`Artist` and :class:`Album` objects
Search Types:
+-------------------... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"type",
"=",
"SONGS",
")",
":",
"result",
"=",
"self",
".",
"connection",
".",
"request",
"(",
"'getResultsFromSearch'",
",",
"{",
"'query'",
":",
"query",
",",
"'type'",
":",
"type",
",",
"'guts'",
":",... | Search for songs, artists and albums.
:param query: search string
:param type: type to search for
:rtype: a generator generates :class:`Song`, :class:`Artist` and :class:`Album` objects
Search Types:
+---------------------------------+---------------------------------+
... | [
"Search",
"for",
"songs",
"artists",
"and",
"albums",
"."
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L318-L353 | train | 58,256 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Client.popular | def popular(self, period=DAILY):
'''
Get popular songs.
:param period: time period
:rtype: a generator generates :class:`Song` objects
Time periods:
+---------------------------------+-----------------------------------+
| Constant | Mean... | python | def popular(self, period=DAILY):
'''
Get popular songs.
:param period: time period
:rtype: a generator generates :class:`Song` objects
Time periods:
+---------------------------------+-----------------------------------+
| Constant | Mean... | [
"def",
"popular",
"(",
"self",
",",
"period",
"=",
"DAILY",
")",
":",
"songs",
"=",
"self",
".",
"connection",
".",
"request",
"(",
"'popularGetSongs'",
",",
"{",
"'type'",
":",
"period",
"}",
",",
"self",
".",
"connection",
".",
"header",
"(",
"'popul... | Get popular songs.
:param period: time period
:rtype: a generator generates :class:`Song` objects
Time periods:
+---------------------------------+-----------------------------------+
| Constant | Meaning |
+============... | [
"Get",
"popular",
"songs",
"."
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L355-L376 | train | 58,257 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Client.playlist | def playlist(self, playlist_id):
'''
Get a playlist from it's ID
:param playlist_id: ID of the playlist
:rtype: a :class:`Playlist` object
'''
playlist = self.connection.request(
'getPlaylistByID',
{'playlistID': playlist_id},
self.con... | python | def playlist(self, playlist_id):
'''
Get a playlist from it's ID
:param playlist_id: ID of the playlist
:rtype: a :class:`Playlist` object
'''
playlist = self.connection.request(
'getPlaylistByID',
{'playlistID': playlist_id},
self.con... | [
"def",
"playlist",
"(",
"self",
",",
"playlist_id",
")",
":",
"playlist",
"=",
"self",
".",
"connection",
".",
"request",
"(",
"'getPlaylistByID'",
",",
"{",
"'playlistID'",
":",
"playlist_id",
"}",
",",
"self",
".",
"connection",
".",
"header",
"(",
"'get... | Get a playlist from it's ID
:param playlist_id: ID of the playlist
:rtype: a :class:`Playlist` object | [
"Get",
"a",
"playlist",
"from",
"it",
"s",
"ID"
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L378-L389 | train | 58,258 |
koehlma/pygrooveshark | src/grooveshark/__init__.py | Client.collection | def collection(self, user_id):
"""
Get the song collection of a user.
:param user_id: ID of a user.
:rtype: list of :class:`Song`
"""
# TODO further evaluation of the page param, I don't know where the
# limit is.
dct = {'userID': user_id, 'page': 0}
... | python | def collection(self, user_id):
"""
Get the song collection of a user.
:param user_id: ID of a user.
:rtype: list of :class:`Song`
"""
# TODO further evaluation of the page param, I don't know where the
# limit is.
dct = {'userID': user_id, 'page': 0}
... | [
"def",
"collection",
"(",
"self",
",",
"user_id",
")",
":",
"# TODO further evaluation of the page param, I don't know where the",
"# limit is.",
"dct",
"=",
"{",
"'userID'",
":",
"user_id",
",",
"'page'",
":",
"0",
"}",
"r",
"=",
"'userGetSongsInLibrary'",
"result",
... | Get the song collection of a user.
:param user_id: ID of a user.
:rtype: list of :class:`Song` | [
"Get",
"the",
"song",
"collection",
"of",
"a",
"user",
"."
] | 17673758ac12f54dc26ac879c30ea44f13b81057 | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/__init__.py#L391-L404 | train | 58,259 |
ponty/confduino | confduino/hwpacklist.py | hwpack_names | def hwpack_names():
"""return installed hardware package names."""
ls = hwpack_dir().listdir()
ls = [x.name for x in ls]
ls = [x for x in ls if x != 'tools']
arduino_included = 'arduino' in ls
ls = [x for x in ls if x != 'arduino']
ls.sort()
if arduino_included:
ls = ['arduino'] ... | python | def hwpack_names():
"""return installed hardware package names."""
ls = hwpack_dir().listdir()
ls = [x.name for x in ls]
ls = [x for x in ls if x != 'tools']
arduino_included = 'arduino' in ls
ls = [x for x in ls if x != 'arduino']
ls.sort()
if arduino_included:
ls = ['arduino'] ... | [
"def",
"hwpack_names",
"(",
")",
":",
"ls",
"=",
"hwpack_dir",
"(",
")",
".",
"listdir",
"(",
")",
"ls",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"ls",
"]",
"ls",
"=",
"[",
"x",
"for",
"x",
"in",
"ls",
"if",
"x",
"!=",
"'tools'",
"]",
... | return installed hardware package names. | [
"return",
"installed",
"hardware",
"package",
"names",
"."
] | f4c261e5e84997f145a8bdd001f471db74c9054b | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/hwpacklist.py#L93-L103 | train | 58,260 |
hatemile/hatemile-for-python | hatemile/util/css/tinycss/tinycssparser.py | TinyCSSParser._create_parser | def _create_parser(self, html_parser, current_url):
"""
Create the tinycss stylesheet.
:param html_parser: The HTML parser.
:type html_parser: hatemile.util.html.htmldomparser.HTMLDOMParser
:param current_url: The current URL of page.
:type current_url: str
"""
... | python | def _create_parser(self, html_parser, current_url):
"""
Create the tinycss stylesheet.
:param html_parser: The HTML parser.
:type html_parser: hatemile.util.html.htmldomparser.HTMLDOMParser
:param current_url: The current URL of page.
:type current_url: str
"""
... | [
"def",
"_create_parser",
"(",
"self",
",",
"html_parser",
",",
"current_url",
")",
":",
"css_code",
"=",
"''",
"elements",
"=",
"html_parser",
".",
"find",
"(",
"'style,link[rel=\"stylesheet\"]'",
")",
".",
"list_results",
"(",
")",
"for",
"element",
"in",
"el... | Create the tinycss stylesheet.
:param html_parser: The HTML parser.
:type html_parser: hatemile.util.html.htmldomparser.HTMLDOMParser
:param current_url: The current URL of page.
:type current_url: str | [
"Create",
"the",
"tinycss",
"stylesheet",
"."
] | 1e914f9aa09f6f8d78282af131311546ecba9fb8 | https://github.com/hatemile/hatemile-for-python/blob/1e914f9aa09f6f8d78282af131311546ecba9fb8/hatemile/util/css/tinycss/tinycssparser.py#L53-L76 | train | 58,261 |
SeattleTestbed/seash | pyreadline/modes/notemacs.py | NotEmacsMode.readline | def readline(self, prompt=''):
u'''Try to act like GNU readline.'''
# handle startup_hook
if self.first_prompt:
self.first_prompt = False
if self.startup_hook:
try:
self.startup_hook()
except:
... | python | def readline(self, prompt=''):
u'''Try to act like GNU readline.'''
# handle startup_hook
if self.first_prompt:
self.first_prompt = False
if self.startup_hook:
try:
self.startup_hook()
except:
... | [
"def",
"readline",
"(",
"self",
",",
"prompt",
"=",
"''",
")",
":",
"# handle startup_hook\r",
"if",
"self",
".",
"first_prompt",
":",
"self",
".",
"first_prompt",
"=",
"False",
"if",
"self",
".",
"startup_hook",
":",
"try",
":",
"self",
".",
"startup_hook... | u'''Try to act like GNU readline. | [
"u",
"Try",
"to",
"act",
"like",
"GNU",
"readline",
"."
] | 40f9d2285662ff8b61e0468b4196acee089b273b | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/notemacs.py#L51-L89 | train | 58,262 |
SeattleTestbed/seash | pyreadline/modes/notemacs.py | NotEmacsMode.history_search_backward | def history_search_backward(self, e): # ()
u'''Search backward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound.'''
self.l_buffer=self._history.history_search_ba... | python | def history_search_backward(self, e): # ()
u'''Search backward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound.'''
self.l_buffer=self._history.history_search_ba... | [
"def",
"history_search_backward",
"(",
"self",
",",
"e",
")",
":",
"# ()\r",
"self",
".",
"l_buffer",
"=",
"self",
".",
"_history",
".",
"history_search_backward",
"(",
"self",
".",
"l_buffer",
")"
] | u'''Search backward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search. By default, this command is unbound. | [
"u",
"Search",
"backward",
"through",
"the",
"history",
"for",
"the",
"string",
"of",
"characters",
"between",
"the",
"start",
"of",
"the",
"current",
"line",
"and",
"the",
"point",
".",
"This",
"is",
"a",
"non",
"-",
"incremental",
"search",
".",
"By",
... | 40f9d2285662ff8b61e0468b4196acee089b273b | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/notemacs.py#L229-L233 | train | 58,263 |
SeattleTestbed/seash | pyreadline/modes/notemacs.py | NotEmacsMode.quoted_insert | def quoted_insert(self, e): # (C-q or C-v)
u'''Add the next character typed to the line verbatim. This is how to
insert key sequences like C-q, for example.'''
e = self.console.getkeypress()
self.insert_text(e.char) | python | def quoted_insert(self, e): # (C-q or C-v)
u'''Add the next character typed to the line verbatim. This is how to
insert key sequences like C-q, for example.'''
e = self.console.getkeypress()
self.insert_text(e.char) | [
"def",
"quoted_insert",
"(",
"self",
",",
"e",
")",
":",
"# (C-q or C-v)\r",
"e",
"=",
"self",
".",
"console",
".",
"getkeypress",
"(",
")",
"self",
".",
"insert_text",
"(",
"e",
".",
"char",
")"
] | u'''Add the next character typed to the line verbatim. This is how to
insert key sequences like C-q, for example. | [
"u",
"Add",
"the",
"next",
"character",
"typed",
"to",
"the",
"line",
"verbatim",
".",
"This",
"is",
"how",
"to",
"insert",
"key",
"sequences",
"like",
"C",
"-",
"q",
"for",
"example",
"."
] | 40f9d2285662ff8b61e0468b4196acee089b273b | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/notemacs.py#L267-L271 | train | 58,264 |
SeattleTestbed/seash | pyreadline/modes/notemacs.py | NotEmacsMode.ipython_paste | def ipython_paste(self,e):
u'''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
True then try to convert tabseparated data to repr of list of lists or
repr of array'''
if self.enable_win32_clipboard:
txt=clipboard.get_clipboard_text_and_convert(
... | python | def ipython_paste(self,e):
u'''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
True then try to convert tabseparated data to repr of list of lists or
repr of array'''
if self.enable_win32_clipboard:
txt=clipboard.get_clipboard_text_and_convert(
... | [
"def",
"ipython_paste",
"(",
"self",
",",
"e",
")",
":",
"if",
"self",
".",
"enable_win32_clipboard",
":",
"txt",
"=",
"clipboard",
".",
"get_clipboard_text_and_convert",
"(",
"self",
".",
"enable_ipython_paste_list_of_lists",
")",
"if",
"self",
".",
"enable_ipyth... | u'''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
True then try to convert tabseparated data to repr of list of lists or
repr of array | [
"u",
"Paste",
"windows",
"clipboard",
".",
"If",
"enable_ipython_paste_list_of_lists",
"is",
"True",
"then",
"try",
"to",
"convert",
"tabseparated",
"data",
"to",
"repr",
"of",
"list",
"of",
"lists",
"or",
"repr",
"of",
"array"
] | 40f9d2285662ff8b61e0468b4196acee089b273b | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/modes/notemacs.py#L416-L426 | train | 58,265 |
corydodt/Codado | codado/tx.py | Main.main | def main(cls, args=None):
"""
Fill in command-line arguments from argv
"""
if args is None:
args = sys.argv[1:]
try:
o = cls()
o.parseOptions(args)
except usage.UsageError as e:
print(o.getSynopsis())
print(o.ge... | python | def main(cls, args=None):
"""
Fill in command-line arguments from argv
"""
if args is None:
args = sys.argv[1:]
try:
o = cls()
o.parseOptions(args)
except usage.UsageError as e:
print(o.getSynopsis())
print(o.ge... | [
"def",
"main",
"(",
"cls",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"try",
":",
"o",
"=",
"cls",
"(",
")",
"o",
".",
"parseOptions",
"(",
"args",
")",
"except",
... | Fill in command-line arguments from argv | [
"Fill",
"in",
"command",
"-",
"line",
"arguments",
"from",
"argv"
] | 487d51ec6132c05aa88e2f128012c95ccbf6928e | https://github.com/corydodt/Codado/blob/487d51ec6132c05aa88e2f128012c95ccbf6928e/codado/tx.py#L38-L57 | train | 58,266 |
RI-imaging/qpformat | qpformat/file_formats/series_zip_tif_phasics.py | SeriesZipTifPhasics._index_files | def _index_files(path):
"""Search zip file for SID PHA files"""
with zipfile.ZipFile(path) as zf:
names = sorted(zf.namelist())
names = [nn for nn in names if nn.endswith(".tif")]
names = [nn for nn in names if nn.startswith("SID PHA")]
phasefiles = []
... | python | def _index_files(path):
"""Search zip file for SID PHA files"""
with zipfile.ZipFile(path) as zf:
names = sorted(zf.namelist())
names = [nn for nn in names if nn.endswith(".tif")]
names = [nn for nn in names if nn.startswith("SID PHA")]
phasefiles = []
... | [
"def",
"_index_files",
"(",
"path",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"zf",
":",
"names",
"=",
"sorted",
"(",
"zf",
".",
"namelist",
"(",
")",
")",
"names",
"=",
"[",
"nn",
"for",
"nn",
"in",
"names",
"if",
"nn"... | Search zip file for SID PHA files | [
"Search",
"zip",
"file",
"for",
"SID",
"PHA",
"files"
] | 364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb | https://github.com/RI-imaging/qpformat/blob/364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb/qpformat/file_formats/series_zip_tif_phasics.py#L40-L52 | train | 58,267 |
RI-imaging/qpformat | qpformat/file_formats/series_zip_tif_phasics.py | SeriesZipTifPhasics.files | def files(self):
"""List of Phasics tif file names in the input zip file"""
if self._files is None:
self._files = SeriesZipTifPhasics._index_files(self.path)
return self._files | python | def files(self):
"""List of Phasics tif file names in the input zip file"""
if self._files is None:
self._files = SeriesZipTifPhasics._index_files(self.path)
return self._files | [
"def",
"files",
"(",
"self",
")",
":",
"if",
"self",
".",
"_files",
"is",
"None",
":",
"self",
".",
"_files",
"=",
"SeriesZipTifPhasics",
".",
"_index_files",
"(",
"self",
".",
"path",
")",
"return",
"self",
".",
"_files"
] | List of Phasics tif file names in the input zip file | [
"List",
"of",
"Phasics",
"tif",
"file",
"names",
"in",
"the",
"input",
"zip",
"file"
] | 364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb | https://github.com/RI-imaging/qpformat/blob/364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb/qpformat/file_formats/series_zip_tif_phasics.py#L55-L59 | train | 58,268 |
RI-imaging/qpformat | qpformat/file_formats/series_zip_tif_phasics.py | SeriesZipTifPhasics.verify | def verify(path):
"""Verify that `path` is a zip file with Phasics TIFF files"""
valid = False
try:
zf = zipfile.ZipFile(path)
except (zipfile.BadZipfile, IsADirectoryError):
pass
else:
names = sorted(zf.namelist())
names = [nn for ... | python | def verify(path):
"""Verify that `path` is a zip file with Phasics TIFF files"""
valid = False
try:
zf = zipfile.ZipFile(path)
except (zipfile.BadZipfile, IsADirectoryError):
pass
else:
names = sorted(zf.namelist())
names = [nn for ... | [
"def",
"verify",
"(",
"path",
")",
":",
"valid",
"=",
"False",
"try",
":",
"zf",
"=",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"except",
"(",
"zipfile",
".",
"BadZipfile",
",",
"IsADirectoryError",
")",
":",
"pass",
"else",
":",
"names",
"=",
"so... | Verify that `path` is a zip file with Phasics TIFF files | [
"Verify",
"that",
"path",
"is",
"a",
"zip",
"file",
"with",
"Phasics",
"TIFF",
"files"
] | 364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb | https://github.com/RI-imaging/qpformat/blob/364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb/qpformat/file_formats/series_zip_tif_phasics.py#L74-L92 | train | 58,269 |
metagriffin/asset | asset/resource.py | chunks | def chunks(stream, size=None):
'''
Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
... | python | def chunks(stream, size=None):
'''
Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
... | [
"def",
"chunks",
"(",
"stream",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
"==",
"'lines'",
":",
"for",
"item",
"in",
"stream",
":",
"# for item in stream.readline():",
"yield",
"item",
"return",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"MAXB... | Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
size : int | 'lines'; default: null
... | [
"Returns",
"a",
"generator",
"of",
"chunks",
"from",
"the",
"stream",
"with",
"a",
"maximum",
"size",
"of",
"size",
".",
"I",
"don",
"t",
"know",
"why",
"this",
"isn",
"t",
"part",
"of",
"core",
"Python",
"."
] | f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c | https://github.com/metagriffin/asset/blob/f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c/asset/resource.py#L279-L309 | train | 58,270 |
contains-io/rcli | rcli/log.py | write_logfile | def write_logfile():
# type: () -> None
"""Write a DEBUG log file COMMAND-YYYYMMDD-HHMMSS.ffffff.log."""
command = os.path.basename(os.path.realpath(os.path.abspath(sys.argv[0])))
now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S.%f')
filename = '{}-{}.log'.format(command, now)
with open(fil... | python | def write_logfile():
# type: () -> None
"""Write a DEBUG log file COMMAND-YYYYMMDD-HHMMSS.ffffff.log."""
command = os.path.basename(os.path.realpath(os.path.abspath(sys.argv[0])))
now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S.%f')
filename = '{}-{}.log'.format(command, now)
with open(fil... | [
"def",
"write_logfile",
"(",
")",
":",
"# type: () -> None",
"command",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
")",... | Write a DEBUG log file COMMAND-YYYYMMDD-HHMMSS.ffffff.log. | [
"Write",
"a",
"DEBUG",
"log",
"file",
"COMMAND",
"-",
"YYYYMMDD",
"-",
"HHMMSS",
".",
"ffffff",
".",
"log",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L35-L46 | train | 58,271 |
contains-io/rcli | rcli/log.py | excepthook | def excepthook(type, value, traceback): # pylint: disable=unused-argument
"""Log exceptions instead of printing a traceback to stderr."""
try:
six.reraise(type, value, traceback)
except type:
_LOGGER.exception(str(value))
if isinstance(value, KeyboardInterrupt):
message = "Cance... | python | def excepthook(type, value, traceback): # pylint: disable=unused-argument
"""Log exceptions instead of printing a traceback to stderr."""
try:
six.reraise(type, value, traceback)
except type:
_LOGGER.exception(str(value))
if isinstance(value, KeyboardInterrupt):
message = "Cance... | [
"def",
"excepthook",
"(",
"type",
",",
"value",
",",
"traceback",
")",
":",
"# pylint: disable=unused-argument",
"try",
":",
"six",
".",
"reraise",
"(",
"type",
",",
"value",
",",
"traceback",
")",
"except",
"type",
":",
"_LOGGER",
".",
"exception",
"(",
"... | Log exceptions instead of printing a traceback to stderr. | [
"Log",
"exceptions",
"instead",
"of",
"printing",
"a",
"traceback",
"to",
"stderr",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L56-L66 | train | 58,272 |
contains-io/rcli | rcli/log.py | handle_unexpected_exception | def handle_unexpected_exception(exc):
# type: (BaseException) -> str
"""Return an error message and write a log file if logging was not enabled.
Args:
exc: The unexpected exception.
Returns:
A message to display to the user concerning the unexpected exception.
"""
try:
... | python | def handle_unexpected_exception(exc):
# type: (BaseException) -> str
"""Return an error message and write a log file if logging was not enabled.
Args:
exc: The unexpected exception.
Returns:
A message to display to the user concerning the unexpected exception.
"""
try:
... | [
"def",
"handle_unexpected_exception",
"(",
"exc",
")",
":",
"# type: (BaseException) -> str",
"try",
":",
"write_logfile",
"(",
")",
"addendum",
"=",
"'Please see the log file for more information.'",
"except",
"IOError",
":",
"addendum",
"=",
"'Unable to write log file.'",
... | Return an error message and write a log file if logging was not enabled.
Args:
exc: The unexpected exception.
Returns:
A message to display to the user concerning the unexpected exception. | [
"Return",
"an",
"error",
"message",
"and",
"write",
"a",
"log",
"file",
"if",
"logging",
"was",
"not",
"enabled",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L70-L89 | train | 58,273 |
contains-io/rcli | rcli/log.py | enable_logging | def enable_logging(log_level):
# type: (typing.Union[None, int]) -> None
"""Configure the root logger and a logfile handler.
Args:
log_level: The logging level to set the logger handler.
"""
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
logfile_handler = logg... | python | def enable_logging(log_level):
# type: (typing.Union[None, int]) -> None
"""Configure the root logger and a logfile handler.
Args:
log_level: The logging level to set the logger handler.
"""
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
logfile_handler = logg... | [
"def",
"enable_logging",
"(",
"log_level",
")",
":",
"# type: (typing.Union[None, int]) -> None",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"logfile_handler",
"=",
"logging",
".",
... | Configure the root logger and a logfile handler.
Args:
log_level: The logging level to set the logger handler. | [
"Configure",
"the",
"root",
"logger",
"and",
"a",
"logfile",
"handler",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L92-L112 | train | 58,274 |
contains-io/rcli | rcli/log.py | get_log_level | def get_log_level(args):
# type: (typing.Dict[str, typing.Any]) -> int
"""Get the log level from the CLI arguments.
Removes logging arguments from sys.argv.
Args:
args: The parsed docopt arguments to be used to determine the logging
level.
Returns:
The correct log leve... | python | def get_log_level(args):
# type: (typing.Dict[str, typing.Any]) -> int
"""Get the log level from the CLI arguments.
Removes logging arguments from sys.argv.
Args:
args: The parsed docopt arguments to be used to determine the logging
level.
Returns:
The correct log leve... | [
"def",
"get_log_level",
"(",
"args",
")",
":",
"# type: (typing.Dict[str, typing.Any]) -> int",
"index",
"=",
"-",
"1",
"log_level",
"=",
"None",
"if",
"'<command>'",
"in",
"args",
"and",
"args",
"[",
"'<command>'",
"]",
":",
"index",
"=",
"sys",
".",
"argv",
... | Get the log level from the CLI arguments.
Removes logging arguments from sys.argv.
Args:
args: The parsed docopt arguments to be used to determine the logging
level.
Returns:
The correct log level based on the three CLI arguments given.
Raises:
ValueError: Raised ... | [
"Get",
"the",
"log",
"level",
"from",
"the",
"CLI",
"arguments",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L115-L154 | train | 58,275 |
contains-io/rcli | rcli/log.py | _logfile_sigterm_handler | def _logfile_sigterm_handler(*_):
# type: (...) -> None
"""Handle exit signals and write out a log file.
Raises:
SystemExit: Contains the signal as the return code.
"""
logging.error('Received SIGTERM.')
write_logfile()
print('Received signal. Please see the log file for more inform... | python | def _logfile_sigterm_handler(*_):
# type: (...) -> None
"""Handle exit signals and write out a log file.
Raises:
SystemExit: Contains the signal as the return code.
"""
logging.error('Received SIGTERM.')
write_logfile()
print('Received signal. Please see the log file for more inform... | [
"def",
"_logfile_sigterm_handler",
"(",
"*",
"_",
")",
":",
"# type: (...) -> None",
"logging",
".",
"error",
"(",
"'Received SIGTERM.'",
")",
"write_logfile",
"(",
")",
"print",
"(",
"'Received signal. Please see the log file for more information.'",
",",
"file",
"=",
... | Handle exit signals and write out a log file.
Raises:
SystemExit: Contains the signal as the return code. | [
"Handle",
"exit",
"signals",
"and",
"write",
"out",
"a",
"log",
"file",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L157-L168 | train | 58,276 |
contains-io/rcli | rcli/log.py | _LogColorFormatter.format | def format(self, record):
# type: (logging.LogRecord) -> str
"""Format the log record with timestamps and level based colors.
Args:
record: The log record to format.
Returns:
The formatted log record.
"""
if record.levelno >= logging.ERROR:
... | python | def format(self, record):
# type: (logging.LogRecord) -> str
"""Format the log record with timestamps and level based colors.
Args:
record: The log record to format.
Returns:
The formatted log record.
"""
if record.levelno >= logging.ERROR:
... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"# type: (logging.LogRecord) -> str",
"if",
"record",
".",
"levelno",
">=",
"logging",
".",
"ERROR",
":",
"color",
"=",
"colorama",
".",
"Fore",
".",
"RED",
"elif",
"record",
".",
"levelno",
">=",
"log... | Format the log record with timestamps and level based colors.
Args:
record: The log record to format.
Returns:
The formatted log record. | [
"Format",
"the",
"log",
"record",
"with",
"timestamps",
"and",
"level",
"based",
"colors",
"."
] | cdd6191a0e0a19bc767f84921650835d099349cf | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/log.py#L174-L205 | train | 58,277 |
sherlocke/pywatson | pywatson/watson.py | Watson.ask_question | def ask_question(self, question_text, question=None):
"""Ask Watson a question via the Question and Answer API
:param question_text: question to ask Watson
:type question_text: str
:param question: if question_text is not provided, a Question object
representing... | python | def ask_question(self, question_text, question=None):
"""Ask Watson a question via the Question and Answer API
:param question_text: question to ask Watson
:type question_text: str
:param question: if question_text is not provided, a Question object
representing... | [
"def",
"ask_question",
"(",
"self",
",",
"question_text",
",",
"question",
"=",
"None",
")",
":",
"if",
"question",
"is",
"not",
"None",
":",
"q",
"=",
"question",
".",
"to_dict",
"(",
")",
"else",
":",
"q",
"=",
"WatsonQuestion",
"(",
"question_text",
... | Ask Watson a question via the Question and Answer API
:param question_text: question to ask Watson
:type question_text: str
:param question: if question_text is not provided, a Question object
representing the question to ask Watson
:type question: WatsonQuestio... | [
"Ask",
"Watson",
"a",
"question",
"via",
"the",
"Question",
"and",
"Answer",
"API"
] | ab15d1ca3c01a185136b420d443f712dfa865485 | https://github.com/sherlocke/pywatson/blob/ab15d1ca3c01a185136b420d443f712dfa865485/pywatson/watson.py#L14-L36 | train | 58,278 |
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/process_queue.py | process_queue | def process_queue(queue=None, **kwargs):
"""Loops and waits on queue calling queue's `next_task` method.
If an exception occurs, log the error, log the exception,
and break.
"""
while True:
item = queue.get()
if item is None:
queue.task_done()
logger.info(f"{... | python | def process_queue(queue=None, **kwargs):
"""Loops and waits on queue calling queue's `next_task` method.
If an exception occurs, log the error, log the exception,
and break.
"""
while True:
item = queue.get()
if item is None:
queue.task_done()
logger.info(f"{... | [
"def",
"process_queue",
"(",
"queue",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"item",
"=",
"queue",
".",
"get",
"(",
")",
"if",
"item",
"is",
"None",
":",
"queue",
".",
"task_done",
"(",
")",
"logger",
".",
"info",
"... | Loops and waits on queue calling queue's `next_task` method.
If an exception occurs, log the error, log the exception,
and break. | [
"Loops",
"and",
"waits",
"on",
"queue",
"calling",
"queue",
"s",
"next_task",
"method",
"."
] | 78f61c823ea3926eb88206b019b5dca3c36017da | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/process_queue.py#L11-L39 | train | 58,279 |
CMUSTRUDEL/strudel.utils | stutils/decorators.py | memoize | def memoize(func):
""" Classic memoize decorator for non-class methods """
cache = {}
@functools.wraps(func)
def wrapper(*args):
key = "__".join(str(arg) for arg in args)
if key not in cache:
cache[key] = func(*args)
return cache[key]
return wrapper | python | def memoize(func):
""" Classic memoize decorator for non-class methods """
cache = {}
@functools.wraps(func)
def wrapper(*args):
key = "__".join(str(arg) for arg in args)
if key not in cache:
cache[key] = func(*args)
return cache[key]
return wrapper | [
"def",
"memoize",
"(",
"func",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"key",
"=",
"\"__\"",
".",
"join",
"(",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",... | Classic memoize decorator for non-class methods | [
"Classic",
"memoize",
"decorator",
"for",
"non",
"-",
"class",
"methods"
] | 888ef72fcdb851b5873092bc9c4d6958733691f2 | https://github.com/CMUSTRUDEL/strudel.utils/blob/888ef72fcdb851b5873092bc9c4d6958733691f2/stutils/decorators.py#L156-L166 | train | 58,280 |
CMUSTRUDEL/strudel.utils | stutils/decorators.py | cached_method | def cached_method(func):
""" Memoize for class methods """
@functools.wraps(func)
def wrapper(self, *args):
if not hasattr(self, "_cache"):
self._cache = {}
key = _argstring((func.__name__,) + args)
if key not in self._cache:
self._cache[key] = func(self, *arg... | python | def cached_method(func):
""" Memoize for class methods """
@functools.wraps(func)
def wrapper(self, *args):
if not hasattr(self, "_cache"):
self._cache = {}
key = _argstring((func.__name__,) + args)
if key not in self._cache:
self._cache[key] = func(self, *arg... | [
"def",
"cached_method",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_cache\"",
")",
":",
"self",
".",
"_cache",
"="... | Memoize for class methods | [
"Memoize",
"for",
"class",
"methods"
] | 888ef72fcdb851b5873092bc9c4d6958733691f2 | https://github.com/CMUSTRUDEL/strudel.utils/blob/888ef72fcdb851b5873092bc9c4d6958733691f2/stutils/decorators.py#L169-L179 | train | 58,281 |
CMUSTRUDEL/strudel.utils | stutils/decorators.py | guard | def guard(func):
""" Prevents the decorated function from parallel execution.
Internally, this decorator creates a Lock object and transparently
obtains/releases it when calling the function.
"""
semaphore = threading.Lock()
@functools.wraps(func)
def wrapper(*args, **kwargs):
s... | python | def guard(func):
""" Prevents the decorated function from parallel execution.
Internally, this decorator creates a Lock object and transparently
obtains/releases it when calling the function.
"""
semaphore = threading.Lock()
@functools.wraps(func)
def wrapper(*args, **kwargs):
s... | [
"def",
"guard",
"(",
"func",
")",
":",
"semaphore",
"=",
"threading",
".",
"Lock",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"semaphore",
".",
"acquire",
"(",
... | Prevents the decorated function from parallel execution.
Internally, this decorator creates a Lock object and transparently
obtains/releases it when calling the function. | [
"Prevents",
"the",
"decorated",
"function",
"from",
"parallel",
"execution",
"."
] | 888ef72fcdb851b5873092bc9c4d6958733691f2 | https://github.com/CMUSTRUDEL/strudel.utils/blob/888ef72fcdb851b5873092bc9c4d6958733691f2/stutils/decorators.py#L241-L257 | train | 58,282 |
CMUSTRUDEL/strudel.utils | stutils/decorators.py | threadpool | def threadpool(num_workers=None):
"""Apply stutils.mapreduce.map to the given function"""
def decorator(func):
@functools.wraps(func)
def wrapper(data):
return mapreduce.map(func, data, num_workers)
return wrapper
return decorator | python | def threadpool(num_workers=None):
"""Apply stutils.mapreduce.map to the given function"""
def decorator(func):
@functools.wraps(func)
def wrapper(data):
return mapreduce.map(func, data, num_workers)
return wrapper
return decorator | [
"def",
"threadpool",
"(",
"num_workers",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"data",
")",
":",
"return",
"mapreduce",
".",
"map",
"(",
"func",
",",... | Apply stutils.mapreduce.map to the given function | [
"Apply",
"stutils",
".",
"mapreduce",
".",
"map",
"to",
"the",
"given",
"function"
] | 888ef72fcdb851b5873092bc9c4d6958733691f2 | https://github.com/CMUSTRUDEL/strudel.utils/blob/888ef72fcdb851b5873092bc9c4d6958733691f2/stutils/decorators.py#L260-L267 | train | 58,283 |
CMUSTRUDEL/strudel.utils | stutils/decorators.py | _FSCacher.invalidate_all | def invalidate_all(self):
""" Remove all files caching this function """
for fname in os.listdir(self.cache_path):
if fname.startswith(self.func.__name__ + "."):
os.remove(os.path.join(self.cache_path, fname)) | python | def invalidate_all(self):
""" Remove all files caching this function """
for fname in os.listdir(self.cache_path):
if fname.startswith(self.func.__name__ + "."):
os.remove(os.path.join(self.cache_path, fname)) | [
"def",
"invalidate_all",
"(",
"self",
")",
":",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"cache_path",
")",
":",
"if",
"fname",
".",
"startswith",
"(",
"self",
".",
"func",
".",
"__name__",
"+",
"\".\"",
")",
":",
"os",
".",
"r... | Remove all files caching this function | [
"Remove",
"all",
"files",
"caching",
"this",
"function"
] | 888ef72fcdb851b5873092bc9c4d6958733691f2 | https://github.com/CMUSTRUDEL/strudel.utils/blob/888ef72fcdb851b5873092bc9c4d6958733691f2/stutils/decorators.py#L106-L110 | train | 58,284 |
kmedian/ctmc | ctmc/ctmc_func.py | ctmc | def ctmc(data, numstates, transintv=1.0, toltime=1e-8, debug=False):
""" Continous Time Markov Chain
Parameters
----------
data : list of lists
A python list of N examples (e.g. rating histories of N companies,
the event data of N basketball games, etc.). The i-th example
consis... | python | def ctmc(data, numstates, transintv=1.0, toltime=1e-8, debug=False):
""" Continous Time Markov Chain
Parameters
----------
data : list of lists
A python list of N examples (e.g. rating histories of N companies,
the event data of N basketball games, etc.). The i-th example
consis... | [
"def",
"ctmc",
"(",
"data",
",",
"numstates",
",",
"transintv",
"=",
"1.0",
",",
"toltime",
"=",
"1e-8",
",",
"debug",
"=",
"False",
")",
":",
"# raise an exception if the data format is wrong",
"if",
"debug",
":",
"datacheck",
"(",
"data",
",",
"numstates",
... | Continous Time Markov Chain
Parameters
----------
data : list of lists
A python list of N examples (e.g. rating histories of N companies,
the event data of N basketball games, etc.). The i-th example
consist of one list with M_i encoded state labels and M_i the
durations or ... | [
"Continous",
"Time",
"Markov",
"Chain"
] | e30747f797ce777fd2aaa1b7ee5a77e91d7db5e4 | https://github.com/kmedian/ctmc/blob/e30747f797ce777fd2aaa1b7ee5a77e91d7db5e4/ctmc/ctmc_func.py#L9-L106 | train | 58,285 |
metagriffin/asset | asset/plugin.py | plugins | def plugins(group, spec=None):
# TODO: share this documentation with `../doc/plugin.rst`...
'''
Returns a `PluginSet` object for the specified setuptools-style
entrypoint `group`. This is just a wrapper around
`pkg_resources.iter_entry_points` that allows the plugins to sort
and override themselves.
The ... | python | def plugins(group, spec=None):
# TODO: share this documentation with `../doc/plugin.rst`...
'''
Returns a `PluginSet` object for the specified setuptools-style
entrypoint `group`. This is just a wrapper around
`pkg_resources.iter_entry_points` that allows the plugins to sort
and override themselves.
The ... | [
"def",
"plugins",
"(",
"group",
",",
"spec",
"=",
"None",
")",
":",
"# TODO: share this documentation with `../doc/plugin.rst`...",
"pspec",
"=",
"_parse_spec",
"(",
"spec",
")",
"plugs",
"=",
"list",
"(",
"_get_registered_plugins",
"(",
"group",
",",
"pspec",
")"... | Returns a `PluginSet` object for the specified setuptools-style
entrypoint `group`. This is just a wrapper around
`pkg_resources.iter_entry_points` that allows the plugins to sort
and override themselves.
The optional `spec` parameter controls how and what plugins are
loaded. If it is ``None`` or the special... | [
"Returns",
"a",
"PluginSet",
"object",
"for",
"the",
"specified",
"setuptools",
"-",
"style",
"entrypoint",
"group",
".",
"This",
"is",
"just",
"a",
"wrapper",
"around",
"pkg_resources",
".",
"iter_entry_points",
"that",
"allows",
"the",
"plugins",
"to",
"sort",... | f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c | https://github.com/metagriffin/asset/blob/f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c/asset/plugin.py#L112-L184 | train | 58,286 |
metagriffin/asset | asset/plugin.py | PluginSet.handle | def handle(self, object, *args, **kw):
'''
Calls each plugin in this PluginSet with the specified object,
arguments, and keywords in the standard group plugin order. The
return value from each successive invoked plugin is passed as the
first parameter to the next plugin. The final return value is th... | python | def handle(self, object, *args, **kw):
'''
Calls each plugin in this PluginSet with the specified object,
arguments, and keywords in the standard group plugin order. The
return value from each successive invoked plugin is passed as the
first parameter to the next plugin. The final return value is th... | [
"def",
"handle",
"(",
"self",
",",
"object",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"bool",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"spec",
"or",
"self",
".",
"spec",
"==",
"SPEC_ALL",
":",
"raise",
"ValueError",
... | Calls each plugin in this PluginSet with the specified object,
arguments, and keywords in the standard group plugin order. The
return value from each successive invoked plugin is passed as the
first parameter to the next plugin. The final return value is the
object returned from the last plugin.
If... | [
"Calls",
"each",
"plugin",
"in",
"this",
"PluginSet",
"with",
"the",
"specified",
"object",
"arguments",
"and",
"keywords",
"in",
"the",
"standard",
"group",
"plugin",
"order",
".",
"The",
"return",
"value",
"from",
"each",
"successive",
"invoked",
"plugin",
"... | f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c | https://github.com/metagriffin/asset/blob/f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c/asset/plugin.py#L50-L68 | train | 58,287 |
metagriffin/asset | asset/plugin.py | PluginSet.select | def select(self, name):
'''
Returns a new PluginSet that has only the plugins in this that are
named `name`.
'''
return PluginSet(self.group, name, [
plug for plug in self.plugins if plug.name == name]) | python | def select(self, name):
'''
Returns a new PluginSet that has only the plugins in this that are
named `name`.
'''
return PluginSet(self.group, name, [
plug for plug in self.plugins if plug.name == name]) | [
"def",
"select",
"(",
"self",
",",
"name",
")",
":",
"return",
"PluginSet",
"(",
"self",
".",
"group",
",",
"name",
",",
"[",
"plug",
"for",
"plug",
"in",
"self",
".",
"plugins",
"if",
"plug",
".",
"name",
"==",
"name",
"]",
")"
] | Returns a new PluginSet that has only the plugins in this that are
named `name`. | [
"Returns",
"a",
"new",
"PluginSet",
"that",
"has",
"only",
"the",
"plugins",
"in",
"this",
"that",
"are",
"named",
"name",
"."
] | f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c | https://github.com/metagriffin/asset/blob/f2c5e599cd4688f82216d4b5cfa87aab96d8bb8c/asset/plugin.py#L86-L92 | train | 58,288 |
MacHu-GWU/crawl_zillow-project | crawl_zillow/urlbuilder.py | UrlBuilder.browse_home_listpage_url | def browse_home_listpage_url(self,
state=None,
county=None,
zipcode=None,
street=None,
**kwargs):
"""
Construct an url of home list page by... | python | def browse_home_listpage_url(self,
state=None,
county=None,
zipcode=None,
street=None,
**kwargs):
"""
Construct an url of home list page by... | [
"def",
"browse_home_listpage_url",
"(",
"self",
",",
"state",
"=",
"None",
",",
"county",
"=",
"None",
",",
"zipcode",
"=",
"None",
",",
"street",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"domain_browse_homes",
"for",
"i... | Construct an url of home list page by state, county, zipcode, street.
Example:
- https://www.zillow.com/browse/homes/ca/
- https://www.zillow.com/browse/homes/ca/los-angeles-county/
- https://www.zillow.com/browse/homes/ca/los-angeles-county/91001/
- https://www.zillow.com/brow... | [
"Construct",
"an",
"url",
"of",
"home",
"list",
"page",
"by",
"state",
"county",
"zipcode",
"street",
"."
] | c6d7ca8e4c80e7e7e963496433ef73df1413c16e | https://github.com/MacHu-GWU/crawl_zillow-project/blob/c6d7ca8e4c80e7e7e963496433ef73df1413c16e/crawl_zillow/urlbuilder.py#L12-L33 | train | 58,289 |
sdcooke/django_bundles | django_bundles/templatetags/django_bundles_tags.py | _render_bundle | def _render_bundle(bundle_name):
"""
Renders the HTML for a bundle in place - one HTML tag or many depending on settings.USE_BUNDLES
"""
try:
bundle = get_bundles()[bundle_name]
except KeyError:
raise ImproperlyConfigured("Bundle '%s' is not defined" % bundle_name)
if bundle.use... | python | def _render_bundle(bundle_name):
"""
Renders the HTML for a bundle in place - one HTML tag or many depending on settings.USE_BUNDLES
"""
try:
bundle = get_bundles()[bundle_name]
except KeyError:
raise ImproperlyConfigured("Bundle '%s' is not defined" % bundle_name)
if bundle.use... | [
"def",
"_render_bundle",
"(",
"bundle_name",
")",
":",
"try",
":",
"bundle",
"=",
"get_bundles",
"(",
")",
"[",
"bundle_name",
"]",
"except",
"KeyError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"Bundle '%s' is not defined\"",
"%",
"bundle_name",
")",
"if",
... | Renders the HTML for a bundle in place - one HTML tag or many depending on settings.USE_BUNDLES | [
"Renders",
"the",
"HTML",
"for",
"a",
"bundle",
"in",
"place",
"-",
"one",
"HTML",
"tag",
"or",
"many",
"depending",
"on",
"settings",
".",
"USE_BUNDLES"
] | 2810fc455ec7391283792c1f108f4e8340f5d12f | https://github.com/sdcooke/django_bundles/blob/2810fc455ec7391283792c1f108f4e8340f5d12f/django_bundles/templatetags/django_bundles_tags.py#L23-L44 | train | 58,290 |
helixyte/everest | everest/representers/base.py | Representer.from_string | def from_string(self, string_representation, resource=None):
"""
Extracts resource data from the given string and converts them to
a new resource or updates the given resource from it.
"""
stream = NativeIO(string_representation)
return self.from_stream(stream, resource=r... | python | def from_string(self, string_representation, resource=None):
"""
Extracts resource data from the given string and converts them to
a new resource or updates the given resource from it.
"""
stream = NativeIO(string_representation)
return self.from_stream(stream, resource=r... | [
"def",
"from_string",
"(",
"self",
",",
"string_representation",
",",
"resource",
"=",
"None",
")",
":",
"stream",
"=",
"NativeIO",
"(",
"string_representation",
")",
"return",
"self",
".",
"from_stream",
"(",
"stream",
",",
"resource",
"=",
"resource",
")"
] | Extracts resource data from the given string and converts them to
a new resource or updates the given resource from it. | [
"Extracts",
"resource",
"data",
"from",
"the",
"given",
"string",
"and",
"converts",
"them",
"to",
"a",
"new",
"resource",
"or",
"updates",
"the",
"given",
"resource",
"from",
"it",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L38-L44 | train | 58,291 |
helixyte/everest | everest/representers/base.py | Representer.to_string | def to_string(self, obj):
"""
Converts the given resource to a string representation and returns
it.
"""
stream = NativeIO()
self.to_stream(obj, stream)
return text_(stream.getvalue(), encoding=self.encoding) | python | def to_string(self, obj):
"""
Converts the given resource to a string representation and returns
it.
"""
stream = NativeIO()
self.to_stream(obj, stream)
return text_(stream.getvalue(), encoding=self.encoding) | [
"def",
"to_string",
"(",
"self",
",",
"obj",
")",
":",
"stream",
"=",
"NativeIO",
"(",
")",
"self",
".",
"to_stream",
"(",
"obj",
",",
"stream",
")",
"return",
"text_",
"(",
"stream",
".",
"getvalue",
"(",
")",
",",
"encoding",
"=",
"self",
".",
"e... | Converts the given resource to a string representation and returns
it. | [
"Converts",
"the",
"given",
"resource",
"to",
"a",
"string",
"representation",
"and",
"returns",
"it",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L54-L61 | train | 58,292 |
helixyte/everest | everest/representers/base.py | ResourceRepresenter.data_from_bytes | def data_from_bytes(self, byte_representation):
"""
Converts the given bytes representation to resource data.
"""
text = byte_representation.decode(self.encoding)
return self.data_from_string(text) | python | def data_from_bytes(self, byte_representation):
"""
Converts the given bytes representation to resource data.
"""
text = byte_representation.decode(self.encoding)
return self.data_from_string(text) | [
"def",
"data_from_bytes",
"(",
"self",
",",
"byte_representation",
")",
":",
"text",
"=",
"byte_representation",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"return",
"self",
".",
"data_from_string",
"(",
"text",
")"
] | Converts the given bytes representation to resource data. | [
"Converts",
"the",
"given",
"bytes",
"representation",
"to",
"resource",
"data",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L135-L140 | train | 58,293 |
helixyte/everest | everest/representers/base.py | ResourceRepresenter.data_to_string | def data_to_string(self, data_element):
"""
Converts the given data element into a string representation.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
:returns: string representation (using the MIME content type
... | python | def data_to_string(self, data_element):
"""
Converts the given data element into a string representation.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
:returns: string representation (using the MIME content type
... | [
"def",
"data_to_string",
"(",
"self",
",",
"data_element",
")",
":",
"stream",
"=",
"NativeIO",
"(",
")",
"self",
".",
"data_to_stream",
"(",
"data_element",
",",
"stream",
")",
"return",
"stream",
".",
"getvalue",
"(",
")"
] | Converts the given data element into a string representation.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
:returns: string representation (using the MIME content type
configured for this representer) | [
"Converts",
"the",
"given",
"data",
"element",
"into",
"a",
"string",
"representation",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L142-L153 | train | 58,294 |
helixyte/everest | everest/representers/base.py | MappingResourceRepresenter.create_from_resource_class | def create_from_resource_class(cls, resource_class):
"""
Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class.
"""
mp_reg = get_mapping_registry(cls.content_type)
... | python | def create_from_resource_class(cls, resource_class):
"""
Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class.
"""
mp_reg = get_mapping_registry(cls.content_type)
... | [
"def",
"create_from_resource_class",
"(",
"cls",
",",
"resource_class",
")",
":",
"mp_reg",
"=",
"get_mapping_registry",
"(",
"cls",
".",
"content_type",
")",
"mp",
"=",
"mp_reg",
".",
"find_or_create_mapping",
"(",
"resource_class",
")",
"return",
"cls",
"(",
"... | Creates a new representer for the given resource class.
The representer obtains a reference to the (freshly created or looked
up) mapping for the resource class. | [
"Creates",
"a",
"new",
"representer",
"for",
"the",
"given",
"resource",
"class",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L215-L224 | train | 58,295 |
helixyte/everest | everest/representers/base.py | MappingResourceRepresenter.data_from_stream | def data_from_stream(self, stream):
"""
Creates a data element reading a representation from the given stream.
:returns: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
"""
parser = self._make_representation_parser(stream, self.resou... | python | def data_from_stream(self, stream):
"""
Creates a data element reading a representation from the given stream.
:returns: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
"""
parser = self._make_representation_parser(stream, self.resou... | [
"def",
"data_from_stream",
"(",
"self",
",",
"stream",
")",
":",
"parser",
"=",
"self",
".",
"_make_representation_parser",
"(",
"stream",
",",
"self",
".",
"resource_class",
",",
"self",
".",
"_mapping",
")",
"return",
"parser",
".",
"run",
"(",
")"
] | Creates a data element reading a representation from the given stream.
:returns: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement` | [
"Creates",
"a",
"data",
"element",
"reading",
"a",
"representation",
"from",
"the",
"given",
"stream",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L230-L239 | train | 58,296 |
helixyte/everest | everest/representers/base.py | MappingResourceRepresenter.data_to_stream | def data_to_stream(self, data_element, stream):
"""
Writes the given data element to the given stream.
"""
generator = \
self._make_representation_generator(stream, self.resource_class,
self._mapping)
generator.run(data_... | python | def data_to_stream(self, data_element, stream):
"""
Writes the given data element to the given stream.
"""
generator = \
self._make_representation_generator(stream, self.resource_class,
self._mapping)
generator.run(data_... | [
"def",
"data_to_stream",
"(",
"self",
",",
"data_element",
",",
"stream",
")",
":",
"generator",
"=",
"self",
".",
"_make_representation_generator",
"(",
"stream",
",",
"self",
".",
"resource_class",
",",
"self",
".",
"_mapping",
")",
"generator",
".",
"run",
... | Writes the given data element to the given stream. | [
"Writes",
"the",
"given",
"data",
"element",
"to",
"the",
"given",
"stream",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L241-L248 | train | 58,297 |
helixyte/everest | everest/representers/base.py | MappingResourceRepresenter.resource_from_data | def resource_from_data(self, data_element, resource=None):
"""
Converts the given data element to a resource.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
"""
return self._mapping.map_to_resource(data_element,... | python | def resource_from_data(self, data_element, resource=None):
"""
Converts the given data element to a resource.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
"""
return self._mapping.map_to_resource(data_element,... | [
"def",
"resource_from_data",
"(",
"self",
",",
"data_element",
",",
"resource",
"=",
"None",
")",
":",
"return",
"self",
".",
"_mapping",
".",
"map_to_resource",
"(",
"data_element",
",",
"resource",
"=",
"resource",
")"
] | Converts the given data element to a resource.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement` | [
"Converts",
"the",
"given",
"data",
"element",
"to",
"a",
"resource",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L250-L257 | train | 58,298 |
helixyte/everest | everest/representers/base.py | MappingResourceRepresenter.configure | def configure(self, options=None, attribute_options=None): # pylint: disable=W0221
"""
Configures the options and attribute options of the mapping associated
with this representer with the given dictionaries.
:param dict options: configuration options for the mapping associated
... | python | def configure(self, options=None, attribute_options=None): # pylint: disable=W0221
"""
Configures the options and attribute options of the mapping associated
with this representer with the given dictionaries.
:param dict options: configuration options for the mapping associated
... | [
"def",
"configure",
"(",
"self",
",",
"options",
"=",
"None",
",",
"attribute_options",
"=",
"None",
")",
":",
"# pylint: disable=W0221",
"self",
".",
"_mapping",
".",
"update",
"(",
"options",
"=",
"options",
",",
"attribute_options",
"=",
"attribute_options",
... | Configures the options and attribute options of the mapping associated
with this representer with the given dictionaries.
:param dict options: configuration options for the mapping associated
with this representer.
:param dict attribute_options: attribute options for the mapping
... | [
"Configures",
"the",
"options",
"and",
"attribute",
"options",
"of",
"the",
"mapping",
"associated",
"with",
"this",
"representer",
"with",
"the",
"given",
"dictionaries",
"."
] | 70c9b93c3061db5cb62428349d18b8fb8566411b | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/base.py#L278-L289 | train | 58,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.