repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
hobson/pug-dj | pug/dj/sqlserver.py | dictfetchall | def dictfetchall(cursor):
"""Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/
"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] | python | def dictfetchall(cursor):
"""Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/
"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] | [
"def",
"dictfetchall",
"(",
"cursor",
")",
":",
"desc",
"=",
"cursor",
".",
"description",
"return",
"[",
"dict",
"(",
"zip",
"(",
"[",
"col",
"[",
"0",
"]",
"for",
"col",
"in",
"desc",
"]",
",",
"row",
")",
")",
"for",
"row",
"in",
"cursor",
"."... | Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/ | [
"Returns",
"all",
"rows",
"from",
"a",
"cursor",
"as",
"a",
"dict",
"(",
"rather",
"than",
"a",
"headerless",
"table",
")"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/sqlserver.py#L9-L15 |
hobson/pug-dj | pug/dj/sqlserver.py | dicts_from_table | def dicts_from_table(table, keys=None):
"""Returns a list of dict() objects, one for each row in a list of lists (table)"""
lod = []
for row in table:
if not keys:
keys = row
if not all((k not in (None, '') or bool(k.strip())) for k in keys):
keys = None
... | python | def dicts_from_table(table, keys=None):
"""Returns a list of dict() objects, one for each row in a list of lists (table)"""
lod = []
for row in table:
if not keys:
keys = row
if not all((k not in (None, '') or bool(k.strip())) for k in keys):
keys = None
... | [
"def",
"dicts_from_table",
"(",
"table",
",",
"keys",
"=",
"None",
")",
":",
"lod",
"=",
"[",
"]",
"for",
"row",
"in",
"table",
":",
"if",
"not",
"keys",
":",
"keys",
"=",
"row",
"if",
"not",
"all",
"(",
"(",
"k",
"not",
"in",
"(",
"None",
",",... | Returns a list of dict() objects, one for each row in a list of lists (table) | [
"Returns",
"a",
"list",
"of",
"dict",
"()",
"objects",
"one",
"for",
"each",
"row",
"in",
"a",
"list",
"of",
"lists",
"(",
"table",
")"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/sqlserver.py#L18-L28 |
hobson/pug-dj | pug/dj/sqlserver.py | datatype | def datatype(dbtype, description, cursor):
"""Google AppEngine Helper to convert a data type into a string."""
dt = cursor.db.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt | python | def datatype(dbtype, description, cursor):
"""Google AppEngine Helper to convert a data type into a string."""
dt = cursor.db.introspection.get_field_type(dbtype, description)
if type(dt) is tuple:
return dt[0]
else:
return dt | [
"def",
"datatype",
"(",
"dbtype",
",",
"description",
",",
"cursor",
")",
":",
"dt",
"=",
"cursor",
".",
"db",
".",
"introspection",
".",
"get_field_type",
"(",
"dbtype",
",",
"description",
")",
"if",
"type",
"(",
"dt",
")",
"is",
"tuple",
":",
"retur... | Google AppEngine Helper to convert a data type into a string. | [
"Google",
"AppEngine",
"Helper",
"to",
"convert",
"a",
"data",
"type",
"into",
"a",
"string",
"."
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/sqlserver.py#L90-L96 |
Vito2015/pyextend | pyextend/core/json2csv.py | json2csv | def json2csv(json_str, show_header=False, separator='\t'):
"""
Format a json string to csv like.
:param json_str: json object string
:param show_header: can returns csv header line
:param separator: csv column format separator
:return: if show_header=False: a string like csv formatting;
... | python | def json2csv(json_str, show_header=False, separator='\t'):
"""
Format a json string to csv like.
:param json_str: json object string
:param show_header: can returns csv header line
:param separator: csv column format separator
:return: if show_header=False: a string like csv formatting;
... | [
"def",
"json2csv",
"(",
"json_str",
",",
"show_header",
"=",
"False",
",",
"separator",
"=",
"'\\t'",
")",
":",
"json_obj",
"=",
"json",
".",
"loads",
"(",
"json_str",
")",
"cols",
"=",
"[",
"col",
"for",
"col",
"in",
"json_obj",
".",
"keys",
"(",
")... | Format a json string to csv like.
:param json_str: json object string
:param show_header: can returns csv header line
:param separator: csv column format separator
:return: if show_header=False: a string like csv formatting;
if show_header=True: a tuple (header, csv string) | [
"Format",
"a",
"json",
"string",
"to",
"csv",
"like",
".",
":",
"param",
"json_str",
":",
"json",
"object",
"string",
":",
"param",
"show_header",
":",
"can",
"returns",
"csv",
"header",
"line",
":",
"param",
"separator",
":",
"csv",
"column",
"format",
... | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/json2csv.py#L6-L23 |
flytrap/flytrap-base | flytrap/base/backends.py | MongoDjangoFilterBackend.get_filter_class | def get_filter_class(self, view, queryset=None):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
if filter_class:
filter_model = filter_class.Meta.model
assert issubclass(querys... | python | def get_filter_class(self, view, queryset=None):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
if filter_class:
filter_model = filter_class.Meta.model
assert issubclass(querys... | [
"def",
"get_filter_class",
"(",
"self",
",",
"view",
",",
"queryset",
"=",
"None",
")",
":",
"filter_class",
"=",
"getattr",
"(",
"view",
",",
"'filter_class'",
",",
"None",
")",
"if",
"filter_class",
":",
"filter_model",
"=",
"filter_class",
".",
"Meta",
... | Return the django-filters `FilterSet` used to filter the queryset. | [
"Return",
"the",
"django",
"-",
"filters",
"FilterSet",
"used",
"to",
"filter",
"the",
"queryset",
"."
] | train | https://github.com/flytrap/flytrap-base/blob/fa5a3135ce669725f88ef61d5d9f548cedfaf0ff/flytrap/base/backends.py#L11-L24 |
pycontribs/pyversion | version/tag_command.py | tag.run | def run(self):
"""Will tag the currently active git commit id with the next release tag id"""
sha = VersionUtils.run_git_command(["rev-parse", "HEAD"], self.git_dir)
tag = self.distribution.get_version()
if self.has_tag(tag, sha):
tags_sha = VersionUtils.run_git_command(["re... | python | def run(self):
"""Will tag the currently active git commit id with the next release tag id"""
sha = VersionUtils.run_git_command(["rev-parse", "HEAD"], self.git_dir)
tag = self.distribution.get_version()
if self.has_tag(tag, sha):
tags_sha = VersionUtils.run_git_command(["re... | [
"def",
"run",
"(",
"self",
")",
":",
"sha",
"=",
"VersionUtils",
".",
"run_git_command",
"(",
"[",
"\"rev-parse\"",
",",
"\"HEAD\"",
"]",
",",
"self",
".",
"git_dir",
")",
"tag",
"=",
"self",
".",
"distribution",
".",
"get_version",
"(",
")",
"if",
"se... | Will tag the currently active git commit id with the next release tag id | [
"Will",
"tag",
"the",
"currently",
"active",
"git",
"commit",
"id",
"with",
"the",
"next",
"release",
"tag",
"id"
] | train | https://github.com/pycontribs/pyversion/blob/6bbb799846ed4e97e84a3f0f2dbe14685f2ddb39/version/tag_command.py#L38-L68 |
CTPUG/mdx_attr_cols | mdx_attr_cols.py | AttrColExtension.extendMarkdown | def extendMarkdown(self, md, md_globals=None):
"""Initializes markdown extension components."""
if any(
x not in md.treeprocessors
for x in self.REQUIRED_EXTENSION_INTERNAL_NAMES):
raise RuntimeError(
"The attr_cols markdown extension depends t... | python | def extendMarkdown(self, md, md_globals=None):
"""Initializes markdown extension components."""
if any(
x not in md.treeprocessors
for x in self.REQUIRED_EXTENSION_INTERNAL_NAMES):
raise RuntimeError(
"The attr_cols markdown extension depends t... | [
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
",",
"md_globals",
"=",
"None",
")",
":",
"if",
"any",
"(",
"x",
"not",
"in",
"md",
".",
"treeprocessors",
"for",
"x",
"in",
"self",
".",
"REQUIRED_EXTENSION_INTERNAL_NAMES",
")",
":",
"raise",
"RuntimeError... | Initializes markdown extension components. | [
"Initializes",
"markdown",
"extension",
"components",
"."
] | train | https://github.com/CTPUG/mdx_attr_cols/blob/46329b676842205b75b368a7cf2aeba0474c2870/mdx_attr_cols.py#L71-L83 |
FlorianLudwig/rueckenwind | rw/cfg.py | read_file | def read_file(paths):
"""read config from path or list of paths
:param str|list[str] paths: path or list of paths
:return dict: loaded and merged config
"""
if isinstance(paths, str):
paths = [paths]
re = {}
for path in paths:
cfg = yaml.load(open(path))
merge(re, ... | python | def read_file(paths):
"""read config from path or list of paths
:param str|list[str] paths: path or list of paths
:return dict: loaded and merged config
"""
if isinstance(paths, str):
paths = [paths]
re = {}
for path in paths:
cfg = yaml.load(open(path))
merge(re, ... | [
"def",
"read_file",
"(",
"paths",
")",
":",
"if",
"isinstance",
"(",
"paths",
",",
"str",
")",
":",
"paths",
"=",
"[",
"paths",
"]",
"re",
"=",
"{",
"}",
"for",
"path",
"in",
"paths",
":",
"cfg",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"pat... | read config from path or list of paths
:param str|list[str] paths: path or list of paths
:return dict: loaded and merged config | [
"read",
"config",
"from",
"path",
"or",
"list",
"of",
"paths"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/cfg.py#L29-L44 |
openp2pdesign/makerlabs | makerlabs/diybio_org.py | data_from_diybio_org | def data_from_diybio_org():
"""Scrapes data from diybio.org."""
r = requests.get(diy_bio_labs_url)
if r.status_code == 200:
# Fix a problem in the html source while loading it
data = BeautifulSoup(r.text.replace(u'\xa0', u''), "lxml")
else:
data = "There was an error while acce... | python | def data_from_diybio_org():
"""Scrapes data from diybio.org."""
r = requests.get(diy_bio_labs_url)
if r.status_code == 200:
# Fix a problem in the html source while loading it
data = BeautifulSoup(r.text.replace(u'\xa0', u''), "lxml")
else:
data = "There was an error while acce... | [
"def",
"data_from_diybio_org",
"(",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"diy_bio_labs_url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"# Fix a problem in the html source while loading it",
"data",
"=",
"BeautifulSoup",
"(",
"r",
".",
"te... | Scrapes data from diybio.org. | [
"Scrapes",
"data",
"from",
"diybio",
".",
"org",
"."
] | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/diybio_org.py#L34-L45 |
openp2pdesign/makerlabs | makerlabs/diybio_org.py | get_labs | def get_labs(format, open_cage_api_key):
"""Gets DIYBio Lab data from diybio.org."""
diybiolabs_soup = data_from_diybio_org()
diybiolabs = {}
rows_list = []
continents_dict = {}
continents_order = 0
ranges_starting_points = []
# Load all the DIYBio Labs
# By first parsing the html... | python | def get_labs(format, open_cage_api_key):
"""Gets DIYBio Lab data from diybio.org."""
diybiolabs_soup = data_from_diybio_org()
diybiolabs = {}
rows_list = []
continents_dict = {}
continents_order = 0
ranges_starting_points = []
# Load all the DIYBio Labs
# By first parsing the html... | [
"def",
"get_labs",
"(",
"format",
",",
"open_cage_api_key",
")",
":",
"diybiolabs_soup",
"=",
"data_from_diybio_org",
"(",
")",
"diybiolabs",
"=",
"{",
"}",
"rows_list",
"=",
"[",
"]",
"continents_dict",
"=",
"{",
"}",
"continents_order",
"=",
"0",
"ranges_sta... | Gets DIYBio Lab data from diybio.org. | [
"Gets",
"DIYBio",
"Lab",
"data",
"from",
"diybio",
".",
"org",
"."
] | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/diybio_org.py#L48-L176 |
jeffrimko/Auxly | lib/auxly/__init__.py | open | def open(target):
"""Opens the target file or URL in the default application.
**Attribution**:
Written by user4815162342 and originally posted on
`Stack Overflow <http://stackoverflow.com/a/17317468>`_.
**Examples**:
::
auxly.open("myfile.txt")
auxly.open("https://www.github.co... | python | def open(target):
"""Opens the target file or URL in the default application.
**Attribution**:
Written by user4815162342 and originally posted on
`Stack Overflow <http://stackoverflow.com/a/17317468>`_.
**Examples**:
::
auxly.open("myfile.txt")
auxly.open("https://www.github.co... | [
"def",
"open",
"(",
"target",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"os",
".",
"startfile",
"(",
"target",
")",
"else",
":",
"opener",
"=",
"\"open\"",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
"else",
"\"xdg-open\"",
... | Opens the target file or URL in the default application.
**Attribution**:
Written by user4815162342 and originally posted on
`Stack Overflow <http://stackoverflow.com/a/17317468>`_.
**Examples**:
::
auxly.open("myfile.txt")
auxly.open("https://www.github.com/") | [
"Opens",
"the",
"target",
"file",
"or",
"URL",
"in",
"the",
"default",
"application",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L25-L41 |
jeffrimko/Auxly | lib/auxly/__init__.py | verbose | def verbose(enabled):
"""Returns normal print function if enable, otherwise a dummy print
function is returned which will suppress output."""
def _vprint(msg, **kwargs):
print(msg, **kwargs)
def _nprint(msg, **kwargs):
pass
return _vprint if enabled else _nprint | python | def verbose(enabled):
"""Returns normal print function if enable, otherwise a dummy print
function is returned which will suppress output."""
def _vprint(msg, **kwargs):
print(msg, **kwargs)
def _nprint(msg, **kwargs):
pass
return _vprint if enabled else _nprint | [
"def",
"verbose",
"(",
"enabled",
")",
":",
"def",
"_vprint",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
"def",
"_nprint",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"pass",
"return",
"... | Returns normal print function if enable, otherwise a dummy print
function is returned which will suppress output. | [
"Returns",
"normal",
"print",
"function",
"if",
"enable",
"otherwise",
"a",
"dummy",
"print",
"function",
"is",
"returned",
"which",
"will",
"suppress",
"output",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L55-L62 |
jeffrimko/Auxly | lib/auxly/__init__.py | trycatch | def trycatch(*args, **kwargs):
"""Wraps a function in a try/catch block. Can be used as a function
decorator or as a function that accepts another function.
**Params**:
- func (func) - Function to call. Only available when used as a function.
- oncatch (str) [kwargs] - Function to call if an ex... | python | def trycatch(*args, **kwargs):
"""Wraps a function in a try/catch block. Can be used as a function
decorator or as a function that accepts another function.
**Params**:
- func (func) - Function to call. Only available when used as a function.
- oncatch (str) [kwargs] - Function to call if an ex... | [
"def",
"trycatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rethrow",
"=",
"kwargs",
".",
"get",
"(",
"'rethrow'",
",",
"False",
")",
"oncatch",
"=",
"kwargs",
".",
"get",
"(",
"'oncatch'",
",",
"None",
")",
"def",
"decor",
"(",
"func"... | Wraps a function in a try/catch block. Can be used as a function
decorator or as a function that accepts another function.
**Params**:
- func (func) - Function to call. Only available when used as a function.
- oncatch (str) [kwargs] - Function to call if an exception is caught.
- rethrow (st... | [
"Wraps",
"a",
"function",
"in",
"a",
"try",
"/",
"catch",
"block",
".",
"Can",
"be",
"used",
"as",
"a",
"function",
"decorator",
"or",
"as",
"a",
"function",
"that",
"accepts",
"another",
"function",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L64-L95 |
jeffrimko/Auxly | lib/auxly/__init__.py | callstop | def callstop(*args, **kwargs):
"""Limits the number of times a function can be called. Can be used as a
function decorator or as a function that accepts another function. If used
as a function, it returns a new function that will be call limited.
**Params**:
- func (func) - Function to call. Only... | python | def callstop(*args, **kwargs):
"""Limits the number of times a function can be called. Can be used as a
function decorator or as a function that accepts another function. If used
as a function, it returns a new function that will be call limited.
**Params**:
- func (func) - Function to call. Only... | [
"def",
"callstop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"limit",
"=",
"kwargs",
".",
"get",
"(",
"'limit'",
",",
"1",
")",
"def",
"decor",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
... | Limits the number of times a function can be called. Can be used as a
function decorator or as a function that accepts another function. If used
as a function, it returns a new function that will be call limited.
**Params**:
- func (func) - Function to call. Only available when used as a function.
... | [
"Limits",
"the",
"number",
"of",
"times",
"a",
"function",
"can",
"be",
"called",
".",
"Can",
"be",
"used",
"as",
"a",
"function",
"decorator",
"or",
"as",
"a",
"function",
"that",
"accepts",
"another",
"function",
".",
"If",
"used",
"as",
"a",
"function... | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/__init__.py#L97-L122 |
50onRed/smr | smr/ec2.py | wait_for_instance | def wait_for_instance(instance):
""" wait for instance status to be 'running' in which case return True, False otherwise """
status = None
print("getting status for instance {} ...".format(instance.id))
while status is None:
try:
status = instance.update()
if status is N... | python | def wait_for_instance(instance):
""" wait for instance status to be 'running' in which case return True, False otherwise """
status = None
print("getting status for instance {} ...".format(instance.id))
while status is None:
try:
status = instance.update()
if status is N... | [
"def",
"wait_for_instance",
"(",
"instance",
")",
":",
"status",
"=",
"None",
"print",
"(",
"\"getting status for instance {} ...\"",
".",
"format",
"(",
"instance",
".",
"id",
")",
")",
"while",
"status",
"is",
"None",
":",
"try",
":",
"status",
"=",
"insta... | wait for instance status to be 'running' in which case return True, False otherwise | [
"wait",
"for",
"instance",
"status",
"to",
"be",
"running",
"in",
"which",
"case",
"return",
"True",
"False",
"otherwise"
] | train | https://github.com/50onRed/smr/blob/999b33d86b6a900d7c4aadf03cf4a661acba9f1b/smr/ec2.py#L78-L102 |
openknowledge-archive/datapackage-validate-py | datapackage_validate/validate.py | validate | def validate(datapackage, schema='base'):
'''Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can ... | python | def validate(datapackage, schema='base'):
'''Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can ... | [
"def",
"validate",
"(",
"datapackage",
",",
"schema",
"=",
"'base'",
")",
":",
"errors",
"=",
"[",
"]",
"schema_obj",
"=",
"None",
"datapackage_obj",
"=",
"None",
"# Sanity check datapackage",
"# If datapackage is a str, check json is well formed",
"if",
"isinstance",
... | Validate Data Package datapackage.json files against a jsonschema.
Args:
datapackage (str or dict): The Data Package descriptor file (i.e.
datapackage.json) as a dict or its contents in a string.
schema (str or dict): If a string, it can be the schema ID in the
registry, a l... | [
"Validate",
"Data",
"Package",
"datapackage",
".",
"json",
"files",
"against",
"a",
"jsonschema",
"."
] | train | https://github.com/openknowledge-archive/datapackage-validate-py/blob/5f906bd4e0baa78dfd45f48e7fa3c5d649e6846a/datapackage_validate/validate.py#L19-L78 |
lextoumbourou/txstripe | txstripe/resource.py | make_request | def make_request(
ins, method, url, stripe_account=None, params=None, headers=None, **kwargs
):
"""
Return a deferred or handle error.
For overriding in various classes.
"""
if txstripe.api_key is None:
raise error.AuthenticationError(
'No API key provided. (HINT: set your A... | python | def make_request(
ins, method, url, stripe_account=None, params=None, headers=None, **kwargs
):
"""
Return a deferred or handle error.
For overriding in various classes.
"""
if txstripe.api_key is None:
raise error.AuthenticationError(
'No API key provided. (HINT: set your A... | [
"def",
"make_request",
"(",
"ins",
",",
"method",
",",
"url",
",",
"stripe_account",
"=",
"None",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"txstripe",
".",
"api_key",
"is",
"None",
":",
"raise"... | Return a deferred or handle error.
For overriding in various classes. | [
"Return",
"a",
"deferred",
"or",
"handle",
"error",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L52-L110 |
lextoumbourou/txstripe | txstripe/resource.py | StripeObject.request | def request(self, method, url, params=None, headers=None):
"""Return a deferred."""
if params is None:
params = self._retrieve_params
return make_request(
self, method, url, stripe_account=self.stripe_account,
params=params, headers=headers) | python | def request(self, method, url, params=None, headers=None):
"""Return a deferred."""
if params is None:
params = self._retrieve_params
return make_request(
self, method, url, stripe_account=self.stripe_account,
params=params, headers=headers) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"self",
".",
"_retrieve_params",
"return",
"make_request",
"(",
"self",
",",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L117-L124 |
lextoumbourou/txstripe | txstripe/resource.py | APIResource.retrieve | def retrieve(cls, id, api_key=None, **params):
"""Return a deferred."""
instance = cls(id, api_key, **params)
d = instance.refresh()
return d.addCallback(lambda _: instance) | python | def retrieve(cls, id, api_key=None, **params):
"""Return a deferred."""
instance = cls(id, api_key, **params)
d = instance.refresh()
return d.addCallback(lambda _: instance) | [
"def",
"retrieve",
"(",
"cls",
",",
"id",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"instance",
"=",
"cls",
"(",
"id",
",",
"api_key",
",",
"*",
"*",
"params",
")",
"d",
"=",
"instance",
".",
"refresh",
"(",
")",
"return",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L132-L136 |
lextoumbourou/txstripe | txstripe/resource.py | APIResource.refresh | def refresh(self):
"""Return a deferred."""
d = self.request('get', self.instance_url())
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | python | def refresh(self):
"""Return a deferred."""
d = self.request('get', self.instance_url())
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | [
"def",
"refresh",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"self",
".",
"instance_url",
"(",
")",
")",
"return",
"d",
".",
"addCallback",
"(",
"self",
".",
"refresh_from",
")",
".",
"addCallback",
"(",
"lambda",
"_"... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L138-L141 |
lextoumbourou/txstripe | txstripe/resource.py | ListableAPIResource.all | def all(cls, api_key=None, idempotency_key=None,
stripe_account=None, **params):
"""Return a deferred."""
url = cls.class_url()
return make_request(
cls, 'get', url, stripe_acconut=None, params=params) | python | def all(cls, api_key=None, idempotency_key=None,
stripe_account=None, **params):
"""Return a deferred."""
url = cls.class_url()
return make_request(
cls, 'get', url, stripe_acconut=None, params=params) | [
"def",
"all",
"(",
"cls",
",",
"api_key",
"=",
"None",
",",
"idempotency_key",
"=",
"None",
",",
"stripe_account",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"cls",
".",
"class_url",
"(",
")",
"return",
"make_request",
"(",
"cls",
",... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L187-L192 |
lextoumbourou/txstripe | txstripe/resource.py | CreateableAPIResource.create | def create(
cls, api_key=None, idempotency_key=None, stripe_account=None, **params
):
"""Return a deferred."""
url = cls.class_url()
headers = populate_headers(idempotency_key)
return make_request(
cls, 'post', url, stripe_account=stripe_account,
heade... | python | def create(
cls, api_key=None, idempotency_key=None, stripe_account=None, **params
):
"""Return a deferred."""
url = cls.class_url()
headers = populate_headers(idempotency_key)
return make_request(
cls, 'post', url, stripe_account=stripe_account,
heade... | [
"def",
"create",
"(",
"cls",
",",
"api_key",
"=",
"None",
",",
"idempotency_key",
"=",
"None",
",",
"stripe_account",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"cls",
".",
"class_url",
"(",
")",
"headers",
"=",
"populate_headers",
"("... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L200-L208 |
lextoumbourou/txstripe | txstripe/resource.py | UpdateableAPIResource.save | def save(self, idempotency_key=None):
"""Return a deferred."""
updated_params = self.serialize(None)
headers = populate_headers(idempotency_key)
if not updated_params:
util.logger.debug("Trying to save already saved object %r", self)
return defer.succeed(self)
... | python | def save(self, idempotency_key=None):
"""Return a deferred."""
updated_params = self.serialize(None)
headers = populate_headers(idempotency_key)
if not updated_params:
util.logger.debug("Trying to save already saved object %r", self)
return defer.succeed(self)
... | [
"def",
"save",
"(",
"self",
",",
"idempotency_key",
"=",
"None",
")",
":",
"updated_params",
"=",
"self",
".",
"serialize",
"(",
"None",
")",
"headers",
"=",
"populate_headers",
"(",
"idempotency_key",
")",
"if",
"not",
"updated_params",
":",
"util",
".",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L215-L225 |
lextoumbourou/txstripe | txstripe/resource.py | DeletableAPIResource.delete | def delete(self, **params):
"""Return a deferred."""
d = self.request('delete', self.instance_url(), params)
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | python | def delete(self, **params):
"""Return a deferred."""
d = self.request('delete', self.instance_url(), params)
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"d",
"=",
"self",
".",
"request",
"(",
"'delete'",
",",
"self",
".",
"instance_url",
"(",
")",
",",
"params",
")",
"return",
"d",
".",
"addCallback",
"(",
"self",
".",
"refresh_from",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L232-L235 |
lextoumbourou/txstripe | txstripe/resource.py | Card.retrieve | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Card, cls).retrieve(*args, **kwargs) | python | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Card, cls).retrieve(*args, **kwargs) | [
"def",
"retrieve",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Card",
",",
"cls",
")",
".",
"retrieve",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return parent method. | [
"Return",
"parent",
"method",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L270-L272 |
lextoumbourou/txstripe | txstripe/resource.py | BankAccount.retrieve | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(BankAccount, cls).retrieve(*args, **kwargs) | python | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(BankAccount, cls).retrieve(*args, **kwargs) | [
"def",
"retrieve",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"BankAccount",
",",
"cls",
")",
".",
"retrieve",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return parent method. | [
"Return",
"parent",
"method",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L284-L286 |
lextoumbourou/txstripe | txstripe/resource.py | Charge.update_dispute | def update_dispute(self, idempotency_key=None, **params):
"""Return a deferred."""
url = self.instance_url() + '/dispute'
headers = populate_headers(idempotency_key)
d = self.request('post', url, params, headers)
d.addCallback(lambda response: self.refresh_from(
{'dis... | python | def update_dispute(self, idempotency_key=None, **params):
"""Return a deferred."""
url = self.instance_url() + '/dispute'
headers = populate_headers(idempotency_key)
d = self.request('post', url, params, headers)
d.addCallback(lambda response: self.refresh_from(
{'dis... | [
"def",
"update_dispute",
"(",
"self",
",",
"idempotency_key",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"self",
".",
"instance_url",
"(",
")",
"+",
"'/dispute'",
"headers",
"=",
"populate_headers",
"(",
"idempotency_key",
")",
"d",
"=",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L309-L316 |
lextoumbourou/txstripe | txstripe/resource.py | Dispute.close | def close(self, idempotency_key=None):
"""Return a deferred."""
url = self.instance_url() + '/close'
headers = populate_headers(idempotency_key)
d = self.request('post', url, {}, headers)
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | python | def close(self, idempotency_key=None):
"""Return a deferred."""
url = self.instance_url() + '/close'
headers = populate_headers(idempotency_key)
d = self.request('post', url, {}, headers)
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | [
"def",
"close",
"(",
"self",
",",
"idempotency_key",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"instance_url",
"(",
")",
"+",
"'/close'",
"headers",
"=",
"populate_headers",
"(",
"idempotency_key",
")",
"d",
"=",
"self",
".",
"request",
"(",
"'post... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L350-L355 |
lextoumbourou/txstripe | txstripe/resource.py | Customer.invoices | def invoices(self, **params):
"""Return a deferred."""
params['customer'] = self.id
return Invoice.all(self.api_key, **params) | python | def invoices(self, **params):
"""Return a deferred."""
params['customer'] = self.id
return Invoice.all(self.api_key, **params) | [
"def",
"invoices",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'customer'",
"]",
"=",
"self",
".",
"id",
"return",
"Invoice",
".",
"all",
"(",
"self",
".",
"api_key",
",",
"*",
"*",
"params",
")"
] | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L369-L372 |
lextoumbourou/txstripe | txstripe/resource.py | Customer.invoice_items | def invoice_items(self, **params):
"""Return a deferred."""
params['customer'] = self.id
return InvoiceItem.all(self.api_key, **params) | python | def invoice_items(self, **params):
"""Return a deferred."""
params['customer'] = self.id
return InvoiceItem.all(self.api_key, **params) | [
"def",
"invoice_items",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'customer'",
"]",
"=",
"self",
".",
"id",
"return",
"InvoiceItem",
".",
"all",
"(",
"self",
".",
"api_key",
",",
"*",
"*",
"params",
")"
] | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L374-L377 |
lextoumbourou/txstripe | txstripe/resource.py | Customer.cancel_subscription | def cancel_subscription(self, idempotency_key=None, **params):
"""Return a deferred."""
warnings.warn(
'The `cancel_subscription` method is deprecated. Instead, use the '
'`subscriptions` resource on the customer object to cancel a '
'subscription',
Deprec... | python | def cancel_subscription(self, idempotency_key=None, **params):
"""Return a deferred."""
warnings.warn(
'The `cancel_subscription` method is deprecated. Instead, use the '
'`subscriptions` resource on the customer object to cancel a '
'subscription',
Deprec... | [
"def",
"cancel_subscription",
"(",
"self",
",",
"idempotency_key",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"warnings",
".",
"warn",
"(",
"'The `cancel_subscription` method is deprecated. Instead, use the '",
"'`subscriptions` resource on the customer object to cancel a ... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L398-L410 |
lextoumbourou/txstripe | txstripe/resource.py | Customer.delete_discount | def delete_discount(self, **params):
"""Return a deferred."""
url = self.instance_url() + '/discount'
d = self.request('delete', url)
d.addCallback(lambda response: self.refresh_from(
{'discount': None}, api_key, True))
return d.addCallback(lambda _: self.subscription... | python | def delete_discount(self, **params):
"""Return a deferred."""
url = self.instance_url() + '/discount'
d = self.request('delete', url)
d.addCallback(lambda response: self.refresh_from(
{'discount': None}, api_key, True))
return d.addCallback(lambda _: self.subscription... | [
"def",
"delete_discount",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"self",
".",
"instance_url",
"(",
")",
"+",
"'/discount'",
"d",
"=",
"self",
".",
"request",
"(",
"'delete'",
",",
"url",
")",
"d",
".",
"addCallback",
"(",
"lambda... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L412-L418 |
lextoumbourou/txstripe | txstripe/resource.py | Invoice.upcoming | def upcoming(cls, api_key=None, stripe_account=None, **params):
"""Return a deferred."""
url = cls.class_url() + '/upcoming'
return cls.request('get', url, params) | python | def upcoming(cls, api_key=None, stripe_account=None, **params):
"""Return a deferred."""
url = cls.class_url() + '/upcoming'
return cls.request('get', url, params) | [
"def",
"upcoming",
"(",
"cls",
",",
"api_key",
"=",
"None",
",",
"stripe_account",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"cls",
".",
"class_url",
"(",
")",
"+",
"'/upcoming'",
"return",
"cls",
".",
"request",
"(",
"'get'",
",",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L433-L436 |
lextoumbourou/txstripe | txstripe/resource.py | Subscription.retrieve | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Subscription, cls).retrieve(*args, **kwargs) | python | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Subscription, cls).retrieve(*args, **kwargs) | [
"def",
"retrieve",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Subscription",
",",
"cls",
")",
".",
"retrieve",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return parent method. | [
"Return",
"parent",
"method",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L470-L472 |
lextoumbourou/txstripe | txstripe/resource.py | Transfer.cancel | def cancel(self):
"""Return a deferred."""
d = self.request('post', self.instance_url() + '/cancel')
return d.addCallback(self.refresh_from) | python | def cancel(self):
"""Return a deferred."""
d = self.request('post', self.instance_url() + '/cancel')
return d.addCallback(self.refresh_from) | [
"def",
"cancel",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"request",
"(",
"'post'",
",",
"self",
".",
"instance_url",
"(",
")",
"+",
"'/cancel'",
")",
"return",
"d",
".",
"addCallback",
"(",
"self",
".",
"refresh_from",
")"
] | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L521-L524 |
lextoumbourou/txstripe | txstripe/resource.py | Reversal.retrieve | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Reversal, cls).retrieve(*args, **kwargs) | python | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(Reversal, cls).retrieve(*args, **kwargs) | [
"def",
"retrieve",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Reversal",
",",
"cls",
")",
".",
"retrieve",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return parent method. | [
"Return",
"parent",
"method",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L536-L538 |
lextoumbourou/txstripe | txstripe/resource.py | Recipient.transfers | def transfers(self, **params):
"""Return a deferred."""
params['recipient'] = self.id
return Transfer.all(self.api_key, **params) | python | def transfers(self, **params):
"""Return a deferred."""
params['recipient'] = self.id
return Transfer.all(self.api_key, **params) | [
"def",
"transfers",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'recipient'",
"]",
"=",
"self",
".",
"id",
"return",
"Transfer",
".",
"all",
"(",
"self",
".",
"api_key",
",",
"*",
"*",
"params",
")"
] | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L548-L551 |
lextoumbourou/txstripe | txstripe/resource.py | ApplicationFee.refund | def refund(self, idempotency_key=None, **params):
"""Return a deferred."""
headers = populate_headers(idempotency_key)
url = self.instance_url() + '/refund'
d = self.request('post', url, params, headers)
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | python | def refund(self, idempotency_key=None, **params):
"""Return a deferred."""
headers = populate_headers(idempotency_key)
url = self.instance_url() + '/refund'
d = self.request('post', url, params, headers)
return d.addCallback(self.refresh_from).addCallback(lambda _: self) | [
"def",
"refund",
"(",
"self",
",",
"idempotency_key",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"headers",
"=",
"populate_headers",
"(",
"idempotency_key",
")",
"url",
"=",
"self",
".",
"instance_url",
"(",
")",
"+",
"'/refund'",
"d",
"=",
"self",
... | Return a deferred. | [
"Return",
"a",
"deferred",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L584-L589 |
lextoumbourou/txstripe | txstripe/resource.py | ApplicationFeeRefund.retrieve | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(ApplicationFeeRefund, cls).retrieve(*args, **kwargs) | python | def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(ApplicationFeeRefund, cls).retrieve(*args, **kwargs) | [
"def",
"retrieve",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApplicationFeeRefund",
",",
"cls",
")",
".",
"retrieve",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return parent method. | [
"Return",
"parent",
"method",
"."
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/txstripe/resource.py#L601-L603 |
mrstephenneal/dirutility | dirutility/move.py | move_files_to_folders | def move_files_to_folders(directory):
"""
Loops through a parent directory and nests files within folders that already exists and have matching prefixs
:param directory: Starting directory
"""
# Generate lists of files and folders in root directory
files, folders, files_to_move = [], [], []
... | python | def move_files_to_folders(directory):
"""
Loops through a parent directory and nests files within folders that already exists and have matching prefixs
:param directory: Starting directory
"""
# Generate lists of files and folders in root directory
files, folders, files_to_move = [], [], []
... | [
"def",
"move_files_to_folders",
"(",
"directory",
")",
":",
"# Generate lists of files and folders in root directory",
"files",
",",
"folders",
",",
"files_to_move",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"... | Loops through a parent directory and nests files within folders that already exists and have matching prefixs
:param directory: Starting directory | [
"Loops",
"through",
"a",
"parent",
"directory",
"and",
"nests",
"files",
"within",
"folders",
"that",
"already",
"exists",
"and",
"have",
"matching",
"prefixs",
":",
"param",
"directory",
":",
"Starting",
"directory"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/move.py#L87-L110 |
mrstephenneal/dirutility | dirutility/move.py | FlattenTree.remove_path_dirname | def remove_path_dirname(path):
"""
Removes file paths directory if the directory is empty
:param path: Filepath
"""
dir_to_remove = os.path.dirname(path)
if not os.listdir(dir_to_remove):
shutil.rmtree(dir_to_remove)
else:
if len(os.listdir... | python | def remove_path_dirname(path):
"""
Removes file paths directory if the directory is empty
:param path: Filepath
"""
dir_to_remove = os.path.dirname(path)
if not os.listdir(dir_to_remove):
shutil.rmtree(dir_to_remove)
else:
if len(os.listdir... | [
"def",
"remove_path_dirname",
"(",
"path",
")",
":",
"dir_to_remove",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"listdir",
"(",
"dir_to_remove",
")",
":",
"shutil",
".",
"rmtree",
"(",
"dir_to_remove",
")",
"else",... | Removes file paths directory if the directory is empty
:param path: Filepath | [
"Removes",
"file",
"paths",
"directory",
"if",
"the",
"directory",
"is",
"empty",
":",
"param",
"path",
":",
"Filepath"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/move.py#L24-L35 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.parse_arguments | def parse_arguments(arguments=sys.argv[1:]):
"""
Process command line arguments
:param: List of strings containing command line arguments, defaults to sys.argv[1:]
:return: docopt args object
"""
args = docopt.docopt(doc="""
Smart File Sorter
Usage:
sfp RULEFILE DIRECT... | python | def parse_arguments(arguments=sys.argv[1:]):
"""
Process command line arguments
:param: List of strings containing command line arguments, defaults to sys.argv[1:]
:return: docopt args object
"""
args = docopt.docopt(doc="""
Smart File Sorter
Usage:
sfp RULEFILE DIRECT... | [
"def",
"parse_arguments",
"(",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"args",
"=",
"docopt",
".",
"docopt",
"(",
"doc",
"=",
"\"\"\"\nSmart File Sorter\n\nUsage:\n sfp RULEFILE DIRECTORY [--debug] [--dry-run] [--log LOGFILE]\n sfp [--debug] ... | Process command line arguments
:param: List of strings containing command line arguments, defaults to sys.argv[1:]
:return: docopt args object | [
"Process",
"command",
"line",
"arguments",
":",
"param",
":",
"List",
"of",
"strings",
"containing",
"command",
"line",
"arguments",
"defaults",
"to",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"return",
":",
"docopt",
"args",
"object"
] | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L22-L43 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.create_logger | def create_logger(self, args={}):
"""
Create and configure the program's logger object.
Log levels:
DEBUG - Log everything. Hidden unless --debug is used.
INFO - information only
ERROR - Critical error
:param args: Object containing program's parsed command line ... | python | def create_logger(self, args={}):
"""
Create and configure the program's logger object.
Log levels:
DEBUG - Log everything. Hidden unless --debug is used.
INFO - information only
ERROR - Critical error
:param args: Object containing program's parsed command line ... | [
"def",
"create_logger",
"(",
"self",
",",
"args",
"=",
"{",
"}",
")",
":",
"# Set up logging",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"SmartFileSorter\"",
")",
"logger",
".",
"level",
"=",
"logging",
".",
"INFO",
"if",
"'--debug'",
"in",
"args"... | Create and configure the program's logger object.
Log levels:
DEBUG - Log everything. Hidden unless --debug is used.
INFO - information only
ERROR - Critical error
:param args: Object containing program's parsed command line arguments
:return: None | [
"Create",
"and",
"configure",
"the",
"program",
"s",
"logger",
"object",
"."
] | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L45-L81 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.get_files | def get_files(self, path):
"""
Yields full path and filename for each file that exists in the given directory. Will
ignore hidden files (that start with a ".") and directories
:param path: Directory or filename
:return:
"""
if os.path.isfile(path):
se... | python | def get_files(self, path):
"""
Yields full path and filename for each file that exists in the given directory. Will
ignore hidden files (that start with a ".") and directories
:param path: Directory or filename
:return:
"""
if os.path.isfile(path):
se... | [
"def",
"get_files",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Called with single file as target: {0}'",
".",
"format",
"(",
"path",
")",
")",
"yield",
... | Yields full path and filename for each file that exists in the given directory. Will
ignore hidden files (that start with a ".") and directories
:param path: Directory or filename
:return: | [
"Yields",
"full",
"path",
"and",
"filename",
"for",
"each",
"file",
"that",
"exists",
"in",
"the",
"given",
"directory",
".",
"Will",
"ignore",
"hidden",
"files",
"(",
"that",
"start",
"with",
"a",
".",
")",
"and",
"directories",
":",
"param",
"path",
":... | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L83-L105 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.load_rules | def load_rules(self, filename):
"""
Load rules from YAML configuration in the given stream object
:param filename: Filename of rule YAML file
:return: rules object
"""
self.logger.debug('Reading rules from %s', filename)
try:
in_file = open(filename)
... | python | def load_rules(self, filename):
"""
Load rules from YAML configuration in the given stream object
:param filename: Filename of rule YAML file
:return: rules object
"""
self.logger.debug('Reading rules from %s', filename)
try:
in_file = open(filename)
... | [
"def",
"load_rules",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Reading rules from %s'",
",",
"filename",
")",
"try",
":",
"in_file",
"=",
"open",
"(",
"filename",
")",
"except",
"IOError",
":",
"self",
".",
"logg... | Load rules from YAML configuration in the given stream object
:param filename: Filename of rule YAML file
:return: rules object | [
"Load",
"rules",
"from",
"YAML",
"configuration",
"in",
"the",
"given",
"stream",
"object",
":",
"param",
"filename",
":",
"Filename",
"of",
"rule",
"YAML",
"file",
":",
"return",
":",
"rules",
"object"
] | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L107-L130 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.load_plugins | def load_plugins(self, plugin_path):
"""
Loads plugins from modules in plugin_path. Looks for the config_name property
in each object that's found. If so, adds that to the dictionary with the
config_name as the key. config_name should be unique between different plugins.
:param ... | python | def load_plugins(self, plugin_path):
"""
Loads plugins from modules in plugin_path. Looks for the config_name property
in each object that's found. If so, adds that to the dictionary with the
config_name as the key. config_name should be unique between different plugins.
:param ... | [
"def",
"load_plugins",
"(",
"self",
",",
"plugin_path",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Loading plugins from {0}'",
".",
"format",
"(",
"plugin_path",
")",
")",
"plugins",
"=",
"{",
"}",
"plugin_dir",
"=",
"os",
".",
"path",
".",
"r... | Loads plugins from modules in plugin_path. Looks for the config_name property
in each object that's found. If so, adds that to the dictionary with the
config_name as the key. config_name should be unique between different plugins.
:param plugin_path: Path to load plugins from
:return: d... | [
"Loads",
"plugins",
"from",
"modules",
"in",
"plugin_path",
".",
"Looks",
"for",
"the",
"config_name",
"property",
"in",
"each",
"object",
"that",
"s",
"found",
".",
"If",
"so",
"adds",
"that",
"to",
"the",
"dictionary",
"with",
"the",
"config_name",
"as",
... | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L132-L178 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.build_rules | def build_rules(rule_yaml, match_plugins, action_plugins):
"""
Convert parsed rule YAML in to a list of ruleset objects
:param rule_yaml: Dictionary parsed from YAML rule file
:param match_plugins: Dictionary of match plugins (key=config_name, value=plugin object)
:param action_p... | python | def build_rules(rule_yaml, match_plugins, action_plugins):
"""
Convert parsed rule YAML in to a list of ruleset objects
:param rule_yaml: Dictionary parsed from YAML rule file
:param match_plugins: Dictionary of match plugins (key=config_name, value=plugin object)
:param action_p... | [
"def",
"build_rules",
"(",
"rule_yaml",
",",
"match_plugins",
",",
"action_plugins",
")",
":",
"rule_sets",
"=",
"[",
"]",
"for",
"yaml_section",
"in",
"rule_yaml",
":",
"rule_sets",
".",
"append",
"(",
"RuleSet",
"(",
"yaml_section",
",",
"match_plugins",
"="... | Convert parsed rule YAML in to a list of ruleset objects
:param rule_yaml: Dictionary parsed from YAML rule file
:param match_plugins: Dictionary of match plugins (key=config_name, value=plugin object)
:param action_plugins: Dictionary of action plugins (key=config_name, value=plugin object)
... | [
"Convert",
"parsed",
"rule",
"YAML",
"in",
"to",
"a",
"list",
"of",
"ruleset",
"objects",
":",
"param",
"rule_yaml",
":",
"Dictionary",
"parsed",
"from",
"YAML",
"rule",
"file",
":",
"param",
"match_plugins",
":",
"Dictionary",
"of",
"match",
"plugins",
"(",... | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L181-L193 |
jashort/SmartFileSorter | smartfilesorter/smartfilesorter.py | SmartFileSorter.run | def run(self, args):
"""
Load plugins and run with the configuration given in args
:param args: Object containing program's parsed command line arguments
:return: None
"""
module_dir = os.path.dirname(__file__)
self.match_plugins = self.load_plugins(os.path.join(m... | python | def run(self, args):
"""
Load plugins and run with the configuration given in args
:param args: Object containing program's parsed command line arguments
:return: None
"""
module_dir = os.path.dirname(__file__)
self.match_plugins = self.load_plugins(os.path.join(m... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"self",
".",
"match_plugins",
"=",
"self",
".",
"load_plugins",
"(",
"os",
".",
"path",
".",
"join",
"(",
"module_dir",
",",... | Load plugins and run with the configuration given in args
:param args: Object containing program's parsed command line arguments
:return: None | [
"Load",
"plugins",
"and",
"run",
"with",
"the",
"configuration",
"given",
"in",
"args",
":",
"param",
"args",
":",
"Object",
"containing",
"program",
"s",
"parsed",
"command",
"line",
"arguments",
":",
"return",
":",
"None"
] | train | https://github.com/jashort/SmartFileSorter/blob/77faf09e5a737da93e16e71a64707366b8307910/smartfilesorter/smartfilesorter.py#L195-L239 |
boatd/python-boatd | boatdclient/bearing.py | Bearing.delta | def delta(self, other):
'''
Return the error between this and another bearing. This will be an
angle in degrees, positive or negative depending on the direction of
the error.
self other
\ /
\ /
\__/
... | python | def delta(self, other):
'''
Return the error between this and another bearing. This will be an
angle in degrees, positive or negative depending on the direction of
the error.
self other
\ /
\ /
\__/
... | [
"def",
"delta",
"(",
"self",
",",
"other",
")",
":",
"difference",
"=",
"float",
"(",
"other",
")",
"-",
"float",
"(",
"self",
")",
"while",
"difference",
"<",
"-",
"180",
":",
"difference",
"+=",
"360",
"while",
"difference",
">",
"180",
":",
"diffe... | Return the error between this and another bearing. This will be an
angle in degrees, positive or negative depending on the direction of
the error.
self other
\ /
\ /
\__/
\/ <- angle will be +ve
oth... | [
"Return",
"the",
"error",
"between",
"this",
"and",
"another",
"bearing",
".",
"This",
"will",
"be",
"an",
"angle",
"in",
"degrees",
"positive",
"or",
"negative",
"depending",
"on",
"the",
"direction",
"of",
"the",
"error",
".",
"self",
"other",
"\\",
"/",... | train | https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/bearing.py#L38-L67 |
klmitch/appathy | appathy/actions.py | ActionDescriptor.deserialize_request | def deserialize_request(self, req):
"""
Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported.
... | python | def deserialize_request(self, req):
"""
Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported.
... | [
"def",
"deserialize_request",
"(",
"self",
",",
"req",
")",
":",
"# See if we have a body",
"if",
"req",
".",
"content_length",
"==",
"0",
":",
"return",
"None",
"# Get the primary deserializer",
"try",
":",
"deserializer",
"=",
"self",
".",
"method",
".",
"dese... | Uses the deserializers declared on the action method and its
extensions to deserialize the request. Returns the result of
the deserialization. Raises `webob.HTTPUnsupportedMediaType`
if the media type of the request is unsupported. | [
"Uses",
"the",
"deserializers",
"declared",
"on",
"the",
"action",
"method",
"and",
"its",
"extensions",
"to",
"deserialize",
"the",
"request",
".",
"Returns",
"the",
"result",
"of",
"the",
"deserialization",
".",
"Raises",
"webob",
".",
"HTTPUnsupportedMediaType"... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L99-L127 |
klmitch/appathy | appathy/actions.py | ActionDescriptor.serializer | def serializer(self, req):
"""
Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
head... | python | def serializer(self, req):
"""
Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
head... | [
"def",
"serializer",
"(",
"self",
",",
"req",
")",
":",
"# Select the best match serializer",
"content_types",
"=",
"self",
".",
"method",
".",
"serializers",
".",
"get_types",
"(",
")",
"content_type",
"=",
"req",
".",
"accept",
".",
"best_match",
"(",
"conte... | Selects and returns the serializer to use, based on the
serializers declared on the action method and its extensions.
The returned content type is selected based on the types
available and the best match generated from the HTTP `Accept`
header. Raises `HTTPNotAcceptable` if the request ... | [
"Selects",
"and",
"returns",
"the",
"serializer",
"to",
"use",
"based",
"on",
"the",
"serializers",
"declared",
"on",
"the",
"action",
"method",
"and",
"its",
"extensions",
".",
"The",
"returned",
"content",
"type",
"is",
"selected",
"based",
"on",
"the",
"t... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L129-L162 |
klmitch/appathy | appathy/actions.py | ActionDescriptor.pre_process | def pre_process(self, req, params):
"""
Pre-process the extensions for the action. If any
pre-processing extension yields a value which tests as True,
extension pre-processing aborts and that value is returned;
otherwise, None is returned. Return value is always a tuple,
... | python | def pre_process(self, req, params):
"""
Pre-process the extensions for the action. If any
pre-processing extension yields a value which tests as True,
extension pre-processing aborts and that value is returned;
otherwise, None is returned. Return value is always a tuple,
... | [
"def",
"pre_process",
"(",
"self",
",",
"req",
",",
"params",
")",
":",
"post_list",
"=",
"[",
"]",
"# Walk through the list of extensions",
"for",
"ext",
"in",
"self",
".",
"extensions",
":",
"if",
"ext",
".",
"isgenerator",
":",
"gen",
"=",
"ext",
"(",
... | Pre-process the extensions for the action. If any
pre-processing extension yields a value which tests as True,
extension pre-processing aborts and that value is returned;
otherwise, None is returned. Return value is always a tuple,
with the second element of the tuple being a list to f... | [
"Pre",
"-",
"process",
"the",
"extensions",
"for",
"the",
"action",
".",
"If",
"any",
"pre",
"-",
"processing",
"extension",
"yields",
"a",
"value",
"which",
"tests",
"as",
"True",
"extension",
"pre",
"-",
"processing",
"aborts",
"and",
"that",
"value",
"i... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L164-L196 |
klmitch/appathy | appathy/actions.py | ActionDescriptor.post_process | def post_process(self, post_list, req, resp, params):
"""
Post-process the extensions for the action. If any
post-processing extension (specified by `post_list`, which
should be generated by the pre_process() method) yields a
value which tests as True, the response being conside... | python | def post_process(self, post_list, req, resp, params):
"""
Post-process the extensions for the action. If any
post-processing extension (specified by `post_list`, which
should be generated by the pre_process() method) yields a
value which tests as True, the response being conside... | [
"def",
"post_process",
"(",
"self",
",",
"post_list",
",",
"req",
",",
"resp",
",",
"params",
")",
":",
"# Walk through the post-processing extensions",
"for",
"ext",
"in",
"post_list",
":",
"if",
"inspect",
".",
"isgenerator",
"(",
"ext",
")",
":",
"try",
"... | Post-process the extensions for the action. If any
post-processing extension (specified by `post_list`, which
should be generated by the pre_process() method) yields a
value which tests as True, the response being considered by
post-processing extensions is updated to be that value.
... | [
"Post",
"-",
"process",
"the",
"extensions",
"for",
"the",
"action",
".",
"If",
"any",
"post",
"-",
"processing",
"extension",
"(",
"specified",
"by",
"post_list",
"which",
"should",
"be",
"generated",
"by",
"the",
"pre_process",
"()",
"method",
")",
"yields... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L198-L229 |
klmitch/appathy | appathy/actions.py | ActionDescriptor.wrap | def wrap(self, req, result):
"""
Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
e... | python | def wrap(self, req, result):
"""
Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
e... | [
"def",
"wrap",
"(",
"self",
",",
"req",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"webob",
".",
"exc",
".",
"HTTPException",
")",
":",
"# It's a webob HTTP exception; use raise to bail out",
"# immediately and pass it upstream",
"raise",
"resu... | Wrap method return results. The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller. Instances of
`webob.Response` are thrown, to abort the rest of action and
extension processing; otherwise, objects which are... | [
"Wrap",
"method",
"return",
"results",
".",
"The",
"return",
"value",
"of",
"the",
"action",
"method",
"and",
"of",
"the",
"action",
"extensions",
"is",
"passed",
"through",
"this",
"method",
"before",
"being",
"returned",
"to",
"the",
"caller",
".",
"Instan... | train | https://github.com/klmitch/appathy/blob/a10aa7d21d38622e984a8fe106ab37114af90dc2/appathy/actions.py#L231-L255 |
bitlabstudio/django-outlets | outlets/models.py | OutletManager.active | def active(self):
"""Returns all outlets that are currently active and have sales."""
qs = self.get_queryset()
return qs.filter(
models.Q(
models.Q(start_date__isnull=True) |
models.Q(start_date__lte=now().date())
) &
models.Q(
... | python | def active(self):
"""Returns all outlets that are currently active and have sales."""
qs = self.get_queryset()
return qs.filter(
models.Q(
models.Q(start_date__isnull=True) |
models.Q(start_date__lte=now().date())
) &
models.Q(
... | [
"def",
"active",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"models",
".",
"Q",
"(",
"models",
".",
"Q",
"(",
"start_date__isnull",
"=",
"True",
")",
"|",
"models",
".",
"Q",
"(",
... | Returns all outlets that are currently active and have sales. | [
"Returns",
"all",
"outlets",
"that",
"are",
"currently",
"active",
"and",
"have",
"sales",
"."
] | train | https://github.com/bitlabstudio/django-outlets/blob/eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228/outlets/models.py#L14-L26 |
bitlabstudio/django-outlets | outlets/models.py | OutletManager.future | def future(self):
"""Returns all outlets that are or will be active."""
qs = self.get_queryset()
return qs.filter(
models.Q(end_date__isnull=True) |
models.Q(end_date__gte=now().date())
) | python | def future(self):
"""Returns all outlets that are or will be active."""
qs = self.get_queryset()
return qs.filter(
models.Q(end_date__isnull=True) |
models.Q(end_date__gte=now().date())
) | [
"def",
"future",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"models",
".",
"Q",
"(",
"end_date__isnull",
"=",
"True",
")",
"|",
"models",
".",
"Q",
"(",
"end_date__gte",
"=",
"now",
... | Returns all outlets that are or will be active. | [
"Returns",
"all",
"outlets",
"that",
"are",
"or",
"will",
"be",
"active",
"."
] | train | https://github.com/bitlabstudio/django-outlets/blob/eaecc1e8ef8fb48d6dc5886b321d9e3b0359b228/outlets/models.py#L28-L34 |
political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | _get_path | def _get_path(dict_, path):
'''
Get value at specific path in dictionary. Path is specified by slash-
separated string, eg _get_path(foo, 'bar/baz') returns foo['bar']['baz']
'''
cur = dict_
for part in path.split('/'):
cur = cur[part]
return cur | python | def _get_path(dict_, path):
'''
Get value at specific path in dictionary. Path is specified by slash-
separated string, eg _get_path(foo, 'bar/baz') returns foo['bar']['baz']
'''
cur = dict_
for part in path.split('/'):
cur = cur[part]
return cur | [
"def",
"_get_path",
"(",
"dict_",
",",
"path",
")",
":",
"cur",
"=",
"dict_",
"for",
"part",
"in",
"path",
".",
"split",
"(",
"'/'",
")",
":",
"cur",
"=",
"cur",
"[",
"part",
"]",
"return",
"cur"
] | Get value at specific path in dictionary. Path is specified by slash-
separated string, eg _get_path(foo, 'bar/baz') returns foo['bar']['baz'] | [
"Get",
"value",
"at",
"specific",
"path",
"in",
"dictionary",
".",
"Path",
"is",
"specified",
"by",
"slash",
"-",
"separated",
"string",
"eg",
"_get_path",
"(",
"foo",
"bar",
"/",
"baz",
")",
"returns",
"foo",
"[",
"bar",
"]",
"[",
"baz",
"]"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L63-L71 |
political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | ensure_chambers | def ensure_chambers():
"""
Ensures chambers are created
"""
france = Country.objects.get(name="France")
for key in ('AN', 'SEN'):
variant = FranceDataVariants[key]
Chamber.objects.get_or_create(name=variant['chamber'],
abbreviation=variant['abbre... | python | def ensure_chambers():
"""
Ensures chambers are created
"""
france = Country.objects.get(name="France")
for key in ('AN', 'SEN'):
variant = FranceDataVariants[key]
Chamber.objects.get_or_create(name=variant['chamber'],
abbreviation=variant['abbre... | [
"def",
"ensure_chambers",
"(",
")",
":",
"france",
"=",
"Country",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"\"France\"",
")",
"for",
"key",
"in",
"(",
"'AN'",
",",
"'SEN'",
")",
":",
"variant",
"=",
"FranceDataVariants",
"[",
"key",
"]",
"Chamber... | Ensures chambers are created | [
"Ensures",
"chambers",
"are",
"created"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L95-L104 |
political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | GenericImporter.touch_model | def touch_model(self, model, **data):
'''
This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field
'''
instance, created = model.objects.get_or_create(**data)
if not created:
if insta... | python | def touch_model(self, model, **data):
'''
This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field
'''
instance, created = model.objects.get_or_create(**data)
if not created:
if insta... | [
"def",
"touch_model",
"(",
"self",
",",
"model",
",",
"*",
"*",
"data",
")",
":",
"instance",
",",
"created",
"=",
"model",
".",
"objects",
".",
"get_or_create",
"(",
"*",
"*",
"data",
")",
"if",
"not",
"created",
":",
"if",
"instance",
".",
"updated... | This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field | [
"This",
"method",
"create",
"or",
"look",
"up",
"a",
"model",
"with",
"the",
"given",
"data",
"it",
"saves",
"the",
"given",
"model",
"if",
"it",
"exists",
"updating",
"its",
"updated",
"field"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L79-L92 |
political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | FranceDataImporter.manage_rep | def manage_rep(self, rep_json):
'''
Import a rep as a representative from the json dict fetched from
FranceData (which comes from nosdeputes.fr)
'''
# Some versions of memopol will connect to this and skip inactive reps.
responses = representative_pre_import.send(sender=... | python | def manage_rep(self, rep_json):
'''
Import a rep as a representative from the json dict fetched from
FranceData (which comes from nosdeputes.fr)
'''
# Some versions of memopol will connect to this and skip inactive reps.
responses = representative_pre_import.send(sender=... | [
"def",
"manage_rep",
"(",
"self",
",",
"rep_json",
")",
":",
"# Some versions of memopol will connect to this and skip inactive reps.",
"responses",
"=",
"representative_pre_import",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"representative_data",
"=",
"rep_json",
")"... | Import a rep as a representative from the json dict fetched from
FranceData (which comes from nosdeputes.fr) | [
"Import",
"a",
"rep",
"as",
"a",
"representative",
"from",
"the",
"json",
"dict",
"fetched",
"from",
"FranceData",
"(",
"which",
"comes",
"from",
"nosdeputes",
".",
"fr",
")"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L121-L162 |
political-memory/django-representatives | representatives/contrib/francedata/import_representatives.py | FranceDataImporter.add_mandates | def add_mandates(self, representative, rep_json):
'''
Create mandates from rep data based on variant configuration
'''
# Mandate in country group for party constituency
if rep_json.get('parti_ratt_financier'):
constituency, _ = Constituency.objects.get_or_create(
... | python | def add_mandates(self, representative, rep_json):
'''
Create mandates from rep data based on variant configuration
'''
# Mandate in country group for party constituency
if rep_json.get('parti_ratt_financier'):
constituency, _ = Constituency.objects.get_or_create(
... | [
"def",
"add_mandates",
"(",
"self",
",",
"representative",
",",
"rep_json",
")",
":",
"# Mandate in country group for party constituency",
"if",
"rep_json",
".",
"get",
"(",
"'parti_ratt_financier'",
")",
":",
"constituency",
",",
"_",
"=",
"Constituency",
".",
"obj... | Create mandates from rep data based on variant configuration | [
"Create",
"mandates",
"from",
"rep",
"data",
"based",
"on",
"variant",
"configuration"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/contrib/francedata/import_representatives.py#L218-L270 |
hobson/pug-dj | pug/dj/crawlnmine/crawlnmine/settings/master_common.py | env | def env(var_name, default=False):
""" Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable."""
try:
value = os.environ[var_name]
if str(value).strip().lower() in ['false', 'f', 'no', 'off' '0', 'none', 'null', '', ]:
... | python | def env(var_name, default=False):
""" Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable."""
try:
value = os.environ[var_name]
if str(value).strip().lower() in ['false', 'f', 'no', 'off' '0', 'none', 'null', '', ]:
... | [
"def",
"env",
"(",
"var_name",
",",
"default",
"=",
"False",
")",
":",
"try",
":",
"value",
"=",
"os",
".",
"environ",
"[",
"var_name",
"]",
"if",
"str",
"(",
"value",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'false'",
"... | Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable. | [
"Get",
"the",
"environment",
"variable",
".",
"If",
"not",
"found",
"use",
"a",
"default",
"or",
"False",
"but",
"print",
"to",
"stderr",
"a",
"warning",
"about",
"the",
"missing",
"env",
"variable",
"."
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/crawlnmine/settings/master_common.py#L21-L33 |
davisd50/sparc.db | sparc/db/splunk/kvstore.py | current_kv_names | def current_kv_names(sci, app_user, app_name, request=None):
"""Return set of string names of current available Splunk KV collections
Args:
sci: Instance of sparc.db.splunk.ISplunkConnectionInfo
app_user: Splunk KV Collection app user to reference
app_name: Splunk KV Collection appl... | python | def current_kv_names(sci, app_user, app_name, request=None):
"""Return set of string names of current available Splunk KV collections
Args:
sci: Instance of sparc.db.splunk.ISplunkConnectionInfo
app_user: Splunk KV Collection app user to reference
app_name: Splunk KV Collection appl... | [
"def",
"current_kv_names",
"(",
"sci",
",",
"app_user",
",",
"app_name",
",",
"request",
"=",
"None",
")",
":",
"resolver",
"=",
"sm",
".",
"getUtility",
"(",
"IRequest",
",",
"u'sparc.utils.requests.request_resolver'",
")",
"req",
"=",
"resolver",
"(",
"reque... | Return set of string names of current available Splunk KV collections
Args:
sci: Instance of sparc.db.splunk.ISplunkConnectionInfo
app_user: Splunk KV Collection app user to reference
app_name: Splunk KV Collection application name to reference
kwargs:
request: instance of s... | [
"Return",
"set",
"of",
"string",
"names",
"of",
"current",
"available",
"Splunk",
"KV",
"collections",
"Args",
":",
"sci",
":",
"Instance",
"of",
"sparc",
".",
"db",
".",
"splunk",
".",
"ISplunkConnectionInfo",
"app_user",
":",
"Splunk",
"KV",
"Collection",
... | train | https://github.com/davisd50/sparc.db/blob/12dfcb51f7bdc4fbe9c8ec3b5af65059c1f66392/sparc/db/splunk/kvstore.py#L23-L54 |
esterhui/pypu | scripts/build_json_from_gps.py | lookupfile | def lookupfile(filename):
"""Returns dictionary of file content as well
as google reverse GEO data"""
logger.info('Looking up %s'%(filename))
# First open cache file to see if we already looked up this stuff
dirname=os.path.dirname(filename)
basefilename=os.path.basename(filename)
CACHE_F... | python | def lookupfile(filename):
"""Returns dictionary of file content as well
as google reverse GEO data"""
logger.info('Looking up %s'%(filename))
# First open cache file to see if we already looked up this stuff
dirname=os.path.dirname(filename)
basefilename=os.path.basename(filename)
CACHE_F... | [
"def",
"lookupfile",
"(",
"filename",
")",
":",
"logger",
".",
"info",
"(",
"'Looking up %s'",
"%",
"(",
"filename",
")",
")",
"# First open cache file to see if we already looked up this stuff",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
... | Returns dictionary of file content as well
as google reverse GEO data | [
"Returns",
"dictionary",
"of",
"file",
"content",
"as",
"well",
"as",
"google",
"reverse",
"GEO",
"data"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_gps.py#L75-L101 |
esterhui/pypu | scripts/build_json_from_gps.py | lookup_by_latlon | def lookup_by_latlon(lat,lon):
"""Looks up location given lat,lon
returns dictionary with address:
d['street number'] : 1925
d['route'] : Illinois Dr
d['city'] : South Pasadena
d['admin area 2'] : Los Angeles County
d['admin area 1'] : California
d['country'] ... | python | def lookup_by_latlon(lat,lon):
"""Looks up location given lat,lon
returns dictionary with address:
d['street number'] : 1925
d['route'] : Illinois Dr
d['city'] : South Pasadena
d['admin area 2'] : Los Angeles County
d['admin area 1'] : California
d['country'] ... | [
"def",
"lookup_by_latlon",
"(",
"lat",
",",
"lon",
")",
":",
"logger",
".",
"info",
"(",
"\"Looking up %s/%s via google\"",
"%",
"(",
"lat",
",",
"lon",
")",
")",
"results",
"=",
"Geocoder",
".",
"reverse_geocode",
"(",
"float",
"(",
"lat",
")",
",",
"fl... | Looks up location given lat,lon
returns dictionary with address:
d['street number'] : 1925
d['route'] : Illinois Dr
d['city'] : South Pasadena
d['admin area 2'] : Los Angeles County
d['admin area 1'] : California
d['country'] : USA
d['postal_code'] : 910... | [
"Looks",
"up",
"location",
"given",
"lat",
"lon",
"returns",
"dictionary",
"with",
"address",
":",
"d",
"[",
"street",
"number",
"]",
":",
"1925",
"d",
"[",
"route",
"]",
":",
"Illinois",
"Dr",
"d",
"[",
"city",
"]",
":",
"South",
"Pasadena",
"d",
"[... | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_gps.py#L115-L152 |
esterhui/pypu | scripts/build_json_from_gps.py | parsePositionFile | def parsePositionFile(filename):
"""
Parses Android GPS logger csv file and returns list of dictionaries
"""
l=[]
with open( filename, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# Convert the time string to something
# a bit more... | python | def parsePositionFile(filename):
"""
Parses Android GPS logger csv file and returns list of dictionaries
"""
l=[]
with open( filename, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# Convert the time string to something
# a bit more... | [
"def",
"parsePositionFile",
"(",
"filename",
")",
":",
"l",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"theFile",
":",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"theFile",
")",
"for",
"line",
"in",
"reader",
":",
"#... | Parses Android GPS logger csv file and returns list of dictionaries | [
"Parses",
"Android",
"GPS",
"logger",
"csv",
"file",
"and",
"returns",
"list",
"of",
"dictionaries"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_gps.py#L154-L167 |
esterhui/pypu | scripts/build_json_from_gps.py | lookupGeoInfo | def lookupGeoInfo(positions):
"""Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary
"""
list_data=[]
oldlat=0
oldlon=0
d={}
for pos in positions:
# Only lookup point if it is above threshold
... | python | def lookupGeoInfo(positions):
"""Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary
"""
list_data=[]
oldlat=0
oldlon=0
d={}
for pos in positions:
# Only lookup point if it is above threshold
... | [
"def",
"lookupGeoInfo",
"(",
"positions",
")",
":",
"list_data",
"=",
"[",
"]",
"oldlat",
"=",
"0",
"oldlon",
"=",
"0",
"d",
"=",
"{",
"}",
"for",
"pos",
"in",
"positions",
":",
"# Only lookup point if it is above threshold",
"diff_lat",
"=",
"abs",
"(",
"... | Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary | [
"Looks",
"up",
"lat",
"/",
"lon",
"info",
"with",
"goole",
"given",
"a",
"list",
"of",
"positions",
"as",
"parsed",
"by",
"parsePositionFile",
".",
"Returns",
"google",
"results",
"in",
"form",
"of",
"dicionary"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_gps.py#L169-L194 |
datakortet/dkfileutils | dkfileutils/changed.py | digest | def digest(dirname, glob=None):
"""Returns the md5 digest of all interesting files (or glob) in `dirname`.
"""
md5 = hashlib.md5()
if glob is None:
fnames = [fname for _, fname in list_files(Path(dirname))]
for fname in sorted(fnames):
fname = os.path.join(dirname, fname)
... | python | def digest(dirname, glob=None):
"""Returns the md5 digest of all interesting files (or glob) in `dirname`.
"""
md5 = hashlib.md5()
if glob is None:
fnames = [fname for _, fname in list_files(Path(dirname))]
for fname in sorted(fnames):
fname = os.path.join(dirname, fname)
... | [
"def",
"digest",
"(",
"dirname",
",",
"glob",
"=",
"None",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"if",
"glob",
"is",
"None",
":",
"fnames",
"=",
"[",
"fname",
"for",
"_",
",",
"fname",
"in",
"list_files",
"(",
"Path",
"(",
"dirna... | Returns the md5 digest of all interesting files (or glob) in `dirname`. | [
"Returns",
"the",
"md5",
"digest",
"of",
"all",
"interesting",
"files",
"(",
"or",
"glob",
")",
"in",
"dirname",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L12-L25 |
datakortet/dkfileutils | dkfileutils/changed.py | changed | def changed(dirname, filename='.md5', args=None, glob=None):
"""Has `glob` changed in `dirname`
Args:
dirname: directory to measure
filename: filename to store checksum
"""
root = Path(dirname)
if not root.exists():
# if dirname doesn't exist it is changed (by definition)
... | python | def changed(dirname, filename='.md5', args=None, glob=None):
"""Has `glob` changed in `dirname`
Args:
dirname: directory to measure
filename: filename to store checksum
"""
root = Path(dirname)
if not root.exists():
# if dirname doesn't exist it is changed (by definition)
... | [
"def",
"changed",
"(",
"dirname",
",",
"filename",
"=",
"'.md5'",
",",
"args",
"=",
"None",
",",
"glob",
"=",
"None",
")",
":",
"root",
"=",
"Path",
"(",
"dirname",
")",
"if",
"not",
"root",
".",
"exists",
"(",
")",
":",
"# if dirname doesn't exist it ... | Has `glob` changed in `dirname`
Args:
dirname: directory to measure
filename: filename to store checksum | [
"Has",
"glob",
"changed",
"in",
"dirname"
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L28-L52 |
datakortet/dkfileutils | dkfileutils/changed.py | main | def main(): # pragma: nocover
"""Return exit code of zero iff directory is not changed.
"""
p = argparse.ArgumentParser()
p.add_argument(
'directory',
help="Directory to check"
)
p.add_argument(
'--verbose', '-v', action='store_true',
help="increase verbosity"
... | python | def main(): # pragma: nocover
"""Return exit code of zero iff directory is not changed.
"""
p = argparse.ArgumentParser()
p.add_argument(
'directory',
help="Directory to check"
)
p.add_argument(
'--verbose', '-v', action='store_true',
help="increase verbosity"
... | [
"def",
"main",
"(",
")",
":",
"# pragma: nocover",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"p",
".",
"add_argument",
"(",
"'directory'",
",",
"help",
"=",
"\"Directory to check\"",
")",
"p",
".",
"add_argument",
"(",
"'--verbose'",
",",
"'-v'"... | Return exit code of zero iff directory is not changed. | [
"Return",
"exit",
"code",
"of",
"zero",
"iff",
"directory",
"is",
"not",
"changed",
"."
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L67-L83 |
datakortet/dkfileutils | dkfileutils/changed.py | Directory.changed | def changed(self, filename='.md5', glob=None):
"""Are any of the files matched by ``glob`` changed?
"""
if glob is not None:
filename += '.glob-' + ''.join(ch.lower()
for ch in glob if ch.isalpha())
return changed(self, filename, glo... | python | def changed(self, filename='.md5', glob=None):
"""Are any of the files matched by ``glob`` changed?
"""
if glob is not None:
filename += '.glob-' + ''.join(ch.lower()
for ch in glob if ch.isalpha())
return changed(self, filename, glo... | [
"def",
"changed",
"(",
"self",
",",
"filename",
"=",
"'.md5'",
",",
"glob",
"=",
"None",
")",
":",
"if",
"glob",
"is",
"not",
"None",
":",
"filename",
"+=",
"'.glob-'",
"+",
"''",
".",
"join",
"(",
"ch",
".",
"lower",
"(",
")",
"for",
"ch",
"in",... | Are any of the files matched by ``glob`` changed? | [
"Are",
"any",
"of",
"the",
"files",
"matched",
"by",
"glob",
"changed?"
] | train | https://github.com/datakortet/dkfileutils/blob/924098d6e2edf88ad9b3ffdec9c74530f80a7d77/dkfileutils/changed.py#L58-L64 |
mikkeljans/pyconomic | pyconomic/client.py | EconomicsFacade.create_order | def create_order(self, debtor, is_vat_included=True, due_date=None,
heading='', text_line1='', text_line2='',
debtor_data=None, delivery_data=None, products=None,
project=None, other_reference='', model=models.Order, **extra
):
... | python | def create_order(self, debtor, is_vat_included=True, due_date=None,
heading='', text_line1='', text_line2='',
debtor_data=None, delivery_data=None, products=None,
project=None, other_reference='', model=models.Order, **extra
):
... | [
"def",
"create_order",
"(",
"self",
",",
"debtor",
",",
"is_vat_included",
"=",
"True",
",",
"due_date",
"=",
"None",
",",
"heading",
"=",
"''",
",",
"text_line1",
"=",
"''",
",",
"text_line2",
"=",
"''",
",",
"debtor_data",
"=",
"None",
",",
"delivery_d... | Create a new Order.
Args:
debtor (Debtor): the debtor of the order
debtor_data (mapping): map of debtor data {'postal_code: .., 'city': .., 'ean': ..}
defaults to values on debitor instance for missing values
delivery_data (mapping): map of... | [
"Create",
"a",
"new",
"Order",
"."
] | train | https://github.com/mikkeljans/pyconomic/blob/845b8148a364cf5be9065f8a70133d4f16ab645d/pyconomic/client.py#L61-L130 |
bwesterb/py-joyce | src/comet.py | CometJoyceServerRelay.__flush | def __flush(self, async=True):
""" Flushes messages through current HttpRequest and closes it.
It assumes a current requesthandler and requires a lock
on self.lock """
rh = self.rh
messages = list(self.messages)
stream_notices = list(self.stream_notices)
s... | python | def __flush(self, async=True):
""" Flushes messages through current HttpRequest and closes it.
It assumes a current requesthandler and requires a lock
on self.lock """
rh = self.rh
messages = list(self.messages)
stream_notices = list(self.stream_notices)
s... | [
"def",
"__flush",
"(",
"self",
",",
"async",
"=",
"True",
")",
":",
"rh",
"=",
"self",
".",
"rh",
"messages",
"=",
"list",
"(",
"self",
".",
"messages",
")",
"stream_notices",
"=",
"list",
"(",
"self",
".",
"stream_notices",
")",
"self",
".",
"stream... | Flushes messages through current HttpRequest and closes it.
It assumes a current requesthandler and requires a lock
on self.lock | [
"Flushes",
"messages",
"through",
"current",
"HttpRequest",
"and",
"closes",
"it",
".",
"It",
"assumes",
"a",
"current",
"requesthandler",
"and",
"requires",
"a",
"lock",
"on",
"self",
".",
"lock"
] | train | https://github.com/bwesterb/py-joyce/blob/ad1c99ad3939e70b247a18a1a0ef537b037979a0/src/comet.py#L280-L296 |
wtsi-hgi/gitlab-build-variables | gitlabbuildvariables/executables/_common.py | add_common_arguments | def add_common_arguments(parser: ArgumentParser, project: bool=False):
"""
Adds common arguments to the given argument parser.
:param parser: argument parser
:param url: whether the URL named argument should be added
:param token: whether the access token named argument should be added
:param pr... | python | def add_common_arguments(parser: ArgumentParser, project: bool=False):
"""
Adds common arguments to the given argument parser.
:param parser: argument parser
:param url: whether the URL named argument should be added
:param token: whether the access token named argument should be added
:param pr... | [
"def",
"add_common_arguments",
"(",
"parser",
":",
"ArgumentParser",
",",
"project",
":",
"bool",
"=",
"False",
")",
":",
"parser",
".",
"add_argument",
"(",
"\"--url\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Location of GitLab\"",
")",
"parser",
"."... | Adds common arguments to the given argument parser.
:param parser: argument parser
:param url: whether the URL named argument should be added
:param token: whether the access token named argument should be added
:param project: whether the project positional argument should be added | [
"Adds",
"common",
"arguments",
"to",
"the",
"given",
"argument",
"parser",
".",
":",
"param",
"parser",
":",
"argument",
"parser",
":",
"param",
"url",
":",
"whether",
"the",
"URL",
"named",
"argument",
"should",
"be",
"added",
":",
"param",
"token",
":",
... | train | https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/_common.py#L23-L35 |
pycontribs/pyversion | version/version.py | version_keyword | def version_keyword(dist, attr, value):
"""
Implements the actual version setup() keyword.
"""
if value == "PBR":
from pbr.util import setup_cfg_to_setup_kwargs
path = "setup.cfg"
parser = ConfigParser()
if not os.path.exists(path):
raise ValueError("file '%s... | python | def version_keyword(dist, attr, value):
"""
Implements the actual version setup() keyword.
"""
if value == "PBR":
from pbr.util import setup_cfg_to_setup_kwargs
path = "setup.cfg"
parser = ConfigParser()
if not os.path.exists(path):
raise ValueError("file '%s... | [
"def",
"version_keyword",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"PBR\"",
":",
"from",
"pbr",
".",
"util",
"import",
"setup_cfg_to_setup_kwargs",
"path",
"=",
"\"setup.cfg\"",
"parser",
"=",
"ConfigParser",
"(",
")",
"if",
... | Implements the actual version setup() keyword. | [
"Implements",
"the",
"actual",
"version",
"setup",
"()",
"keyword",
"."
] | train | https://github.com/pycontribs/pyversion/blob/6bbb799846ed4e97e84a3f0f2dbe14685f2ddb39/version/version.py#L15-L35 |
pycontribs/pyversion | version/version.py | VersionUtils.increment | def increment(version):
"""Return an incremented version string."""
release_version = os.environ.get("RELEASE_VERSION", None)
if release_version is not None:
return release_version
if isinstance(version, LegacyVersion):
msg = """{0} is considered a legacy version ... | python | def increment(version):
"""Return an incremented version string."""
release_version = os.environ.get("RELEASE_VERSION", None)
if release_version is not None:
return release_version
if isinstance(version, LegacyVersion):
msg = """{0} is considered a legacy version ... | [
"def",
"increment",
"(",
"version",
")",
":",
"release_version",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"RELEASE_VERSION\"",
",",
"None",
")",
"if",
"release_version",
"is",
"not",
"None",
":",
"return",
"release_version",
"if",
"isinstance",
"(",
"ve... | Return an incremented version string. | [
"Return",
"an",
"incremented",
"version",
"string",
"."
] | train | https://github.com/pycontribs/pyversion/blob/6bbb799846ed4e97e84a3f0f2dbe14685f2ddb39/version/version.py#L100-L174 |
maceoutliner/django-fiction-outlines | fiction_outlines/views.py | OutlineExport.return_opml_response | def return_opml_response(self, context, **response_kwargs):
'''
Returns export data as an opml file.
'''
self.template_name = 'fiction_outlines/outline.opml'
response = super().render_to_response(context, content_type='text/xml', **response_kwargs)
response['Content-Dispo... | python | def return_opml_response(self, context, **response_kwargs):
'''
Returns export data as an opml file.
'''
self.template_name = 'fiction_outlines/outline.opml'
response = super().render_to_response(context, content_type='text/xml', **response_kwargs)
response['Content-Dispo... | [
"def",
"return_opml_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"self",
".",
"template_name",
"=",
"'fiction_outlines/outline.opml'",
"response",
"=",
"super",
"(",
")",
".",
"render_to_response",
"(",
"context",
",",
"con... | Returns export data as an opml file. | [
"Returns",
"export",
"data",
"as",
"an",
"opml",
"file",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/views.py#L1261-L1268 |
maceoutliner/django-fiction-outlines | fiction_outlines/views.py | OutlineExport.not_implemented | def not_implemented(self, context, **response_kwargs):
'''
If DEBUG: raise NotImplemented Exception.
If not, raise 404.
:raises:`django.http.Http404` if production environment.
:raises:`NotImplementedError` if ``settings.DEBUG`` is True
'''
if settings.DEBUG:
... | python | def not_implemented(self, context, **response_kwargs):
'''
If DEBUG: raise NotImplemented Exception.
If not, raise 404.
:raises:`django.http.Http404` if production environment.
:raises:`NotImplementedError` if ``settings.DEBUG`` is True
'''
if settings.DEBUG:
... | [
"def",
"not_implemented",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"NotImplementedError",
"(",
"_",
"(",
"'This export type ({})is not yet supported.'",
".",
"format",
"(",
"self",
"."... | If DEBUG: raise NotImplemented Exception.
If not, raise 404.
:raises:`django.http.Http404` if production environment.
:raises:`NotImplementedError` if ``settings.DEBUG`` is True | [
"If",
"DEBUG",
":",
"raise",
"NotImplemented",
"Exception",
".",
"If",
"not",
"raise",
"404",
".",
":",
"raises",
":",
"django",
".",
"http",
".",
"Http404",
"if",
"production",
"environment",
".",
":",
"raises",
":",
"NotImplementedError",
"if",
"settings",... | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/views.py#L1270-L1279 |
maceoutliner/django-fiction-outlines | fiction_outlines/views.py | OutlineExport.return_json_response | def return_json_response(self, context, **request_kwargs):
'''
Returns detailed outline structure as :class:`django.http.JsonResponse`.
'''
outline_dict = model_to_dict(self.object)
logger.debug(str(outline_dict))
logger.debug("Attepting to switch tags from queryset to na... | python | def return_json_response(self, context, **request_kwargs):
'''
Returns detailed outline structure as :class:`django.http.JsonResponse`.
'''
outline_dict = model_to_dict(self.object)
logger.debug(str(outline_dict))
logger.debug("Attepting to switch tags from queryset to na... | [
"def",
"return_json_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"request_kwargs",
")",
":",
"outline_dict",
"=",
"model_to_dict",
"(",
"self",
".",
"object",
")",
"logger",
".",
"debug",
"(",
"str",
"(",
"outline_dict",
")",
")",
"logger",
".",
... | Returns detailed outline structure as :class:`django.http.JsonResponse`. | [
"Returns",
"detailed",
"outline",
"structure",
"as",
":",
"class",
":",
"django",
".",
"http",
".",
"JsonResponse",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/views.py#L1281-L1328 |
maceoutliner/django-fiction-outlines | fiction_outlines/views.py | OutlineExport.render_to_response | def render_to_response(self, context, **response_kwargs):
'''
Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods.
'''
switcher = {
'json': self.return_json_re... | python | def render_to_response(self, context, **response_kwargs):
'''
Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods.
'''
switcher = {
'json': self.return_json_re... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"switcher",
"=",
"{",
"'json'",
":",
"self",
".",
"return_json_response",
",",
"'opml'",
":",
"self",
".",
"return_opml_response",
",",
"'md'",
":",
"self",... | Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods. | [
"Compares",
"requested",
"format",
"to",
"supported",
"formats",
"and",
"routes",
"the",
"response",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/views.py#L1340-L1355 |
anjos/rrbob | rr/analysis.py | CER | def CER(prediction, true_labels):
"""
Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground t... | python | def CER(prediction, true_labels):
"""
Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground t... | [
"def",
"CER",
"(",
"prediction",
",",
"true_labels",
")",
":",
"errors",
"=",
"(",
"prediction",
"!=",
"true_labels",
")",
".",
"sum",
"(",
")",
"return",
"float",
"(",
"errors",
")",
"/",
"len",
"(",
"prediction",
")"
] | Calculates the classification error rate for an N-class classification problem
Parameters:
prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
prediction
true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
containing the ground truth labels for the input array, organized... | [
"Calculates",
"the",
"classification",
"error",
"rate",
"for",
"an",
"N",
"-",
"class",
"classification",
"problem"
] | train | https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/analysis.py#L6-L23 |
lvh/axiombench | axiombench/query.py | benchmark | def benchmark(store, n=10000):
"""
Iterates over all of the referreds, and then iterates over all of the
referrers that refer to each one.
Fairly item instantiation heavy.
"""
R = Referrer
for referred in store.query(Referred):
for _reference in store.query(R, R.reference == referr... | python | def benchmark(store, n=10000):
"""
Iterates over all of the referreds, and then iterates over all of the
referrers that refer to each one.
Fairly item instantiation heavy.
"""
R = Referrer
for referred in store.query(Referred):
for _reference in store.query(R, R.reference == referr... | [
"def",
"benchmark",
"(",
"store",
",",
"n",
"=",
"10000",
")",
":",
"R",
"=",
"Referrer",
"for",
"referred",
"in",
"store",
".",
"query",
"(",
"Referred",
")",
":",
"for",
"_reference",
"in",
"store",
".",
"query",
"(",
"R",
",",
"R",
".",
"referen... | Iterates over all of the referreds, and then iterates over all of the
referrers that refer to each one.
Fairly item instantiation heavy. | [
"Iterates",
"over",
"all",
"of",
"the",
"referreds",
"and",
"then",
"iterates",
"over",
"all",
"of",
"the",
"referrers",
"that",
"refer",
"to",
"each",
"one",
"."
] | train | https://github.com/lvh/axiombench/blob/dd783abfde23b0c67d7a74152d372c4c51e112aa/axiombench/query.py#L21-L32 |
MacHu-GWU/angora-project | angora/markup/rst.py | RstConstructor.header | def header(self, title, level, key, width=80):
"""Example::
.. _header_2:
Header 2
-------------------------------------------------------------------
**中文文档**
"""
linestyle_code = {1: "=", 2: "-", 3: "~"}
if level not in linestyle_code:
... | python | def header(self, title, level, key, width=80):
"""Example::
.. _header_2:
Header 2
-------------------------------------------------------------------
**中文文档**
"""
linestyle_code = {1: "=", 2: "-", 3: "~"}
if level not in linestyle_code:
... | [
"def",
"header",
"(",
"self",
",",
"title",
",",
"level",
",",
"key",
",",
"width",
"=",
"80",
")",
":",
"linestyle_code",
"=",
"{",
"1",
":",
"\"=\"",
",",
"2",
":",
"\"-\"",
",",
"3",
":",
"\"~\"",
"}",
"if",
"level",
"not",
"in",
"linestyle_co... | Example::
.. _header_2:
Header 2
-------------------------------------------------------------------
**中文文档** | [
"Example",
"::"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/rst.py#L40-L59 |
MacHu-GWU/angora-project | angora/markup/rst.py | RstConstructor.enumerated_list | def enumerated_list(self, nth, text):
"""Example::
1. item
"""
if not isinstance(nth, int):
raise Exception("'nth' argument has to be an integer!")
return "{nth}. {text}".format(nth=nth, text=text) | python | def enumerated_list(self, nth, text):
"""Example::
1. item
"""
if not isinstance(nth, int):
raise Exception("'nth' argument has to be an integer!")
return "{nth}. {text}".format(nth=nth, text=text) | [
"def",
"enumerated_list",
"(",
"self",
",",
"nth",
",",
"text",
")",
":",
"if",
"not",
"isinstance",
"(",
"nth",
",",
"int",
")",
":",
"raise",
"Exception",
"(",
"\"'nth' argument has to be an integer!\"",
")",
"return",
"\"{nth}. {text}\"",
".",
"format",
"("... | Example::
1. item | [
"Example",
"::"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/rst.py#L82-L89 |
MacHu-GWU/angora-project | angora/markup/rst.py | RstConstructor.code_block | def code_block(self, code, language, indent=0):
"""Example::
.. code-block:: python
from __future__ import print_function
import math
print(math.sqrt(10.0))
"""
if language not in [None, "console", "python", "ruby", "c"]:
... | python | def code_block(self, code, language, indent=0):
"""Example::
.. code-block:: python
from __future__ import print_function
import math
print(math.sqrt(10.0))
"""
if language not in [None, "console", "python", "ruby", "c"]:
... | [
"def",
"code_block",
"(",
"self",
",",
"code",
",",
"language",
",",
"indent",
"=",
"0",
")",
":",
"if",
"language",
"not",
"in",
"[",
"None",
",",
"\"console\"",
",",
"\"python\"",
",",
"\"ruby\"",
",",
"\"c\"",
"]",
":",
"raise",
"prefix",
"=",
"\"... | Example::
.. code-block:: python
from __future__ import print_function
import math
print(math.sqrt(10.0)) | [
"Example",
"::"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/rst.py#L91-L110 |
MacHu-GWU/angora-project | angora/markup/rst.py | RstConstructor.table | def table(self, data, header=None):
"""Example::
+----------+------------+
| CityName | Population |
+----------+------------+
| Adelaide | 1158259 |
+----------+------------+
| Darwin | 120900 |
+----------+----------... | python | def table(self, data, header=None):
"""Example::
+----------+------------+
| CityName | Population |
+----------+------------+
| Adelaide | 1158259 |
+----------+------------+
| Darwin | 120900 |
+----------+----------... | [
"def",
"table",
"(",
"self",
",",
"data",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
":",
"x",
"=",
"PrettyTable",
"(",
"header",
")",
"else",
":",
"x",
"=",
"PrettyTable",
"(",
")",
"# construct ascii text table, split header and body",
"for",
... | Example::
+----------+------------+
| CityName | Population |
+----------+------------+
| Adelaide | 1158259 |
+----------+------------+
| Darwin | 120900 |
+----------+------------+ | [
"Example",
"::"
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/rst.py#L112-L150 |
deviantony/valigator | valigator/utils.py | generate_uuid | def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '') | python | def generate_uuid():
"""Generate a UUID."""
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.decode().replace('=', '') | [
"def",
"generate_uuid",
"(",
")",
":",
"r_uuid",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
"return",
"r_uuid",
".",
"decode",
"(",
")",
".",
"replace",
"(",
"'='",
",",
"''",
")"
] | Generate a UUID. | [
"Generate",
"a",
"UUID",
"."
] | train | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/utils.py#L9-L12 |
deviantony/valigator | valigator/utils.py | extract_archive | def extract_archive(archive_path, destination_path):
"""Extracts an archive somewhere on the filesystem."""
tar = tarfile.open(archive_path)
tar.errorlevel = 1
tar.extractall(destination_path) | python | def extract_archive(archive_path, destination_path):
"""Extracts an archive somewhere on the filesystem."""
tar = tarfile.open(archive_path)
tar.errorlevel = 1
tar.extractall(destination_path) | [
"def",
"extract_archive",
"(",
"archive_path",
",",
"destination_path",
")",
":",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"archive_path",
")",
"tar",
".",
"errorlevel",
"=",
"1",
"tar",
".",
"extractall",
"(",
"destination_path",
")"
] | Extracts an archive somewhere on the filesystem. | [
"Extracts",
"an",
"archive",
"somewhere",
"on",
"the",
"filesystem",
"."
] | train | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/utils.py#L22-L26 |
deviantony/valigator | valigator/utils.py | remove_file | def remove_file(file_path):
"""Remove a file from the filesystem."""
if path.exists(file_path):
try:
rmtree(file_path)
except Exception:
print('Unable to remove temporary workdir {}'.format(file_path)) | python | def remove_file(file_path):
"""Remove a file from the filesystem."""
if path.exists(file_path):
try:
rmtree(file_path)
except Exception:
print('Unable to remove temporary workdir {}'.format(file_path)) | [
"def",
"remove_file",
"(",
"file_path",
")",
":",
"if",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"try",
":",
"rmtree",
"(",
"file_path",
")",
"except",
"Exception",
":",
"print",
"(",
"'Unable to remove temporary workdir {}'",
".",
"format",
"(",
"... | Remove a file from the filesystem. | [
"Remove",
"a",
"file",
"from",
"the",
"filesystem",
"."
] | train | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/utils.py#L29-L35 |
shaypal5/pdutil | pdutil/iter/iter.py | sub_dfs_by_size | def sub_dfs_by_size(df, size):
"""Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
... | python | def sub_dfs_by_size(df, size):
"""Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
... | [
"def",
"sub_dfs_by_size",
"(",
"df",
",",
"size",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"df",
")",
",",
"size",
")",
":",
"yield",
"(",
"df",
".",
"iloc",
"[",
"i",
":",
"i",
"+",
"size",
"]",
")"
] | Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
A generator yielding consecutive sub-... | [
"Get",
"a",
"generator",
"yielding",
"consecutive",
"sub",
"-",
"dataframes",
"of",
"the",
"given",
"size",
"."
] | train | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/iter/iter.py#L4-L32 |
shaypal5/pdutil | pdutil/iter/iter.py | sub_dfs_by_num | def sub_dfs_by_num(df, num):
"""Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
... | python | def sub_dfs_by_num(df, num):
"""Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
... | [
"def",
"sub_dfs_by_num",
"(",
"df",
",",
"num",
")",
":",
"size",
"=",
"len",
"(",
"df",
")",
"/",
"float",
"(",
"num",
")",
"for",
"i",
"in",
"range",
"(",
"num",
")",
":",
"yield",
"df",
".",
"iloc",
"[",
"int",
"(",
"round",
"(",
"size",
"... | Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
-------
generator
A ge... | [
"Get",
"a",
"generator",
"yielding",
"num",
"consecutive",
"sub",
"-",
"dataframes",
"of",
"the",
"given",
"df",
"."
] | train | https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/iter/iter.py#L35-L64 |
ryanjdillon/pylleo | pylleo/utils.py | predict_encoding | def predict_encoding(file_path, n_lines=20):
'''Get file encoding of a text file'''
import chardet
# Open the file as binary data
with open(file_path, 'rb') as f:
# Join binary lines for specified number of lines
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return cha... | python | def predict_encoding(file_path, n_lines=20):
'''Get file encoding of a text file'''
import chardet
# Open the file as binary data
with open(file_path, 'rb') as f:
# Join binary lines for specified number of lines
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return cha... | [
"def",
"predict_encoding",
"(",
"file_path",
",",
"n_lines",
"=",
"20",
")",
":",
"import",
"chardet",
"# Open the file as binary data",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"f",
":",
"# Join binary lines for specified number of lines",
"rawdata",... | Get file encoding of a text file | [
"Get",
"file",
"encoding",
"of",
"a",
"text",
"file"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L15-L24 |
ryanjdillon/pylleo | pylleo/utils.py | get_n_header | def get_n_header(f, header_char='"'):
'''Get the nummber of header rows in a Little Leonardo data file
Args
----
f : file stream
File handle for the file from which header rows will be read
header_char: str
Character array at beginning of each header line
Returns
-------
... | python | def get_n_header(f, header_char='"'):
'''Get the nummber of header rows in a Little Leonardo data file
Args
----
f : file stream
File handle for the file from which header rows will be read
header_char: str
Character array at beginning of each header line
Returns
-------
... | [
"def",
"get_n_header",
"(",
"f",
",",
"header_char",
"=",
"'\"'",
")",
":",
"n_header",
"=",
"0",
"reading_headers",
"=",
"True",
"while",
"reading_headers",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"header_... | Get the nummber of header rows in a Little Leonardo data file
Args
----
f : file stream
File handle for the file from which header rows will be read
header_char: str
Character array at beginning of each header line
Returns
-------
n_header: int
Number of header rows... | [
"Get",
"the",
"nummber",
"of",
"header",
"rows",
"in",
"a",
"Little",
"Leonardo",
"data",
"file"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L27-L52 |
ryanjdillon/pylleo | pylleo/utils.py | get_tag_params | def get_tag_params(tag_model):
'''Load param strs and n_header based on model of tag model'''
tag_model = tag_model.replace('-', '')
tags = dict()
tags['W190PD3GT'] = ['Acceleration-X', 'Acceleration-Y', 'Acceleration-Z',
'Depth', 'Propeller', 'Temperature']
# Return tag p... | python | def get_tag_params(tag_model):
'''Load param strs and n_header based on model of tag model'''
tag_model = tag_model.replace('-', '')
tags = dict()
tags['W190PD3GT'] = ['Acceleration-X', 'Acceleration-Y', 'Acceleration-Z',
'Depth', 'Propeller', 'Temperature']
# Return tag p... | [
"def",
"get_tag_params",
"(",
"tag_model",
")",
":",
"tag_model",
"=",
"tag_model",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"tags",
"=",
"dict",
"(",
")",
"tags",
"[",
"'W190PD3GT'",
"]",
"=",
"[",
"'Acceleration-X'",
",",
"'Acceleration-Y'",
",",
"'... | Load param strs and n_header based on model of tag model | [
"Load",
"param",
"strs",
"and",
"n_header",
"based",
"on",
"model",
"of",
"tag",
"model"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L55-L67 |
ryanjdillon/pylleo | pylleo/utils.py | find_file | def find_file(path_dir, search_str, file_ext):
'''Find path of file in directory containing the search string'''
import os
file_path = None
for file_name in os.listdir(path_dir):
if (search_str in file_name) and (file_name.endswith(file_ext)):
file_path = os.path.join(path_dir, fil... | python | def find_file(path_dir, search_str, file_ext):
'''Find path of file in directory containing the search string'''
import os
file_path = None
for file_name in os.listdir(path_dir):
if (search_str in file_name) and (file_name.endswith(file_ext)):
file_path = os.path.join(path_dir, fil... | [
"def",
"find_file",
"(",
"path_dir",
",",
"search_str",
",",
"file_ext",
")",
":",
"import",
"os",
"file_path",
"=",
"None",
"for",
"file_name",
"in",
"os",
".",
"listdir",
"(",
"path_dir",
")",
":",
"if",
"(",
"search_str",
"in",
"file_name",
")",
"and"... | Find path of file in directory containing the search string | [
"Find",
"path",
"of",
"file",
"in",
"directory",
"containing",
"the",
"search",
"string"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L70-L85 |
ryanjdillon/pylleo | pylleo/utils.py | nearest | def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | python | def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | [
"def",
"nearest",
"(",
"items",
",",
"pivot",
")",
":",
"return",
"min",
"(",
"items",
",",
"key",
"=",
"lambda",
"x",
":",
"abs",
"(",
"x",
"-",
"pivot",
")",
")"
] | Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Value in items nearest to `pivot` | [
"Find",
"nearest",
"value",
"in",
"array",
"including",
"datetimes"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L104-L119 |
ryanjdillon/pylleo | pylleo/utils.py | parse_experiment_params | def parse_experiment_params(name_exp):
'''Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters
'''
if ('/... | python | def parse_experiment_params(name_exp):
'''Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters
'''
if ('/... | [
"def",
"parse_experiment_params",
"(",
"name_exp",
")",
":",
"if",
"(",
"'/'",
"in",
"name_exp",
")",
"or",
"(",
"'\\\\'",
"in",
"name_exp",
")",
":",
"raise",
"ValueError",
"(",
"\"The path {} appears to be a path. Please pass \"",
"\"only the data directory's name (i.... | Parse experiment parameters from the data directory name
Args
----
name_exp: str
Name of data directory with experiment parameters
Returns
-------
tag_params: dict of str
Dictionary of parsed experiment parameters | [
"Parse",
"experiment",
"parameters",
"from",
"the",
"data",
"directory",
"name"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L122-L147 |
sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | CassandraConnection._get_cassandra_config | def _get_cassandra_config(self):
"""Retrieve a dict containing Cassandra client config params."""
parts = urlsplit(os.environ.get('CASSANDRA_URI', DEFAULT_URI))
if parts.scheme != 'cassandra':
raise RuntimeError(
'CASSANDRA_URI scheme is not "cassandra://"!')
... | python | def _get_cassandra_config(self):
"""Retrieve a dict containing Cassandra client config params."""
parts = urlsplit(os.environ.get('CASSANDRA_URI', DEFAULT_URI))
if parts.scheme != 'cassandra':
raise RuntimeError(
'CASSANDRA_URI scheme is not "cassandra://"!')
... | [
"def",
"_get_cassandra_config",
"(",
"self",
")",
":",
"parts",
"=",
"urlsplit",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'CASSANDRA_URI'",
",",
"DEFAULT_URI",
")",
")",
"if",
"parts",
".",
"scheme",
"!=",
"'cassandra'",
":",
"raise",
"RuntimeError",
"... | Retrieve a dict containing Cassandra client config params. | [
"Retrieve",
"a",
"dict",
"containing",
"Cassandra",
"client",
"config",
"params",
"."
] | train | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L59-L73 |
sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | CassandraConnection.prepare | def prepare(self, query, name=None):
"""Create and cache a prepared statement using the provided query.
This function will take a ``query`` and optional ``name`` parameter
and will create a new prepared statement for the provided ``query``.
The resulting statement object will be cached ... | python | def prepare(self, query, name=None):
"""Create and cache a prepared statement using the provided query.
This function will take a ``query`` and optional ``name`` parameter
and will create a new prepared statement for the provided ``query``.
The resulting statement object will be cached ... | [
"def",
"prepare",
"(",
"self",
",",
"query",
",",
"name",
"=",
"None",
")",
":",
"key",
"=",
"name",
"or",
"query",
"stmt",
"=",
"CassandraConnection",
".",
"_prepared_statement_cache",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"stmt",
"is",
"not... | Create and cache a prepared statement using the provided query.
This function will take a ``query`` and optional ``name`` parameter
and will create a new prepared statement for the provided ``query``.
The resulting statement object will be cached so future invocations
of this function w... | [
"Create",
"and",
"cache",
"a",
"prepared",
"statement",
"using",
"the",
"provided",
"query",
"."
] | train | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L85-L106 |
sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | CassandraConnection.execute | def execute(self, query, *args, **kwargs):
"""Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
"""
tornado_future = Futur... | python | def execute(self, query, *args, **kwargs):
"""Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
"""
tornado_future = Futur... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tornado_future",
"=",
"Future",
"(",
")",
"cassandra_future",
"=",
"self",
".",
"_session",
".",
"execute_async",
"(",
"query",
",",
"*",
"args",
",",
... | Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters. | [
"Asynchronously",
"execute",
"the",
"specified",
"CQL",
"query",
"."
] | train | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L108-L119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.