id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
250,200 | refinery29/chassis | chassis/services/cache.py | set_object | def set_object(cache, template, indexes, data):
"""Set an object in Redis using a pipeline.
Only sets the fields that are present in both the template and the data.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:%(id)s:username',
'email': 'user:%(id)s:email',
'phone': 'user:%(id)s:phone'
}
indexes: a dictionary containing the values to use to cosntruct the
redis keys: Example:
{
'id': 342
}
data: a dictionary returning the data to store. Example:
{
'username': 'bob',
'email': '[email protected]',
'phone': '555-555-5555'
}
"""
# TODO(mattmillr): Handle expiration times
with cache as redis_connection:
pipe = redis_connection.pipeline()
for key in set(template.keys()) & set(data.keys()):
pipe.set(template[key] % indexes, str(data[key]))
pipe.execute() | python | def set_object(cache, template, indexes, data):
"""Set an object in Redis using a pipeline.
Only sets the fields that are present in both the template and the data.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:%(id)s:username',
'email': 'user:%(id)s:email',
'phone': 'user:%(id)s:phone'
}
indexes: a dictionary containing the values to use to cosntruct the
redis keys: Example:
{
'id': 342
}
data: a dictionary returning the data to store. Example:
{
'username': 'bob',
'email': '[email protected]',
'phone': '555-555-5555'
}
"""
# TODO(mattmillr): Handle expiration times
with cache as redis_connection:
pipe = redis_connection.pipeline()
for key in set(template.keys()) & set(data.keys()):
pipe.set(template[key] % indexes, str(data[key]))
pipe.execute() | [
"def",
"set_object",
"(",
"cache",
",",
"template",
",",
"indexes",
",",
"data",
")",
":",
"# TODO(mattmillr): Handle expiration times",
"with",
"cache",
"as",
"redis_connection",
":",
"pipe",
"=",
"redis_connection",
".",
"pipeline",
"(",
")",
"for",
"key",
"in",
"set",
"(",
"template",
".",
"keys",
"(",
")",
")",
"&",
"set",
"(",
"data",
".",
"keys",
"(",
")",
")",
":",
"pipe",
".",
"set",
"(",
"template",
"[",
"key",
"]",
"%",
"indexes",
",",
"str",
"(",
"data",
"[",
"key",
"]",
")",
")",
"pipe",
".",
"execute",
"(",
")"
] | Set an object in Redis using a pipeline.
Only sets the fields that are present in both the template and the data.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:%(id)s:username',
'email': 'user:%(id)s:email',
'phone': 'user:%(id)s:phone'
}
indexes: a dictionary containing the values to use to cosntruct the
redis keys: Example:
{
'id': 342
}
data: a dictionary returning the data to store. Example:
{
'username': 'bob',
'email': '[email protected]',
'phone': '555-555-5555'
} | [
"Set",
"an",
"object",
"in",
"Redis",
"using",
"a",
"pipeline",
"."
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/cache.py#L85-L122 |
250,201 | refinery29/chassis | chassis/services/cache.py | delete_object | def delete_object(cache, template, indexes):
"""Delete an object in Redis using a pipeline.
Deletes all fields defined by the template.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:%(id)s:username',
'email': 'user:%(id)s:email',
'phone': 'user:%(id)s:phone'
}
indexes: a dictionary containing the values to use to construct the
redis keys: Example:
{
'id': 342
}
"""
with cache as redis_connection:
pipe = redis_connection.pipeline()
for key in set(template.keys()):
pipe.delete(template[key] % indexes)
pipe.execute() | python | def delete_object(cache, template, indexes):
"""Delete an object in Redis using a pipeline.
Deletes all fields defined by the template.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:%(id)s:username',
'email': 'user:%(id)s:email',
'phone': 'user:%(id)s:phone'
}
indexes: a dictionary containing the values to use to construct the
redis keys: Example:
{
'id': 342
}
"""
with cache as redis_connection:
pipe = redis_connection.pipeline()
for key in set(template.keys()):
pipe.delete(template[key] % indexes)
pipe.execute() | [
"def",
"delete_object",
"(",
"cache",
",",
"template",
",",
"indexes",
")",
":",
"with",
"cache",
"as",
"redis_connection",
":",
"pipe",
"=",
"redis_connection",
".",
"pipeline",
"(",
")",
"for",
"key",
"in",
"set",
"(",
"template",
".",
"keys",
"(",
")",
")",
":",
"pipe",
".",
"delete",
"(",
"template",
"[",
"key",
"]",
"%",
"indexes",
")",
"pipe",
".",
"execute",
"(",
")"
] | Delete an object in Redis using a pipeline.
Deletes all fields defined by the template.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
string uses named string interpolation format. Example:
{
'username': 'user:%(id)s:username',
'email': 'user:%(id)s:email',
'phone': 'user:%(id)s:phone'
}
indexes: a dictionary containing the values to use to construct the
redis keys: Example:
{
'id': 342
} | [
"Delete",
"an",
"object",
"in",
"Redis",
"using",
"a",
"pipeline",
"."
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/cache.py#L125-L154 |
250,202 | refinery29/chassis | chassis/services/cache.py | set_value | def set_value(cache, key, value):
"""Set a value by key.
Arguments:
cache:
instance of Cache
key:
'user:342:username',
"""
with cache as redis_connection:
return redis_connection.set(key, value) | python | def set_value(cache, key, value):
"""Set a value by key.
Arguments:
cache:
instance of Cache
key:
'user:342:username',
"""
with cache as redis_connection:
return redis_connection.set(key, value) | [
"def",
"set_value",
"(",
"cache",
",",
"key",
",",
"value",
")",
":",
"with",
"cache",
"as",
"redis_connection",
":",
"return",
"redis_connection",
".",
"set",
"(",
"key",
",",
"value",
")"
] | Set a value by key.
Arguments:
cache:
instance of Cache
key:
'user:342:username', | [
"Set",
"a",
"value",
"by",
"key",
"."
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/cache.py#L175-L186 |
250,203 | heikomuller/sco-client | scocli/subject.py | SubjectHandle.create | def create(url, filename, properties):
"""Create new subject at given SCO-API by uploading local file.
Expects an tar-archive containing FreeSurfer archive file. Allows to
update properties of created resource.
Parameters
----------
url : string
Url to POST image group create request
filename : string
Path to tar-archive on local disk
properties : Dictionary
Set of additional properties for subject (may be None)
Returns
-------
string
Url of created subject resource
"""
# Ensure that the file has valid suffix
if not has_tar_suffix(filename):
raise ValueError('invalid file suffix: ' + filename)
# Upload file to create subject. If response is not 201 the uploaded
# file is not a valid FreeSurfer archive
files = {'file': open(filename, 'rb')}
response = requests.post(url, files=files)
if response.status_code != 201:
raise ValueError('invalid file: ' + filename)
# Get image group HATEOAS references from successful response
links = references_to_dict(response.json()['links'])
resource_url = links[REF_SELF]
# Update subject properties if given
if not properties is None:
obj_props = []
# Catch TypeErrors if properties is not a list.
try:
for key in properties:
obj_props.append({'key':key, 'value':properties[key]})
except TypeError as ex:
raise ValueError('invalid property set')
try:
req = urllib2.Request(links[REF_UPSERT_PROPERTIES])
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(
req,
json.dumps({'properties' : obj_props})
)
except urllib2.URLError as ex:
raise ValueError(str(ex))
return resource_url | python | def create(url, filename, properties):
"""Create new subject at given SCO-API by uploading local file.
Expects an tar-archive containing FreeSurfer archive file. Allows to
update properties of created resource.
Parameters
----------
url : string
Url to POST image group create request
filename : string
Path to tar-archive on local disk
properties : Dictionary
Set of additional properties for subject (may be None)
Returns
-------
string
Url of created subject resource
"""
# Ensure that the file has valid suffix
if not has_tar_suffix(filename):
raise ValueError('invalid file suffix: ' + filename)
# Upload file to create subject. If response is not 201 the uploaded
# file is not a valid FreeSurfer archive
files = {'file': open(filename, 'rb')}
response = requests.post(url, files=files)
if response.status_code != 201:
raise ValueError('invalid file: ' + filename)
# Get image group HATEOAS references from successful response
links = references_to_dict(response.json()['links'])
resource_url = links[REF_SELF]
# Update subject properties if given
if not properties is None:
obj_props = []
# Catch TypeErrors if properties is not a list.
try:
for key in properties:
obj_props.append({'key':key, 'value':properties[key]})
except TypeError as ex:
raise ValueError('invalid property set')
try:
req = urllib2.Request(links[REF_UPSERT_PROPERTIES])
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(
req,
json.dumps({'properties' : obj_props})
)
except urllib2.URLError as ex:
raise ValueError(str(ex))
return resource_url | [
"def",
"create",
"(",
"url",
",",
"filename",
",",
"properties",
")",
":",
"# Ensure that the file has valid suffix",
"if",
"not",
"has_tar_suffix",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"'invalid file suffix: '",
"+",
"filename",
")",
"# Upload file to create subject. If response is not 201 the uploaded",
"# file is not a valid FreeSurfer archive",
"files",
"=",
"{",
"'file'",
":",
"open",
"(",
"filename",
",",
"'rb'",
")",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"files",
"=",
"files",
")",
"if",
"response",
".",
"status_code",
"!=",
"201",
":",
"raise",
"ValueError",
"(",
"'invalid file: '",
"+",
"filename",
")",
"# Get image group HATEOAS references from successful response",
"links",
"=",
"references_to_dict",
"(",
"response",
".",
"json",
"(",
")",
"[",
"'links'",
"]",
")",
"resource_url",
"=",
"links",
"[",
"REF_SELF",
"]",
"# Update subject properties if given",
"if",
"not",
"properties",
"is",
"None",
":",
"obj_props",
"=",
"[",
"]",
"# Catch TypeErrors if properties is not a list.",
"try",
":",
"for",
"key",
"in",
"properties",
":",
"obj_props",
".",
"append",
"(",
"{",
"'key'",
":",
"key",
",",
"'value'",
":",
"properties",
"[",
"key",
"]",
"}",
")",
"except",
"TypeError",
"as",
"ex",
":",
"raise",
"ValueError",
"(",
"'invalid property set'",
")",
"try",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"links",
"[",
"REF_UPSERT_PROPERTIES",
"]",
")",
"req",
".",
"add_header",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
",",
"json",
".",
"dumps",
"(",
"{",
"'properties'",
":",
"obj_props",
"}",
")",
")",
"except",
"urllib2",
".",
"URLError",
"as",
"ex",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"ex",
")",
")",
"return",
"resource_url"
] | Create new subject at given SCO-API by uploading local file.
Expects an tar-archive containing FreeSurfer archive file. Allows to
update properties of created resource.
Parameters
----------
url : string
Url to POST image group create request
filename : string
Path to tar-archive on local disk
properties : Dictionary
Set of additional properties for subject (may be None)
Returns
-------
string
Url of created subject resource | [
"Create",
"new",
"subject",
"at",
"given",
"SCO",
"-",
"API",
"by",
"uploading",
"local",
"file",
".",
"Expects",
"an",
"tar",
"-",
"archive",
"containing",
"FreeSurfer",
"archive",
"file",
".",
"Allows",
"to",
"update",
"properties",
"of",
"created",
"resource",
"."
] | c4afab71297f73003379bba4c1679be9dcf7cef8 | https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/subject.py#L74-L123 |
250,204 | calvinku96/labreporthelper | labreporthelper/parse.py | getdata | def getdata(inputfile, argnum=None, close=False):
"""
Get data from the .dat files
args:
inputfile: file
Input File
close: bool, default=False
Closes inputfile if True
inputfile (File): Input file
close (boolean): Closes inputfile if True (default: False)
returns:
dictionary:
data: list of parsed data
variables: dictionary of errors and other additional variables
"""
# get data and converts them to list
# outputtype - list, dict, all
output = []
add_data = {}
line_num = 0
for line in inputfile:
line_num += 1
if ("#" not in line) and (line != ""):
linesplit = line.split()
if argnum is not None and len(linesplit) != int(argnum):
raise ValueError(
"Line {:d} has {:d} arguments (need {:d})".format(
line_num, len(linesplit), argnum))
output.append(linesplit)
# additional float variable
if "#f" in line:
data = line.split()[1].split("=")
add_data[data[0]] = float(data[1])
# additional list float variable
if "#l" in line:
data = line.split()[1].split("=")
add_data[data[0]] = [float(e) for e in data[1].split(",")]
if close:
inputfile.close()
output = cleandata(output)
return {
"data": np.array(output),
"variables": add_data,
} | python | def getdata(inputfile, argnum=None, close=False):
"""
Get data from the .dat files
args:
inputfile: file
Input File
close: bool, default=False
Closes inputfile if True
inputfile (File): Input file
close (boolean): Closes inputfile if True (default: False)
returns:
dictionary:
data: list of parsed data
variables: dictionary of errors and other additional variables
"""
# get data and converts them to list
# outputtype - list, dict, all
output = []
add_data = {}
line_num = 0
for line in inputfile:
line_num += 1
if ("#" not in line) and (line != ""):
linesplit = line.split()
if argnum is not None and len(linesplit) != int(argnum):
raise ValueError(
"Line {:d} has {:d} arguments (need {:d})".format(
line_num, len(linesplit), argnum))
output.append(linesplit)
# additional float variable
if "#f" in line:
data = line.split()[1].split("=")
add_data[data[0]] = float(data[1])
# additional list float variable
if "#l" in line:
data = line.split()[1].split("=")
add_data[data[0]] = [float(e) for e in data[1].split(",")]
if close:
inputfile.close()
output = cleandata(output)
return {
"data": np.array(output),
"variables": add_data,
} | [
"def",
"getdata",
"(",
"inputfile",
",",
"argnum",
"=",
"None",
",",
"close",
"=",
"False",
")",
":",
"# get data and converts them to list",
"# outputtype - list, dict, all",
"output",
"=",
"[",
"]",
"add_data",
"=",
"{",
"}",
"line_num",
"=",
"0",
"for",
"line",
"in",
"inputfile",
":",
"line_num",
"+=",
"1",
"if",
"(",
"\"#\"",
"not",
"in",
"line",
")",
"and",
"(",
"line",
"!=",
"\"\"",
")",
":",
"linesplit",
"=",
"line",
".",
"split",
"(",
")",
"if",
"argnum",
"is",
"not",
"None",
"and",
"len",
"(",
"linesplit",
")",
"!=",
"int",
"(",
"argnum",
")",
":",
"raise",
"ValueError",
"(",
"\"Line {:d} has {:d} arguments (need {:d})\"",
".",
"format",
"(",
"line_num",
",",
"len",
"(",
"linesplit",
")",
",",
"argnum",
")",
")",
"output",
".",
"append",
"(",
"linesplit",
")",
"# additional float variable",
"if",
"\"#f\"",
"in",
"line",
":",
"data",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
".",
"split",
"(",
"\"=\"",
")",
"add_data",
"[",
"data",
"[",
"0",
"]",
"]",
"=",
"float",
"(",
"data",
"[",
"1",
"]",
")",
"# additional list float variable",
"if",
"\"#l\"",
"in",
"line",
":",
"data",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
".",
"split",
"(",
"\"=\"",
")",
"add_data",
"[",
"data",
"[",
"0",
"]",
"]",
"=",
"[",
"float",
"(",
"e",
")",
"for",
"e",
"in",
"data",
"[",
"1",
"]",
".",
"split",
"(",
"\",\"",
")",
"]",
"if",
"close",
":",
"inputfile",
".",
"close",
"(",
")",
"output",
"=",
"cleandata",
"(",
"output",
")",
"return",
"{",
"\"data\"",
":",
"np",
".",
"array",
"(",
"output",
")",
",",
"\"variables\"",
":",
"add_data",
",",
"}"
] | Get data from the .dat files
args:
inputfile: file
Input File
close: bool, default=False
Closes inputfile if True
inputfile (File): Input file
close (boolean): Closes inputfile if True (default: False)
returns:
dictionary:
data: list of parsed data
variables: dictionary of errors and other additional variables | [
"Get",
"data",
"from",
"the",
".",
"dat",
"files"
] | 4d436241f389c02eb188c313190df62ab28c3763 | https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/parse.py#L7-L51 |
250,205 | bird-house/birdhousebuilder.recipe.redis | birdhousebuilder/recipe/redis/__init__.py | Recipe.install_supervisor | def install_supervisor(self, update=False):
"""
install supervisor config for redis
"""
script = supervisor.Recipe(
self.buildout,
self.name,
{'user': self.options.get('user'),
'program': self.options.get('program'),
'command': templ_cmd.render(config=self.conf_filename, prefix=self.prefix),
'stopwaitsecs': '30',
'killasgroup': 'true',
})
return script.install(update) | python | def install_supervisor(self, update=False):
"""
install supervisor config for redis
"""
script = supervisor.Recipe(
self.buildout,
self.name,
{'user': self.options.get('user'),
'program': self.options.get('program'),
'command': templ_cmd.render(config=self.conf_filename, prefix=self.prefix),
'stopwaitsecs': '30',
'killasgroup': 'true',
})
return script.install(update) | [
"def",
"install_supervisor",
"(",
"self",
",",
"update",
"=",
"False",
")",
":",
"script",
"=",
"supervisor",
".",
"Recipe",
"(",
"self",
".",
"buildout",
",",
"self",
".",
"name",
",",
"{",
"'user'",
":",
"self",
".",
"options",
".",
"get",
"(",
"'user'",
")",
",",
"'program'",
":",
"self",
".",
"options",
".",
"get",
"(",
"'program'",
")",
",",
"'command'",
":",
"templ_cmd",
".",
"render",
"(",
"config",
"=",
"self",
".",
"conf_filename",
",",
"prefix",
"=",
"self",
".",
"prefix",
")",
",",
"'stopwaitsecs'",
":",
"'30'",
",",
"'killasgroup'",
":",
"'true'",
",",
"}",
")",
"return",
"script",
".",
"install",
"(",
"update",
")"
] | install supervisor config for redis | [
"install",
"supervisor",
"config",
"for",
"redis"
] | 3e66dd2f891547665055d807277d1c8f23c57003 | https://github.com/bird-house/birdhousebuilder.recipe.redis/blob/3e66dd2f891547665055d807277d1c8f23c57003/birdhousebuilder/recipe/redis/__init__.py#L67-L80 |
250,206 | roaet/eh | eh/mdv/tabulate.py | _format | def _format(val, valtype, floatfmt, missingval="", has_invisible=True):
"""Format a value accoding to its type.
Unicode is supported:
>>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \
tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430 \\u0446\\u0438\\u0444\\u0440\\u0430\\n------- -------\\n\\u0430\\u0437 2\\n\\u0431\\u0443\\u043a\\u0438 4' ; \
tabulate(tbl, headers=hrow) == good_result
True
"""
if val is None:
return missingval
if valtype in [int, _long_type, _text_type]:
return "{0}".format(val)
elif valtype is _binary_type:
try:
return _text_type(val, "ascii")
except TypeError:
return _text_type(val)
elif valtype is float:
is_a_colored_number = has_invisible and isinstance(val, (_text_type, _binary_type))
if is_a_colored_number:
raw_val = _strip_invisible(val)
formatted_val = format(float(raw_val), floatfmt)
return val.replace(raw_val, formatted_val)
else:
return format(float(val), floatfmt)
else:
return "{0}".format(val) | python | def _format(val, valtype, floatfmt, missingval="", has_invisible=True):
"""Format a value accoding to its type.
Unicode is supported:
>>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \
tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430 \\u0446\\u0438\\u0444\\u0440\\u0430\\n------- -------\\n\\u0430\\u0437 2\\n\\u0431\\u0443\\u043a\\u0438 4' ; \
tabulate(tbl, headers=hrow) == good_result
True
"""
if val is None:
return missingval
if valtype in [int, _long_type, _text_type]:
return "{0}".format(val)
elif valtype is _binary_type:
try:
return _text_type(val, "ascii")
except TypeError:
return _text_type(val)
elif valtype is float:
is_a_colored_number = has_invisible and isinstance(val, (_text_type, _binary_type))
if is_a_colored_number:
raw_val = _strip_invisible(val)
formatted_val = format(float(raw_val), floatfmt)
return val.replace(raw_val, formatted_val)
else:
return format(float(val), floatfmt)
else:
return "{0}".format(val) | [
"def",
"_format",
"(",
"val",
",",
"valtype",
",",
"floatfmt",
",",
"missingval",
"=",
"\"\"",
",",
"has_invisible",
"=",
"True",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"missingval",
"if",
"valtype",
"in",
"[",
"int",
",",
"_long_type",
",",
"_text_type",
"]",
":",
"return",
"\"{0}\"",
".",
"format",
"(",
"val",
")",
"elif",
"valtype",
"is",
"_binary_type",
":",
"try",
":",
"return",
"_text_type",
"(",
"val",
",",
"\"ascii\"",
")",
"except",
"TypeError",
":",
"return",
"_text_type",
"(",
"val",
")",
"elif",
"valtype",
"is",
"float",
":",
"is_a_colored_number",
"=",
"has_invisible",
"and",
"isinstance",
"(",
"val",
",",
"(",
"_text_type",
",",
"_binary_type",
")",
")",
"if",
"is_a_colored_number",
":",
"raw_val",
"=",
"_strip_invisible",
"(",
"val",
")",
"formatted_val",
"=",
"format",
"(",
"float",
"(",
"raw_val",
")",
",",
"floatfmt",
")",
"return",
"val",
".",
"replace",
"(",
"raw_val",
",",
"formatted_val",
")",
"else",
":",
"return",
"format",
"(",
"float",
"(",
"val",
")",
",",
"floatfmt",
")",
"else",
":",
"return",
"\"{0}\"",
".",
"format",
"(",
"val",
")"
] | Format a value accoding to its type.
Unicode is supported:
>>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \
tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430 \\u0446\\u0438\\u0444\\u0440\\u0430\\n------- -------\\n\\u0430\\u0437 2\\n\\u0431\\u0443\\u043a\\u0438 4' ; \
tabulate(tbl, headers=hrow) == good_result
True | [
"Format",
"a",
"value",
"accoding",
"to",
"its",
"type",
"."
] | 9370864a9f1d65bb0f822d0aea83f1169c98f3bd | https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/tabulate.py#L544-L575 |
250,207 | solocompt/plugs-filter | plugs_filter/decorators.py | get_view_model | def get_view_model(cls):
"""
Get the model to use in the filter_class by inspecting
the queryset or by using a declared auto_filters_model
"""
msg = 'When using get_queryset you must set a auto_filters_model field in the viewset'
if cls.queryset is not None:
return cls.queryset.model
else:
assert hasattr(cls, 'auto_filters_model'), msg
return cls.auto_filters_model | python | def get_view_model(cls):
"""
Get the model to use in the filter_class by inspecting
the queryset or by using a declared auto_filters_model
"""
msg = 'When using get_queryset you must set a auto_filters_model field in the viewset'
if cls.queryset is not None:
return cls.queryset.model
else:
assert hasattr(cls, 'auto_filters_model'), msg
return cls.auto_filters_model | [
"def",
"get_view_model",
"(",
"cls",
")",
":",
"msg",
"=",
"'When using get_queryset you must set a auto_filters_model field in the viewset'",
"if",
"cls",
".",
"queryset",
"is",
"not",
"None",
":",
"return",
"cls",
".",
"queryset",
".",
"model",
"else",
":",
"assert",
"hasattr",
"(",
"cls",
",",
"'auto_filters_model'",
")",
",",
"msg",
"return",
"cls",
".",
"auto_filters_model"
] | Get the model to use in the filter_class by inspecting
the queryset or by using a declared auto_filters_model | [
"Get",
"the",
"model",
"to",
"use",
"in",
"the",
"filter_class",
"by",
"inspecting",
"the",
"queryset",
"or",
"by",
"using",
"a",
"declared",
"auto_filters_model"
] | cb34c7d662d3f96c07c10b3ed0a34bafef78b52c | https://github.com/solocompt/plugs-filter/blob/cb34c7d662d3f96c07c10b3ed0a34bafef78b52c/plugs_filter/decorators.py#L8-L18 |
250,208 | solocompt/plugs-filter | plugs_filter/decorators.py | auto_filters | def auto_filters(cls):
"""
Adds a dynamic filterclass to a viewset
with all auto filters available for the field type
that are declared in a tuple auto_filter_fields
@auto_filters
def class(...):
...
auto_filters_fields('id', 'location', 'category')
"""
msg = 'Viewset must have auto_filters_fields or auto_filters_exclude attribute when using auto_filters decorator'
if not hasattr(cls, 'auto_filters_fields') and not hasattr(cls, 'auto_filters_exclude'):
raise AssertionError(msg)
dict_ = {}
view_model = get_view_model(cls)
auto_filters_fields = get_auto_filters_fields(cls, view_model)
for auto_filter in auto_filters_fields:
dict_[auto_filter] = AutoFilters(name=auto_filter)
# create the inner Meta class and then the filter class
dict_['Meta'] = type('Meta', (object, ), {'model': view_model, 'fields': ()})
filter_class = type('DynamicFilterClass', (FilterSet, ), dict_)
cls.filter_class = filter_class
return cls | python | def auto_filters(cls):
"""
Adds a dynamic filterclass to a viewset
with all auto filters available for the field type
that are declared in a tuple auto_filter_fields
@auto_filters
def class(...):
...
auto_filters_fields('id', 'location', 'category')
"""
msg = 'Viewset must have auto_filters_fields or auto_filters_exclude attribute when using auto_filters decorator'
if not hasattr(cls, 'auto_filters_fields') and not hasattr(cls, 'auto_filters_exclude'):
raise AssertionError(msg)
dict_ = {}
view_model = get_view_model(cls)
auto_filters_fields = get_auto_filters_fields(cls, view_model)
for auto_filter in auto_filters_fields:
dict_[auto_filter] = AutoFilters(name=auto_filter)
# create the inner Meta class and then the filter class
dict_['Meta'] = type('Meta', (object, ), {'model': view_model, 'fields': ()})
filter_class = type('DynamicFilterClass', (FilterSet, ), dict_)
cls.filter_class = filter_class
return cls | [
"def",
"auto_filters",
"(",
"cls",
")",
":",
"msg",
"=",
"'Viewset must have auto_filters_fields or auto_filters_exclude attribute when using auto_filters decorator'",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'auto_filters_fields'",
")",
"and",
"not",
"hasattr",
"(",
"cls",
",",
"'auto_filters_exclude'",
")",
":",
"raise",
"AssertionError",
"(",
"msg",
")",
"dict_",
"=",
"{",
"}",
"view_model",
"=",
"get_view_model",
"(",
"cls",
")",
"auto_filters_fields",
"=",
"get_auto_filters_fields",
"(",
"cls",
",",
"view_model",
")",
"for",
"auto_filter",
"in",
"auto_filters_fields",
":",
"dict_",
"[",
"auto_filter",
"]",
"=",
"AutoFilters",
"(",
"name",
"=",
"auto_filter",
")",
"# create the inner Meta class and then the filter class",
"dict_",
"[",
"'Meta'",
"]",
"=",
"type",
"(",
"'Meta'",
",",
"(",
"object",
",",
")",
",",
"{",
"'model'",
":",
"view_model",
",",
"'fields'",
":",
"(",
")",
"}",
")",
"filter_class",
"=",
"type",
"(",
"'DynamicFilterClass'",
",",
"(",
"FilterSet",
",",
")",
",",
"dict_",
")",
"cls",
".",
"filter_class",
"=",
"filter_class",
"return",
"cls"
] | Adds a dynamic filterclass to a viewset
with all auto filters available for the field type
that are declared in a tuple auto_filter_fields
@auto_filters
def class(...):
...
auto_filters_fields('id', 'location', 'category') | [
"Adds",
"a",
"dynamic",
"filterclass",
"to",
"a",
"viewset",
"with",
"all",
"auto",
"filters",
"available",
"for",
"the",
"field",
"type",
"that",
"are",
"declared",
"in",
"a",
"tuple",
"auto_filter_fields"
] | cb34c7d662d3f96c07c10b3ed0a34bafef78b52c | https://github.com/solocompt/plugs-filter/blob/cb34c7d662d3f96c07c10b3ed0a34bafef78b52c/plugs_filter/decorators.py#L32-L58 |
250,209 | rackerlabs/rackspace-python-neutronclient | neutronclient/shell.py | env | def env(*_vars, **kwargs):
"""Search for the first defined of possibly many env vars.
Returns the first environment variable defined in vars, or
returns the default defined in kwargs.
"""
for v in _vars:
value = os.environ.get(v, None)
if value:
return value
return kwargs.get('default', '') | python | def env(*_vars, **kwargs):
"""Search for the first defined of possibly many env vars.
Returns the first environment variable defined in vars, or
returns the default defined in kwargs.
"""
for v in _vars:
value = os.environ.get(v, None)
if value:
return value
return kwargs.get('default', '') | [
"def",
"env",
"(",
"*",
"_vars",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"v",
"in",
"_vars",
":",
"value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"v",
",",
"None",
")",
"if",
"value",
":",
"return",
"value",
"return",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"''",
")"
] | Search for the first defined of possibly many env vars.
Returns the first environment variable defined in vars, or
returns the default defined in kwargs. | [
"Search",
"for",
"the",
"first",
"defined",
"of",
"possibly",
"many",
"env",
"vars",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/shell.py#L126-L137 |
250,210 | rackerlabs/rackspace-python-neutronclient | neutronclient/shell.py | NeutronShell.build_option_parser | def build_option_parser(self, description, version):
"""Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
:param version: version number for the application
:paramtype version: str
"""
parser = argparse.ArgumentParser(
description=description,
add_help=False, )
parser.add_argument(
'--version',
action='version',
version=__version__, )
parser.add_argument(
'-v', '--verbose', '--debug',
action='count',
dest='verbose_level',
default=self.DEFAULT_VERBOSE_LEVEL,
help=_('Increase verbosity of output and show tracebacks on'
' errors. You can repeat this option.'))
parser.add_argument(
'-q', '--quiet',
action='store_const',
dest='verbose_level',
const=0,
help=_('Suppress output except warnings and errors.'))
parser.add_argument(
'-h', '--help',
action=HelpAction,
nargs=0,
default=self, # tricky
help=_("Show this help message and exit."))
parser.add_argument(
'-r', '--retries',
metavar="NUM",
type=check_non_negative_int,
default=0,
help=_("How many times the request to the Neutron server should "
"be retried if it fails."))
# FIXME(bklei): this method should come from keystoneauth1
self._append_global_identity_args(parser)
return parser | python | def build_option_parser(self, description, version):
"""Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
:param version: version number for the application
:paramtype version: str
"""
parser = argparse.ArgumentParser(
description=description,
add_help=False, )
parser.add_argument(
'--version',
action='version',
version=__version__, )
parser.add_argument(
'-v', '--verbose', '--debug',
action='count',
dest='verbose_level',
default=self.DEFAULT_VERBOSE_LEVEL,
help=_('Increase verbosity of output and show tracebacks on'
' errors. You can repeat this option.'))
parser.add_argument(
'-q', '--quiet',
action='store_const',
dest='verbose_level',
const=0,
help=_('Suppress output except warnings and errors.'))
parser.add_argument(
'-h', '--help',
action=HelpAction,
nargs=0,
default=self, # tricky
help=_("Show this help message and exit."))
parser.add_argument(
'-r', '--retries',
metavar="NUM",
type=check_non_negative_int,
default=0,
help=_("How many times the request to the Neutron server should "
"be retried if it fails."))
# FIXME(bklei): this method should come from keystoneauth1
self._append_global_identity_args(parser)
return parser | [
"def",
"build_option_parser",
"(",
"self",
",",
"description",
",",
"version",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"add_help",
"=",
"False",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"__version__",
",",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"'--debug'",
",",
"action",
"=",
"'count'",
",",
"dest",
"=",
"'verbose_level'",
",",
"default",
"=",
"self",
".",
"DEFAULT_VERBOSE_LEVEL",
",",
"help",
"=",
"_",
"(",
"'Increase verbosity of output and show tracebacks on'",
"' errors. You can repeat this option.'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'verbose_level'",
",",
"const",
"=",
"0",
",",
"help",
"=",
"_",
"(",
"'Suppress output except warnings and errors.'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-h'",
",",
"'--help'",
",",
"action",
"=",
"HelpAction",
",",
"nargs",
"=",
"0",
",",
"default",
"=",
"self",
",",
"# tricky",
"help",
"=",
"_",
"(",
"\"Show this help message and exit.\"",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--retries'",
",",
"metavar",
"=",
"\"NUM\"",
",",
"type",
"=",
"check_non_negative_int",
",",
"default",
"=",
"0",
",",
"help",
"=",
"_",
"(",
"\"How many times the request to the Neutron server should \"",
"\"be retried if it fails.\"",
")",
")",
"# FIXME(bklei): this method should come from keystoneauth1",
"self",
".",
"_append_global_identity_args",
"(",
"parser",
")",
"return",
"parser"
] | Return an argparse option parser for this application.
Subclasses may override this method to extend
the parser with more global options.
:param description: full description of the application
:paramtype description: str
:param version: version number for the application
:paramtype version: str | [
"Return",
"an",
"argparse",
"option",
"parser",
"for",
"this",
"application",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/shell.py#L510-L557 |
250,211 | rackerlabs/rackspace-python-neutronclient | neutronclient/shell.py | NeutronShell._bash_completion | def _bash_completion(self):
"""Prints all of the commands and options for bash-completion."""
commands = set()
options = set()
for option, _action in self.parser._option_string_actions.items():
options.add(option)
for _name, _command in self.command_manager:
commands.add(_name)
cmd_factory = _command.load()
cmd = cmd_factory(self, None)
cmd_parser = cmd.get_parser('')
for option, _action in cmd_parser._option_string_actions.items():
options.add(option)
print(' '.join(commands | options)) | python | def _bash_completion(self):
"""Prints all of the commands and options for bash-completion."""
commands = set()
options = set()
for option, _action in self.parser._option_string_actions.items():
options.add(option)
for _name, _command in self.command_manager:
commands.add(_name)
cmd_factory = _command.load()
cmd = cmd_factory(self, None)
cmd_parser = cmd.get_parser('')
for option, _action in cmd_parser._option_string_actions.items():
options.add(option)
print(' '.join(commands | options)) | [
"def",
"_bash_completion",
"(",
"self",
")",
":",
"commands",
"=",
"set",
"(",
")",
"options",
"=",
"set",
"(",
")",
"for",
"option",
",",
"_action",
"in",
"self",
".",
"parser",
".",
"_option_string_actions",
".",
"items",
"(",
")",
":",
"options",
".",
"add",
"(",
"option",
")",
"for",
"_name",
",",
"_command",
"in",
"self",
".",
"command_manager",
":",
"commands",
".",
"add",
"(",
"_name",
")",
"cmd_factory",
"=",
"_command",
".",
"load",
"(",
")",
"cmd",
"=",
"cmd_factory",
"(",
"self",
",",
"None",
")",
"cmd_parser",
"=",
"cmd",
".",
"get_parser",
"(",
"''",
")",
"for",
"option",
",",
"_action",
"in",
"cmd_parser",
".",
"_option_string_actions",
".",
"items",
"(",
")",
":",
"options",
".",
"add",
"(",
"option",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"commands",
"|",
"options",
")",
")"
] | Prints all of the commands and options for bash-completion. | [
"Prints",
"all",
"of",
"the",
"commands",
"and",
"options",
"for",
"bash",
"-",
"completion",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/shell.py#L782-L795 |
250,212 | rackerlabs/rackspace-python-neutronclient | neutronclient/shell.py | NeutronShell.run | def run(self, argv):
"""Equivalent to the main program for the application.
:param argv: input arguments and options
:paramtype argv: list of str
"""
try:
index = 0
command_pos = -1
help_pos = -1
help_command_pos = -1
for arg in argv:
if arg == 'bash-completion' and help_command_pos == -1:
self._bash_completion()
return 0
if arg in self.commands[self.api_version]:
if command_pos == -1:
command_pos = index
elif arg in ('-h', '--help'):
if help_pos == -1:
help_pos = index
elif arg == 'help':
if help_command_pos == -1:
help_command_pos = index
index = index + 1
if command_pos > -1 and help_pos > command_pos:
argv = ['help', argv[command_pos]]
if help_command_pos > -1 and command_pos == -1:
argv[help_command_pos] = '--help'
self.options, remainder = self.parser.parse_known_args(argv)
self.configure_logging()
self.interactive_mode = not remainder
self.initialize_app(remainder)
except Exception as err:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(err)
raise
else:
self.log.error(err)
return 1
if self.interactive_mode:
_argv = [sys.argv[0]]
sys.argv = _argv
return self.interact()
return self.run_subcommand(remainder) | python | def run(self, argv):
"""Equivalent to the main program for the application.
:param argv: input arguments and options
:paramtype argv: list of str
"""
try:
index = 0
command_pos = -1
help_pos = -1
help_command_pos = -1
for arg in argv:
if arg == 'bash-completion' and help_command_pos == -1:
self._bash_completion()
return 0
if arg in self.commands[self.api_version]:
if command_pos == -1:
command_pos = index
elif arg in ('-h', '--help'):
if help_pos == -1:
help_pos = index
elif arg == 'help':
if help_command_pos == -1:
help_command_pos = index
index = index + 1
if command_pos > -1 and help_pos > command_pos:
argv = ['help', argv[command_pos]]
if help_command_pos > -1 and command_pos == -1:
argv[help_command_pos] = '--help'
self.options, remainder = self.parser.parse_known_args(argv)
self.configure_logging()
self.interactive_mode = not remainder
self.initialize_app(remainder)
except Exception as err:
if self.options.verbose_level >= self.DEBUG_LEVEL:
self.log.exception(err)
raise
else:
self.log.error(err)
return 1
if self.interactive_mode:
_argv = [sys.argv[0]]
sys.argv = _argv
return self.interact()
return self.run_subcommand(remainder) | [
"def",
"run",
"(",
"self",
",",
"argv",
")",
":",
"try",
":",
"index",
"=",
"0",
"command_pos",
"=",
"-",
"1",
"help_pos",
"=",
"-",
"1",
"help_command_pos",
"=",
"-",
"1",
"for",
"arg",
"in",
"argv",
":",
"if",
"arg",
"==",
"'bash-completion'",
"and",
"help_command_pos",
"==",
"-",
"1",
":",
"self",
".",
"_bash_completion",
"(",
")",
"return",
"0",
"if",
"arg",
"in",
"self",
".",
"commands",
"[",
"self",
".",
"api_version",
"]",
":",
"if",
"command_pos",
"==",
"-",
"1",
":",
"command_pos",
"=",
"index",
"elif",
"arg",
"in",
"(",
"'-h'",
",",
"'--help'",
")",
":",
"if",
"help_pos",
"==",
"-",
"1",
":",
"help_pos",
"=",
"index",
"elif",
"arg",
"==",
"'help'",
":",
"if",
"help_command_pos",
"==",
"-",
"1",
":",
"help_command_pos",
"=",
"index",
"index",
"=",
"index",
"+",
"1",
"if",
"command_pos",
">",
"-",
"1",
"and",
"help_pos",
">",
"command_pos",
":",
"argv",
"=",
"[",
"'help'",
",",
"argv",
"[",
"command_pos",
"]",
"]",
"if",
"help_command_pos",
">",
"-",
"1",
"and",
"command_pos",
"==",
"-",
"1",
":",
"argv",
"[",
"help_command_pos",
"]",
"=",
"'--help'",
"self",
".",
"options",
",",
"remainder",
"=",
"self",
".",
"parser",
".",
"parse_known_args",
"(",
"argv",
")",
"self",
".",
"configure_logging",
"(",
")",
"self",
".",
"interactive_mode",
"=",
"not",
"remainder",
"self",
".",
"initialize_app",
"(",
"remainder",
")",
"except",
"Exception",
"as",
"err",
":",
"if",
"self",
".",
"options",
".",
"verbose_level",
">=",
"self",
".",
"DEBUG_LEVEL",
":",
"self",
".",
"log",
".",
"exception",
"(",
"err",
")",
"raise",
"else",
":",
"self",
".",
"log",
".",
"error",
"(",
"err",
")",
"return",
"1",
"if",
"self",
".",
"interactive_mode",
":",
"_argv",
"=",
"[",
"sys",
".",
"argv",
"[",
"0",
"]",
"]",
"sys",
".",
"argv",
"=",
"_argv",
"return",
"self",
".",
"interact",
"(",
")",
"return",
"self",
".",
"run_subcommand",
"(",
"remainder",
")"
] | Equivalent to the main program for the application.
:param argv: input arguments and options
:paramtype argv: list of str | [
"Equivalent",
"to",
"the",
"main",
"program",
"for",
"the",
"application",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/shell.py#L820-L864 |
250,213 | rackerlabs/rackspace-python-neutronclient | neutronclient/shell.py | NeutronShell.authenticate_user | def authenticate_user(self):
"""Confirm user authentication
Make sure the user has provided all of the authentication
info we need.
"""
cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
cloud=self.options.os_cloud, argparse=self.options,
network_api_version=self.api_version,
verify=not self.options.insecure)
verify, cert = cloud_config.get_requests_verify_args()
# TODO(singhj): Remove dependancy on HTTPClient
# for the case of token-endpoint authentication
# When using token-endpoint authentication legacy
# HTTPClient will be used, otherwise SessionClient
# will be used.
if self.options.os_token and self.options.os_url:
auth = None
auth_session = None
else:
auth = cloud_config.get_auth()
auth_session = session.Session(
auth=auth, verify=verify, cert=cert,
timeout=self.options.http_timeout)
interface = self.options.os_endpoint_type or self.endpoint_type
if interface.endswith('URL'):
interface = interface[:-3]
self.client_manager = clientmanager.ClientManager(
retries=self.options.retries,
raise_errors=False,
session=auth_session,
url=self.options.os_url,
token=self.options.os_token,
region_name=cloud_config.get_region_name(),
api_version=cloud_config.get_api_version('network'),
service_type=cloud_config.get_service_type('network'),
service_name=cloud_config.get_service_name('network'),
endpoint_type=interface,
auth=auth,
insecure=not verify,
log_credentials=True)
return | python | def authenticate_user(self):
"""Confirm user authentication
Make sure the user has provided all of the authentication
info we need.
"""
cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
cloud=self.options.os_cloud, argparse=self.options,
network_api_version=self.api_version,
verify=not self.options.insecure)
verify, cert = cloud_config.get_requests_verify_args()
# TODO(singhj): Remove dependancy on HTTPClient
# for the case of token-endpoint authentication
# When using token-endpoint authentication legacy
# HTTPClient will be used, otherwise SessionClient
# will be used.
if self.options.os_token and self.options.os_url:
auth = None
auth_session = None
else:
auth = cloud_config.get_auth()
auth_session = session.Session(
auth=auth, verify=verify, cert=cert,
timeout=self.options.http_timeout)
interface = self.options.os_endpoint_type or self.endpoint_type
if interface.endswith('URL'):
interface = interface[:-3]
self.client_manager = clientmanager.ClientManager(
retries=self.options.retries,
raise_errors=False,
session=auth_session,
url=self.options.os_url,
token=self.options.os_token,
region_name=cloud_config.get_region_name(),
api_version=cloud_config.get_api_version('network'),
service_type=cloud_config.get_service_type('network'),
service_name=cloud_config.get_service_name('network'),
endpoint_type=interface,
auth=auth,
insecure=not verify,
log_credentials=True)
return | [
"def",
"authenticate_user",
"(",
"self",
")",
":",
"cloud_config",
"=",
"os_client_config",
".",
"OpenStackConfig",
"(",
")",
".",
"get_one_cloud",
"(",
"cloud",
"=",
"self",
".",
"options",
".",
"os_cloud",
",",
"argparse",
"=",
"self",
".",
"options",
",",
"network_api_version",
"=",
"self",
".",
"api_version",
",",
"verify",
"=",
"not",
"self",
".",
"options",
".",
"insecure",
")",
"verify",
",",
"cert",
"=",
"cloud_config",
".",
"get_requests_verify_args",
"(",
")",
"# TODO(singhj): Remove dependancy on HTTPClient",
"# for the case of token-endpoint authentication",
"# When using token-endpoint authentication legacy",
"# HTTPClient will be used, otherwise SessionClient",
"# will be used.",
"if",
"self",
".",
"options",
".",
"os_token",
"and",
"self",
".",
"options",
".",
"os_url",
":",
"auth",
"=",
"None",
"auth_session",
"=",
"None",
"else",
":",
"auth",
"=",
"cloud_config",
".",
"get_auth",
"(",
")",
"auth_session",
"=",
"session",
".",
"Session",
"(",
"auth",
"=",
"auth",
",",
"verify",
"=",
"verify",
",",
"cert",
"=",
"cert",
",",
"timeout",
"=",
"self",
".",
"options",
".",
"http_timeout",
")",
"interface",
"=",
"self",
".",
"options",
".",
"os_endpoint_type",
"or",
"self",
".",
"endpoint_type",
"if",
"interface",
".",
"endswith",
"(",
"'URL'",
")",
":",
"interface",
"=",
"interface",
"[",
":",
"-",
"3",
"]",
"self",
".",
"client_manager",
"=",
"clientmanager",
".",
"ClientManager",
"(",
"retries",
"=",
"self",
".",
"options",
".",
"retries",
",",
"raise_errors",
"=",
"False",
",",
"session",
"=",
"auth_session",
",",
"url",
"=",
"self",
".",
"options",
".",
"os_url",
",",
"token",
"=",
"self",
".",
"options",
".",
"os_token",
",",
"region_name",
"=",
"cloud_config",
".",
"get_region_name",
"(",
")",
",",
"api_version",
"=",
"cloud_config",
".",
"get_api_version",
"(",
"'network'",
")",
",",
"service_type",
"=",
"cloud_config",
".",
"get_service_type",
"(",
"'network'",
")",
",",
"service_name",
"=",
"cloud_config",
".",
"get_service_name",
"(",
"'network'",
")",
",",
"endpoint_type",
"=",
"interface",
",",
"auth",
"=",
"auth",
",",
"insecure",
"=",
"not",
"verify",
",",
"log_credentials",
"=",
"True",
")",
"return"
] | Confirm user authentication
Make sure the user has provided all of the authentication
info we need. | [
"Confirm",
"user",
"authentication"
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/shell.py#L889-L934 |
250,214 | rackerlabs/rackspace-python-neutronclient | neutronclient/shell.py | NeutronShell.configure_logging | def configure_logging(self):
"""Create logging handlers for any log output."""
root_logger = logging.getLogger('')
# Set up logging to a file
root_logger.setLevel(logging.DEBUG)
# Send higher-level messages to the console via stderr
console = logging.StreamHandler(self.stderr)
console_level = {self.WARNING_LEVEL: logging.WARNING,
self.INFO_LEVEL: logging.INFO,
self.DEBUG_LEVEL: logging.DEBUG,
}.get(self.options.verbose_level, logging.DEBUG)
# The default log level is INFO, in this situation, set the
# log level of the console to WARNING, to avoid displaying
# useless messages. This equals using "--quiet"
if console_level == logging.INFO:
console.setLevel(logging.WARNING)
else:
console.setLevel(console_level)
if logging.DEBUG == console_level:
formatter = logging.Formatter(self.DEBUG_MESSAGE_FORMAT)
else:
formatter = logging.Formatter(self.CONSOLE_MESSAGE_FORMAT)
logging.getLogger('iso8601.iso8601').setLevel(logging.WARNING)
logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
console.setFormatter(formatter)
root_logger.addHandler(console)
return | python | def configure_logging(self):
"""Create logging handlers for any log output."""
root_logger = logging.getLogger('')
# Set up logging to a file
root_logger.setLevel(logging.DEBUG)
# Send higher-level messages to the console via stderr
console = logging.StreamHandler(self.stderr)
console_level = {self.WARNING_LEVEL: logging.WARNING,
self.INFO_LEVEL: logging.INFO,
self.DEBUG_LEVEL: logging.DEBUG,
}.get(self.options.verbose_level, logging.DEBUG)
# The default log level is INFO, in this situation, set the
# log level of the console to WARNING, to avoid displaying
# useless messages. This equals using "--quiet"
if console_level == logging.INFO:
console.setLevel(logging.WARNING)
else:
console.setLevel(console_level)
if logging.DEBUG == console_level:
formatter = logging.Formatter(self.DEBUG_MESSAGE_FORMAT)
else:
formatter = logging.Formatter(self.CONSOLE_MESSAGE_FORMAT)
logging.getLogger('iso8601.iso8601').setLevel(logging.WARNING)
logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
console.setFormatter(formatter)
root_logger.addHandler(console)
return | [
"def",
"configure_logging",
"(",
"self",
")",
":",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
"''",
")",
"# Set up logging to a file",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# Send higher-level messages to the console via stderr",
"console",
"=",
"logging",
".",
"StreamHandler",
"(",
"self",
".",
"stderr",
")",
"console_level",
"=",
"{",
"self",
".",
"WARNING_LEVEL",
":",
"logging",
".",
"WARNING",
",",
"self",
".",
"INFO_LEVEL",
":",
"logging",
".",
"INFO",
",",
"self",
".",
"DEBUG_LEVEL",
":",
"logging",
".",
"DEBUG",
",",
"}",
".",
"get",
"(",
"self",
".",
"options",
".",
"verbose_level",
",",
"logging",
".",
"DEBUG",
")",
"# The default log level is INFO, in this situation, set the",
"# log level of the console to WARNING, to avoid displaying",
"# useless messages. This equals using \"--quiet\"",
"if",
"console_level",
"==",
"logging",
".",
"INFO",
":",
"console",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"else",
":",
"console",
".",
"setLevel",
"(",
"console_level",
")",
"if",
"logging",
".",
"DEBUG",
"==",
"console_level",
":",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"self",
".",
"DEBUG_MESSAGE_FORMAT",
")",
"else",
":",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"self",
".",
"CONSOLE_MESSAGE_FORMAT",
")",
"logging",
".",
"getLogger",
"(",
"'iso8601.iso8601'",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"logging",
".",
"getLogger",
"(",
"'urllib3.connectionpool'",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"console",
".",
"setFormatter",
"(",
"formatter",
")",
"root_logger",
".",
"addHandler",
"(",
"console",
")",
"return"
] | Create logging handlers for any log output. | [
"Create",
"logging",
"handlers",
"for",
"any",
"log",
"output",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/shell.py#L956-L984 |
250,215 | TheOneHyer/arandomness | build/lib.linux-x86_64-3.6/arandomness/str/max_substring.py | max_substring | def max_substring(words, position=0, _last_letter=''):
"""Finds max substring shared by all strings starting at position
Args:
words (list): list of unicode of all words to compare
position (int): starting position in each word to begin analyzing
for substring
_last_letter (unicode): last common letter, only for use
internally unless you really know what
you are doing
Returns:
unicode: max str common to all words
Examples:
.. code-block:: Python
>>> max_substring(['aaaa', 'aaab', 'aaac'])
'aaa'
>>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1)
'bbb'
>>> max_substring(['abc', 'bcd', 'cde'])
''
"""
# If end of word is reached, begin reconstructing the substring
try:
letter = [word[position] for word in words]
except IndexError:
return _last_letter
# Recurse if position matches, else begin reconstructing the substring
if all(l == letter[0] for l in letter) is True:
_last_letter += max_substring(words, position=position + 1,
_last_letter=letter[0])
return _last_letter
else:
return _last_letter | python | def max_substring(words, position=0, _last_letter=''):
"""Finds max substring shared by all strings starting at position
Args:
words (list): list of unicode of all words to compare
position (int): starting position in each word to begin analyzing
for substring
_last_letter (unicode): last common letter, only for use
internally unless you really know what
you are doing
Returns:
unicode: max str common to all words
Examples:
.. code-block:: Python
>>> max_substring(['aaaa', 'aaab', 'aaac'])
'aaa'
>>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1)
'bbb'
>>> max_substring(['abc', 'bcd', 'cde'])
''
"""
# If end of word is reached, begin reconstructing the substring
try:
letter = [word[position] for word in words]
except IndexError:
return _last_letter
# Recurse if position matches, else begin reconstructing the substring
if all(l == letter[0] for l in letter) is True:
_last_letter += max_substring(words, position=position + 1,
_last_letter=letter[0])
return _last_letter
else:
return _last_letter | [
"def",
"max_substring",
"(",
"words",
",",
"position",
"=",
"0",
",",
"_last_letter",
"=",
"''",
")",
":",
"# If end of word is reached, begin reconstructing the substring",
"try",
":",
"letter",
"=",
"[",
"word",
"[",
"position",
"]",
"for",
"word",
"in",
"words",
"]",
"except",
"IndexError",
":",
"return",
"_last_letter",
"# Recurse if position matches, else begin reconstructing the substring",
"if",
"all",
"(",
"l",
"==",
"letter",
"[",
"0",
"]",
"for",
"l",
"in",
"letter",
")",
"is",
"True",
":",
"_last_letter",
"+=",
"max_substring",
"(",
"words",
",",
"position",
"=",
"position",
"+",
"1",
",",
"_last_letter",
"=",
"letter",
"[",
"0",
"]",
")",
"return",
"_last_letter",
"else",
":",
"return",
"_last_letter"
] | Finds max substring shared by all strings starting at position
Args:
words (list): list of unicode of all words to compare
position (int): starting position in each word to begin analyzing
for substring
_last_letter (unicode): last common letter, only for use
internally unless you really know what
you are doing
Returns:
unicode: max str common to all words
Examples:
.. code-block:: Python
>>> max_substring(['aaaa', 'aaab', 'aaac'])
'aaa'
>>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1)
'bbb'
>>> max_substring(['abc', 'bcd', 'cde'])
'' | [
"Finds",
"max",
"substring",
"shared",
"by",
"all",
"strings",
"starting",
"at",
"position"
] | ae9f630e9a1d67b0eb6d61644a49756de8a5268c | https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/str/max_substring.py#L31-L71 |
250,216 | abhinav/reversible | reversible/tornado/generator.py | _map_generator | def _map_generator(f, generator):
"""Apply ``f`` to the results of the given bi-directional generator.
Unfortunately, generator comprehension (``f(x) for x in gen``) does not
work for as expected for bi-directional generators. It won't send
exceptions and results back.
This function implements a map function for generators that sends values
and exceptions back and forth as expected.
"""
item = next(generator)
while True:
try:
result = yield f(item)
except Exception:
item = generator.throw(*sys.exc_info())
else:
item = generator.send(result) | python | def _map_generator(f, generator):
"""Apply ``f`` to the results of the given bi-directional generator.
Unfortunately, generator comprehension (``f(x) for x in gen``) does not
work for as expected for bi-directional generators. It won't send
exceptions and results back.
This function implements a map function for generators that sends values
and exceptions back and forth as expected.
"""
item = next(generator)
while True:
try:
result = yield f(item)
except Exception:
item = generator.throw(*sys.exc_info())
else:
item = generator.send(result) | [
"def",
"_map_generator",
"(",
"f",
",",
"generator",
")",
":",
"item",
"=",
"next",
"(",
"generator",
")",
"while",
"True",
":",
"try",
":",
"result",
"=",
"yield",
"f",
"(",
"item",
")",
"except",
"Exception",
":",
"item",
"=",
"generator",
".",
"throw",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"else",
":",
"item",
"=",
"generator",
".",
"send",
"(",
"result",
")"
] | Apply ``f`` to the results of the given bi-directional generator.
Unfortunately, generator comprehension (``f(x) for x in gen``) does not
work for as expected for bi-directional generators. It won't send
exceptions and results back.
This function implements a map function for generators that sends values
and exceptions back and forth as expected. | [
"Apply",
"f",
"to",
"the",
"results",
"of",
"the",
"given",
"bi",
"-",
"directional",
"generator",
"."
] | 7e28aaf0390f7d4b889c6ac14d7b340f8f314e89 | https://github.com/abhinav/reversible/blob/7e28aaf0390f7d4b889c6ac14d7b340f8f314e89/reversible/tornado/generator.py#L34-L51 |
250,217 | patrickayoup/md2remark | md2remark/main.py | compile_markdown_file | def compile_markdown_file(source_file):
'''Compiles a single markdown file to a remark.js slideshow.'''
template = pkg_resources.resource_string('md2remark.resources.templates', 'slideshow.mustache')
renderer = pystache.Renderer(search_dirs='./templates')
f = open(source_file, 'r')
slideshow_md = f.read()
f.close()
slideshow_name = os.path.split(source_file)[1].split('.')[0]
rendered_text = renderer.render(template, {'title': slideshow_name, 'slideshow': slideshow_md})
if not os.path.exists('md2remark_build'):
os.makedirs('md2remark_build')
f = open(os.path.join('md2remark_build', slideshow_name + '.html'), 'w')
f.write(rendered_text)
f.close() | python | def compile_markdown_file(source_file):
'''Compiles a single markdown file to a remark.js slideshow.'''
template = pkg_resources.resource_string('md2remark.resources.templates', 'slideshow.mustache')
renderer = pystache.Renderer(search_dirs='./templates')
f = open(source_file, 'r')
slideshow_md = f.read()
f.close()
slideshow_name = os.path.split(source_file)[1].split('.')[0]
rendered_text = renderer.render(template, {'title': slideshow_name, 'slideshow': slideshow_md})
if not os.path.exists('md2remark_build'):
os.makedirs('md2remark_build')
f = open(os.path.join('md2remark_build', slideshow_name + '.html'), 'w')
f.write(rendered_text)
f.close() | [
"def",
"compile_markdown_file",
"(",
"source_file",
")",
":",
"template",
"=",
"pkg_resources",
".",
"resource_string",
"(",
"'md2remark.resources.templates'",
",",
"'slideshow.mustache'",
")",
"renderer",
"=",
"pystache",
".",
"Renderer",
"(",
"search_dirs",
"=",
"'./templates'",
")",
"f",
"=",
"open",
"(",
"source_file",
",",
"'r'",
")",
"slideshow_md",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"slideshow_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"source_file",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"rendered_text",
"=",
"renderer",
".",
"render",
"(",
"template",
",",
"{",
"'title'",
":",
"slideshow_name",
",",
"'slideshow'",
":",
"slideshow_md",
"}",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'md2remark_build'",
")",
":",
"os",
".",
"makedirs",
"(",
"'md2remark_build'",
")",
"f",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'md2remark_build'",
",",
"slideshow_name",
"+",
"'.html'",
")",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"rendered_text",
")",
"f",
".",
"close",
"(",
")"
] | Compiles a single markdown file to a remark.js slideshow. | [
"Compiles",
"a",
"single",
"markdown",
"file",
"to",
"a",
"remark",
".",
"js",
"slideshow",
"."
] | 04e66462046cd123c5b1810454d949c3a05bc057 | https://github.com/patrickayoup/md2remark/blob/04e66462046cd123c5b1810454d949c3a05bc057/md2remark/main.py#L8-L26 |
250,218 | patrickayoup/md2remark | md2remark/main.py | compile_slides | def compile_slides(source):
'''Compiles the source to a remark.js slideshow.'''
# if it's a directory, do all md files.
if os.path.isdir(source):
for f in os.listdir(source):
if f.lower().endswith('.md'):
compile_markdown_file(os.path.join(source, f))
else:
compile_markdown_file(source) | python | def compile_slides(source):
'''Compiles the source to a remark.js slideshow.'''
# if it's a directory, do all md files.
if os.path.isdir(source):
for f in os.listdir(source):
if f.lower().endswith('.md'):
compile_markdown_file(os.path.join(source, f))
else:
compile_markdown_file(source) | [
"def",
"compile_slides",
"(",
"source",
")",
":",
"# if it's a directory, do all md files.",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"source",
")",
":",
"if",
"f",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.md'",
")",
":",
"compile_markdown_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"source",
",",
"f",
")",
")",
"else",
":",
"compile_markdown_file",
"(",
"source",
")"
] | Compiles the source to a remark.js slideshow. | [
"Compiles",
"the",
"source",
"to",
"a",
"remark",
".",
"js",
"slideshow",
"."
] | 04e66462046cd123c5b1810454d949c3a05bc057 | https://github.com/patrickayoup/md2remark/blob/04e66462046cd123c5b1810454d949c3a05bc057/md2remark/main.py#L28-L36 |
250,219 | patrickayoup/md2remark | md2remark/main.py | parse_cl_args | def parse_cl_args(arg_vector):
'''Parses the command line arguments'''
parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js')
parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the current working directory under a md2remark_build subdirectory.')
return parser.parse_args(arg_vector) | python | def parse_cl_args(arg_vector):
'''Parses the command line arguments'''
parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js')
parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the current working directory under a md2remark_build subdirectory.')
return parser.parse_args(arg_vector) | [
"def",
"parse_cl_args",
"(",
"arg_vector",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Compiles markdown files into html files for remark.js'",
")",
"parser",
".",
"add_argument",
"(",
"'source'",
",",
"metavar",
"=",
"'source'",
",",
"help",
"=",
"'the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the current working directory under a md2remark_build subdirectory.'",
")",
"return",
"parser",
".",
"parse_args",
"(",
"arg_vector",
")"
] | Parses the command line arguments | [
"Parses",
"the",
"command",
"line",
"arguments"
] | 04e66462046cd123c5b1810454d949c3a05bc057 | https://github.com/patrickayoup/md2remark/blob/04e66462046cd123c5b1810454d949c3a05bc057/md2remark/main.py#L38-L43 |
250,220 | sirrice/scorpionsql | scorpionsql/sql.py | Query.get_filter_qobj | def get_filter_qobj(self, keys=None):
"""
Return a copy of this Query object with additional where clauses for the
keys in the argument
"""
# only care about columns in aggregates right?
cols = set()
for agg in self.select.aggregates:
cols.update(agg.cols)
sels = [SelectExpr(col, [col], col, None) for col in cols]
select = Select(sels)
where = list(self.where)
if keys:
keys = list(keys)
keys = map(sqlize, list(keys))
expr = self.select.nonaggs[0].expr
clause = []
if None in keys:
clause.append("%s is null" % expr)
if len([k for k in keys if k is not None]) > 0:
clause.append("%s in %%s" % expr)
clause = " or ".join(clause)
where.append(clause)
else:
where.append( '%s = %%s' % (self.select.nonaggs[0].expr ) )
q = Query(self.db, select, self.fr, where)
return q | python | def get_filter_qobj(self, keys=None):
"""
Return a copy of this Query object with additional where clauses for the
keys in the argument
"""
# only care about columns in aggregates right?
cols = set()
for agg in self.select.aggregates:
cols.update(agg.cols)
sels = [SelectExpr(col, [col], col, None) for col in cols]
select = Select(sels)
where = list(self.where)
if keys:
keys = list(keys)
keys = map(sqlize, list(keys))
expr = self.select.nonaggs[0].expr
clause = []
if None in keys:
clause.append("%s is null" % expr)
if len([k for k in keys if k is not None]) > 0:
clause.append("%s in %%s" % expr)
clause = " or ".join(clause)
where.append(clause)
else:
where.append( '%s = %%s' % (self.select.nonaggs[0].expr ) )
q = Query(self.db, select, self.fr, where)
return q | [
"def",
"get_filter_qobj",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"# only care about columns in aggregates right?",
"cols",
"=",
"set",
"(",
")",
"for",
"agg",
"in",
"self",
".",
"select",
".",
"aggregates",
":",
"cols",
".",
"update",
"(",
"agg",
".",
"cols",
")",
"sels",
"=",
"[",
"SelectExpr",
"(",
"col",
",",
"[",
"col",
"]",
",",
"col",
",",
"None",
")",
"for",
"col",
"in",
"cols",
"]",
"select",
"=",
"Select",
"(",
"sels",
")",
"where",
"=",
"list",
"(",
"self",
".",
"where",
")",
"if",
"keys",
":",
"keys",
"=",
"list",
"(",
"keys",
")",
"keys",
"=",
"map",
"(",
"sqlize",
",",
"list",
"(",
"keys",
")",
")",
"expr",
"=",
"self",
".",
"select",
".",
"nonaggs",
"[",
"0",
"]",
".",
"expr",
"clause",
"=",
"[",
"]",
"if",
"None",
"in",
"keys",
":",
"clause",
".",
"append",
"(",
"\"%s is null\"",
"%",
"expr",
")",
"if",
"len",
"(",
"[",
"k",
"for",
"k",
"in",
"keys",
"if",
"k",
"is",
"not",
"None",
"]",
")",
">",
"0",
":",
"clause",
".",
"append",
"(",
"\"%s in %%s\"",
"%",
"expr",
")",
"clause",
"=",
"\" or \"",
".",
"join",
"(",
"clause",
")",
"where",
".",
"append",
"(",
"clause",
")",
"else",
":",
"where",
".",
"append",
"(",
"'%s = %%s'",
"%",
"(",
"self",
".",
"select",
".",
"nonaggs",
"[",
"0",
"]",
".",
"expr",
")",
")",
"q",
"=",
"Query",
"(",
"self",
".",
"db",
",",
"select",
",",
"self",
".",
"fr",
",",
"where",
")",
"return",
"q"
] | Return a copy of this Query object with additional where clauses for the
keys in the argument | [
"Return",
"a",
"copy",
"of",
"this",
"Query",
"object",
"with",
"additional",
"where",
"clauses",
"for",
"the",
"keys",
"in",
"the",
"argument"
] | baa05b745fae5df3171244c3e32160bd36c99e86 | https://github.com/sirrice/scorpionsql/blob/baa05b745fae5df3171244c3e32160bd36c99e86/scorpionsql/sql.py#L123-L150 |
250,221 | noroute/teamcity-buildchain-stats | tc_buildchain_stats/gatherer.py | BuildChainStatsGatherer.total_build_duration_for_chain | def total_build_duration_for_chain(self, build_chain_id):
"""Returns the total duration for one specific build chain run"""
return sum([
int(self.__build_duration_for_id(id))
for id in self.__build_ids_of_chain(build_chain_id)
]) | python | def total_build_duration_for_chain(self, build_chain_id):
"""Returns the total duration for one specific build chain run"""
return sum([
int(self.__build_duration_for_id(id))
for id in self.__build_ids_of_chain(build_chain_id)
]) | [
"def",
"total_build_duration_for_chain",
"(",
"self",
",",
"build_chain_id",
")",
":",
"return",
"sum",
"(",
"[",
"int",
"(",
"self",
".",
"__build_duration_for_id",
"(",
"id",
")",
")",
"for",
"id",
"in",
"self",
".",
"__build_ids_of_chain",
"(",
"build_chain_id",
")",
"]",
")"
] | Returns the total duration for one specific build chain run | [
"Returns",
"the",
"total",
"duration",
"for",
"one",
"specific",
"build",
"chain",
"run"
] | 54fd7194cd2b7b02dc137e7a9ed013aac96af841 | https://github.com/noroute/teamcity-buildchain-stats/blob/54fd7194cd2b7b02dc137e7a9ed013aac96af841/tc_buildchain_stats/gatherer.py#L101-L106 |
250,222 | noroute/teamcity-buildchain-stats | tc_buildchain_stats/gatherer.py | BuildChainStatsGatherer.build_cycle_time | def build_cycle_time(self, build_id):
"""Returns a BuildCycleTime object for the given build"""
json_form = self.__retrieve_as_json(self.builds_path % build_id)
return BuildCycleTime(
build_id,
json_form[u'buildTypeId'],
as_date(json_form, u'startDate'),
(as_date(json_form, u'finishDate') - as_date(json_form, u'queuedDate')).seconds * 1000
) | python | def build_cycle_time(self, build_id):
"""Returns a BuildCycleTime object for the given build"""
json_form = self.__retrieve_as_json(self.builds_path % build_id)
return BuildCycleTime(
build_id,
json_form[u'buildTypeId'],
as_date(json_form, u'startDate'),
(as_date(json_form, u'finishDate') - as_date(json_form, u'queuedDate')).seconds * 1000
) | [
"def",
"build_cycle_time",
"(",
"self",
",",
"build_id",
")",
":",
"json_form",
"=",
"self",
".",
"__retrieve_as_json",
"(",
"self",
".",
"builds_path",
"%",
"build_id",
")",
"return",
"BuildCycleTime",
"(",
"build_id",
",",
"json_form",
"[",
"u'buildTypeId'",
"]",
",",
"as_date",
"(",
"json_form",
",",
"u'startDate'",
")",
",",
"(",
"as_date",
"(",
"json_form",
",",
"u'finishDate'",
")",
"-",
"as_date",
"(",
"json_form",
",",
"u'queuedDate'",
")",
")",
".",
"seconds",
"*",
"1000",
")"
] | Returns a BuildCycleTime object for the given build | [
"Returns",
"a",
"BuildCycleTime",
"object",
"for",
"the",
"given",
"build"
] | 54fd7194cd2b7b02dc137e7a9ed013aac96af841 | https://github.com/noroute/teamcity-buildchain-stats/blob/54fd7194cd2b7b02dc137e7a9ed013aac96af841/tc_buildchain_stats/gatherer.py#L123-L131 |
250,223 | noroute/teamcity-buildchain-stats | tc_buildchain_stats/gatherer.py | BuildChainStatsGatherer.build_stats_for_chain | def build_stats_for_chain(self, build_chain_id):
"""Returns a list of Build tuples for all elements in the build chain.
This method allows insight into the runtime of each configuratio inside the build chain.
"""
json_form = self.__retrieve_as_json(self.build_chain_path % build_chain_id)
builds = [{'build_id': build[u'id'], 'configuration_id': build[u'buildTypeId']} for build in json_form[u'build']]
return [
BuildStat(
build['build_id'],
build['configuration_id'],
self.__build_duration_for_id(build['build_id']),
self.__build_start_date_for_id(build['build_id']))
for build in builds
] | python | def build_stats_for_chain(self, build_chain_id):
"""Returns a list of Build tuples for all elements in the build chain.
This method allows insight into the runtime of each configuratio inside the build chain.
"""
json_form = self.__retrieve_as_json(self.build_chain_path % build_chain_id)
builds = [{'build_id': build[u'id'], 'configuration_id': build[u'buildTypeId']} for build in json_form[u'build']]
return [
BuildStat(
build['build_id'],
build['configuration_id'],
self.__build_duration_for_id(build['build_id']),
self.__build_start_date_for_id(build['build_id']))
for build in builds
] | [
"def",
"build_stats_for_chain",
"(",
"self",
",",
"build_chain_id",
")",
":",
"json_form",
"=",
"self",
".",
"__retrieve_as_json",
"(",
"self",
".",
"build_chain_path",
"%",
"build_chain_id",
")",
"builds",
"=",
"[",
"{",
"'build_id'",
":",
"build",
"[",
"u'id'",
"]",
",",
"'configuration_id'",
":",
"build",
"[",
"u'buildTypeId'",
"]",
"}",
"for",
"build",
"in",
"json_form",
"[",
"u'build'",
"]",
"]",
"return",
"[",
"BuildStat",
"(",
"build",
"[",
"'build_id'",
"]",
",",
"build",
"[",
"'configuration_id'",
"]",
",",
"self",
".",
"__build_duration_for_id",
"(",
"build",
"[",
"'build_id'",
"]",
")",
",",
"self",
".",
"__build_start_date_for_id",
"(",
"build",
"[",
"'build_id'",
"]",
")",
")",
"for",
"build",
"in",
"builds",
"]"
] | Returns a list of Build tuples for all elements in the build chain.
This method allows insight into the runtime of each configuratio inside the build chain. | [
"Returns",
"a",
"list",
"of",
"Build",
"tuples",
"for",
"all",
"elements",
"in",
"the",
"build",
"chain",
"."
] | 54fd7194cd2b7b02dc137e7a9ed013aac96af841 | https://github.com/noroute/teamcity-buildchain-stats/blob/54fd7194cd2b7b02dc137e7a9ed013aac96af841/tc_buildchain_stats/gatherer.py#L133-L148 |
250,224 | mirca/muchbettermoments | muchbettermoments.py | quadratic_2d | def quadratic_2d(data):
"""
Compute the quadratic estimate of the centroid in a 2d-array.
Args:
data (2darray): two dimensional data array
Returns
center (tuple): centroid estimate on the row and column directions,
respectively
"""
arg_data_max = np.argmax(data)
i, j = np.unravel_index(arg_data_max, data.shape)
z_ = data[i-1:i+2, j-1:j+2]
# our quadratic function is defined as
# f(x, y | a, b, c, d, e, f) := a + b * x + c * y + d * x^2 + e * xy + f * y^2
# therefore, the best fit coeffiecients are given as
# note that they are unique and the uncertainty in each of them (#TODO) can be
# computed following the derivations done by Vakili & Hogg (2016) and
# Teague & Foreman-Mackey (2018)
try:
a = (-z_[0,0] + 2*z_[0,1] - z_[0,2] + 2*z_[1,0] + 5*z_[1,1] + 2*z_[1,2] -
z_[2,0] + 2*z_[2,1] - z_[2,2]) / 9
b = (-z_[0,0] - z_[0,1] - z_[0,2] + z_[2,0] + z_[2,1] + z_[2,2]) / 6
c = (-z_[0,0] + z_[0,2] - z_[1,0] + z_[1,2] - z_[2,0] + z_[2,2]) / 6
d = (z_[0,0] + z_[0,1] + z_[0,2] - z_[1,0]*2 - z_[1,1]*2 - z_[1,2]*2 +
z_[2,0] + z_[2,1] + z_[2,2])/6
e = (z_[0,0] - z_[0,2] - z_[2,0] + z_[2,2]) * .25
f = (z_[0,0] - 2 * z_[0,1] + z_[0,2] + z_[1,0] - 2 * z_[1,1] + z_[1,2] +
z_[2,0] - 2 * z_[2,1] + z_[2,2]) / 6
except IndexError:
return (i, j)
# see https://en.wikipedia.org/wiki/Quadratic_function
det = 4 * d * f - e ** 2
xm = - (2 * f * b - c * e) / det
ym = - (2 * d * c - b * e) / det
return (i+xm, j+ym) | python | def quadratic_2d(data):
"""
Compute the quadratic estimate of the centroid in a 2d-array.
Args:
data (2darray): two dimensional data array
Returns
center (tuple): centroid estimate on the row and column directions,
respectively
"""
arg_data_max = np.argmax(data)
i, j = np.unravel_index(arg_data_max, data.shape)
z_ = data[i-1:i+2, j-1:j+2]
# our quadratic function is defined as
# f(x, y | a, b, c, d, e, f) := a + b * x + c * y + d * x^2 + e * xy + f * y^2
# therefore, the best fit coeffiecients are given as
# note that they are unique and the uncertainty in each of them (#TODO) can be
# computed following the derivations done by Vakili & Hogg (2016) and
# Teague & Foreman-Mackey (2018)
try:
a = (-z_[0,0] + 2*z_[0,1] - z_[0,2] + 2*z_[1,0] + 5*z_[1,1] + 2*z_[1,2] -
z_[2,0] + 2*z_[2,1] - z_[2,2]) / 9
b = (-z_[0,0] - z_[0,1] - z_[0,2] + z_[2,0] + z_[2,1] + z_[2,2]) / 6
c = (-z_[0,0] + z_[0,2] - z_[1,0] + z_[1,2] - z_[2,0] + z_[2,2]) / 6
d = (z_[0,0] + z_[0,1] + z_[0,2] - z_[1,0]*2 - z_[1,1]*2 - z_[1,2]*2 +
z_[2,0] + z_[2,1] + z_[2,2])/6
e = (z_[0,0] - z_[0,2] - z_[2,0] + z_[2,2]) * .25
f = (z_[0,0] - 2 * z_[0,1] + z_[0,2] + z_[1,0] - 2 * z_[1,1] + z_[1,2] +
z_[2,0] - 2 * z_[2,1] + z_[2,2]) / 6
except IndexError:
return (i, j)
# see https://en.wikipedia.org/wiki/Quadratic_function
det = 4 * d * f - e ** 2
xm = - (2 * f * b - c * e) / det
ym = - (2 * d * c - b * e) / det
return (i+xm, j+ym) | [
"def",
"quadratic_2d",
"(",
"data",
")",
":",
"arg_data_max",
"=",
"np",
".",
"argmax",
"(",
"data",
")",
"i",
",",
"j",
"=",
"np",
".",
"unravel_index",
"(",
"arg_data_max",
",",
"data",
".",
"shape",
")",
"z_",
"=",
"data",
"[",
"i",
"-",
"1",
":",
"i",
"+",
"2",
",",
"j",
"-",
"1",
":",
"j",
"+",
"2",
"]",
"# our quadratic function is defined as",
"# f(x, y | a, b, c, d, e, f) := a + b * x + c * y + d * x^2 + e * xy + f * y^2",
"# therefore, the best fit coeffiecients are given as",
"# note that they are unique and the uncertainty in each of them (#TODO) can be",
"# computed following the derivations done by Vakili & Hogg (2016) and",
"# Teague & Foreman-Mackey (2018)",
"try",
":",
"a",
"=",
"(",
"-",
"z_",
"[",
"0",
",",
"0",
"]",
"+",
"2",
"*",
"z_",
"[",
"0",
",",
"1",
"]",
"-",
"z_",
"[",
"0",
",",
"2",
"]",
"+",
"2",
"*",
"z_",
"[",
"1",
",",
"0",
"]",
"+",
"5",
"*",
"z_",
"[",
"1",
",",
"1",
"]",
"+",
"2",
"*",
"z_",
"[",
"1",
",",
"2",
"]",
"-",
"z_",
"[",
"2",
",",
"0",
"]",
"+",
"2",
"*",
"z_",
"[",
"2",
",",
"1",
"]",
"-",
"z_",
"[",
"2",
",",
"2",
"]",
")",
"/",
"9",
"b",
"=",
"(",
"-",
"z_",
"[",
"0",
",",
"0",
"]",
"-",
"z_",
"[",
"0",
",",
"1",
"]",
"-",
"z_",
"[",
"0",
",",
"2",
"]",
"+",
"z_",
"[",
"2",
",",
"0",
"]",
"+",
"z_",
"[",
"2",
",",
"1",
"]",
"+",
"z_",
"[",
"2",
",",
"2",
"]",
")",
"/",
"6",
"c",
"=",
"(",
"-",
"z_",
"[",
"0",
",",
"0",
"]",
"+",
"z_",
"[",
"0",
",",
"2",
"]",
"-",
"z_",
"[",
"1",
",",
"0",
"]",
"+",
"z_",
"[",
"1",
",",
"2",
"]",
"-",
"z_",
"[",
"2",
",",
"0",
"]",
"+",
"z_",
"[",
"2",
",",
"2",
"]",
")",
"/",
"6",
"d",
"=",
"(",
"z_",
"[",
"0",
",",
"0",
"]",
"+",
"z_",
"[",
"0",
",",
"1",
"]",
"+",
"z_",
"[",
"0",
",",
"2",
"]",
"-",
"z_",
"[",
"1",
",",
"0",
"]",
"*",
"2",
"-",
"z_",
"[",
"1",
",",
"1",
"]",
"*",
"2",
"-",
"z_",
"[",
"1",
",",
"2",
"]",
"*",
"2",
"+",
"z_",
"[",
"2",
",",
"0",
"]",
"+",
"z_",
"[",
"2",
",",
"1",
"]",
"+",
"z_",
"[",
"2",
",",
"2",
"]",
")",
"/",
"6",
"e",
"=",
"(",
"z_",
"[",
"0",
",",
"0",
"]",
"-",
"z_",
"[",
"0",
",",
"2",
"]",
"-",
"z_",
"[",
"2",
",",
"0",
"]",
"+",
"z_",
"[",
"2",
",",
"2",
"]",
")",
"*",
".25",
"f",
"=",
"(",
"z_",
"[",
"0",
",",
"0",
"]",
"-",
"2",
"*",
"z_",
"[",
"0",
",",
"1",
"]",
"+",
"z_",
"[",
"0",
",",
"2",
"]",
"+",
"z_",
"[",
"1",
",",
"0",
"]",
"-",
"2",
"*",
"z_",
"[",
"1",
",",
"1",
"]",
"+",
"z_",
"[",
"1",
",",
"2",
"]",
"+",
"z_",
"[",
"2",
",",
"0",
"]",
"-",
"2",
"*",
"z_",
"[",
"2",
",",
"1",
"]",
"+",
"z_",
"[",
"2",
",",
"2",
"]",
")",
"/",
"6",
"except",
"IndexError",
":",
"return",
"(",
"i",
",",
"j",
")",
"# see https://en.wikipedia.org/wiki/Quadratic_function",
"det",
"=",
"4",
"*",
"d",
"*",
"f",
"-",
"e",
"**",
"2",
"xm",
"=",
"-",
"(",
"2",
"*",
"f",
"*",
"b",
"-",
"c",
"*",
"e",
")",
"/",
"det",
"ym",
"=",
"-",
"(",
"2",
"*",
"d",
"*",
"c",
"-",
"b",
"*",
"e",
")",
"/",
"det",
"return",
"(",
"i",
"+",
"xm",
",",
"j",
"+",
"ym",
")"
] | Compute the quadratic estimate of the centroid in a 2d-array.
Args:
data (2darray): two dimensional data array
Returns
center (tuple): centroid estimate on the row and column directions,
respectively | [
"Compute",
"the",
"quadratic",
"estimate",
"of",
"the",
"centroid",
"in",
"a",
"2d",
"-",
"array",
"."
] | 8cc2bf18ff52abf86151a12358434691bea0857d | https://github.com/mirca/muchbettermoments/blob/8cc2bf18ff52abf86151a12358434691bea0857d/muchbettermoments.py#L9-L46 |
250,225 | bwesterb/mirte | src/mirteFile.py | depsOf_of_mirteFile_instance_definition | def depsOf_of_mirteFile_instance_definition(man, insts):
""" Returns a function that returns the dependencies of
an instance definition by its name, where insts is a
dictionary of instance definitions from a mirteFile """
return lambda x: [a[1] for a in six.iteritems(insts[x])
if a[0] in [dn for dn, d in (
six.iteritems(man.modules[insts[x]['module']].deps)
if 'module' in insts[x] else [])]] | python | def depsOf_of_mirteFile_instance_definition(man, insts):
""" Returns a function that returns the dependencies of
an instance definition by its name, where insts is a
dictionary of instance definitions from a mirteFile """
return lambda x: [a[1] for a in six.iteritems(insts[x])
if a[0] in [dn for dn, d in (
six.iteritems(man.modules[insts[x]['module']].deps)
if 'module' in insts[x] else [])]] | [
"def",
"depsOf_of_mirteFile_instance_definition",
"(",
"man",
",",
"insts",
")",
":",
"return",
"lambda",
"x",
":",
"[",
"a",
"[",
"1",
"]",
"for",
"a",
"in",
"six",
".",
"iteritems",
"(",
"insts",
"[",
"x",
"]",
")",
"if",
"a",
"[",
"0",
"]",
"in",
"[",
"dn",
"for",
"dn",
",",
"d",
"in",
"(",
"six",
".",
"iteritems",
"(",
"man",
".",
"modules",
"[",
"insts",
"[",
"x",
"]",
"[",
"'module'",
"]",
"]",
".",
"deps",
")",
"if",
"'module'",
"in",
"insts",
"[",
"x",
"]",
"else",
"[",
"]",
")",
"]",
"]"
] | Returns a function that returns the dependencies of
an instance definition by its name, where insts is a
dictionary of instance definitions from a mirteFile | [
"Returns",
"a",
"function",
"that",
"returns",
"the",
"dependencies",
"of",
"an",
"instance",
"definition",
"by",
"its",
"name",
"where",
"insts",
"is",
"a",
"dictionary",
"of",
"instance",
"definitions",
"from",
"a",
"mirteFile"
] | c58db8c993cd15ffdc64b52703cd466213913200 | https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L31-L38 |
250,226 | bwesterb/mirte | src/mirteFile.py | depsOf_of_mirteFile_module_definition | def depsOf_of_mirteFile_module_definition(defs):
""" Returns a function that returns the dependencies of a module
definition by its name, where defs is a dictionary of module
definitions from a mirteFile """
return lambda x: (list(filter(lambda z: z is not None and z in defs,
map(lambda y: y[1].get('type'),
six.iteritems(defs[x]['settings'])
if 'settings' in defs[x] else [])))) + \
(list(defs[x]['inherits']) if 'inherits' in defs[x] else []) | python | def depsOf_of_mirteFile_module_definition(defs):
""" Returns a function that returns the dependencies of a module
definition by its name, where defs is a dictionary of module
definitions from a mirteFile """
return lambda x: (list(filter(lambda z: z is not None and z in defs,
map(lambda y: y[1].get('type'),
six.iteritems(defs[x]['settings'])
if 'settings' in defs[x] else [])))) + \
(list(defs[x]['inherits']) if 'inherits' in defs[x] else []) | [
"def",
"depsOf_of_mirteFile_module_definition",
"(",
"defs",
")",
":",
"return",
"lambda",
"x",
":",
"(",
"list",
"(",
"filter",
"(",
"lambda",
"z",
":",
"z",
"is",
"not",
"None",
"and",
"z",
"in",
"defs",
",",
"map",
"(",
"lambda",
"y",
":",
"y",
"[",
"1",
"]",
".",
"get",
"(",
"'type'",
")",
",",
"six",
".",
"iteritems",
"(",
"defs",
"[",
"x",
"]",
"[",
"'settings'",
"]",
")",
"if",
"'settings'",
"in",
"defs",
"[",
"x",
"]",
"else",
"[",
"]",
")",
")",
")",
")",
"+",
"(",
"list",
"(",
"defs",
"[",
"x",
"]",
"[",
"'inherits'",
"]",
")",
"if",
"'inherits'",
"in",
"defs",
"[",
"x",
"]",
"else",
"[",
"]",
")"
] | Returns a function that returns the dependencies of a module
definition by its name, where defs is a dictionary of module
definitions from a mirteFile | [
"Returns",
"a",
"function",
"that",
"returns",
"the",
"dependencies",
"of",
"a",
"module",
"definition",
"by",
"its",
"name",
"where",
"defs",
"is",
"a",
"dictionary",
"of",
"module",
"definitions",
"from",
"a",
"mirteFile"
] | c58db8c993cd15ffdc64b52703cd466213913200 | https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L41-L49 |
250,227 | eranimo/nomine | nomine/generate.py | Nomine._generate | def _generate(self, size=None):
"Generates a new word"
corpus_letters = list(self.vectors.keys())
current_letter = random.choice(corpus_letters)
if size is None:
size = int(random.normalvariate(self.avg, self.std_dev))
letters = [current_letter]
for _ in range(size):
if current_letter not in corpus_letters:
# current_letter = random.choice(corpus_letters)
break
found_letter = self.vectors[current_letter].choose()
letters.append(found_letter)
current_letter = found_letter
return ''.join(letters) | python | def _generate(self, size=None):
"Generates a new word"
corpus_letters = list(self.vectors.keys())
current_letter = random.choice(corpus_letters)
if size is None:
size = int(random.normalvariate(self.avg, self.std_dev))
letters = [current_letter]
for _ in range(size):
if current_letter not in corpus_letters:
# current_letter = random.choice(corpus_letters)
break
found_letter = self.vectors[current_letter].choose()
letters.append(found_letter)
current_letter = found_letter
return ''.join(letters) | [
"def",
"_generate",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"corpus_letters",
"=",
"list",
"(",
"self",
".",
"vectors",
".",
"keys",
"(",
")",
")",
"current_letter",
"=",
"random",
".",
"choice",
"(",
"corpus_letters",
")",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"int",
"(",
"random",
".",
"normalvariate",
"(",
"self",
".",
"avg",
",",
"self",
".",
"std_dev",
")",
")",
"letters",
"=",
"[",
"current_letter",
"]",
"for",
"_",
"in",
"range",
"(",
"size",
")",
":",
"if",
"current_letter",
"not",
"in",
"corpus_letters",
":",
"# current_letter = random.choice(corpus_letters)",
"break",
"found_letter",
"=",
"self",
".",
"vectors",
"[",
"current_letter",
"]",
".",
"choose",
"(",
")",
"letters",
".",
"append",
"(",
"found_letter",
")",
"current_letter",
"=",
"found_letter",
"return",
"''",
".",
"join",
"(",
"letters",
")"
] | Generates a new word | [
"Generates",
"a",
"new",
"word"
] | bd6342c7c67d772d2b603d5bb081ceda432cc681 | https://github.com/eranimo/nomine/blob/bd6342c7c67d772d2b603d5bb081ceda432cc681/nomine/generate.py#L65-L82 |
250,228 | xtrementl/focus | focus/plugin/modules/tasks.py | _print_tasks | def _print_tasks(env, tasks, mark_active=False):
""" Prints task information using io stream.
`env`
``Environment`` object.
`tasks`
List of tuples (task_name, options, block_options).
`mark_active`
Set to ``True`` to mark active task.
"""
if env.task.active and mark_active:
active_task = env.task.name
else:
active_task = None
for task, options, blocks in tasks:
# print heading
invalid = False
if task == active_task:
method = 'success'
else:
if options is None and blocks is None:
method = 'error'
invalid = True
else:
method = 'write'
opts = list(options or [])
blks = list(blocks or [])
write = getattr(env.io, method)
write('~' * 80)
write(' ' + task)
write('~' * 80)
env.io.write('')
# non-block options
if opts:
for opt, values in opts:
env.io.write(' {0}: {1}'.format(opt,
', '.join(str(v) for v in values)))
env.io.write('')
# block options
if blks:
had_options = False
for block, options in blks:
if options:
had_options = True
env.io.write(' {{ {0} }}'.format(block))
for opt, values in options:
env.io.write(' {0}: {1}'.format(opt,
', '.join(str(v) for v in values)))
env.io.write('')
if not had_options:
blks = None
if not opts and not blks:
if invalid:
env.io.write(' Invalid task.')
else:
env.io.write(' Empty task.')
env.io.write('') | python | def _print_tasks(env, tasks, mark_active=False):
""" Prints task information using io stream.
`env`
``Environment`` object.
`tasks`
List of tuples (task_name, options, block_options).
`mark_active`
Set to ``True`` to mark active task.
"""
if env.task.active and mark_active:
active_task = env.task.name
else:
active_task = None
for task, options, blocks in tasks:
# print heading
invalid = False
if task == active_task:
method = 'success'
else:
if options is None and blocks is None:
method = 'error'
invalid = True
else:
method = 'write'
opts = list(options or [])
blks = list(blocks or [])
write = getattr(env.io, method)
write('~' * 80)
write(' ' + task)
write('~' * 80)
env.io.write('')
# non-block options
if opts:
for opt, values in opts:
env.io.write(' {0}: {1}'.format(opt,
', '.join(str(v) for v in values)))
env.io.write('')
# block options
if blks:
had_options = False
for block, options in blks:
if options:
had_options = True
env.io.write(' {{ {0} }}'.format(block))
for opt, values in options:
env.io.write(' {0}: {1}'.format(opt,
', '.join(str(v) for v in values)))
env.io.write('')
if not had_options:
blks = None
if not opts and not blks:
if invalid:
env.io.write(' Invalid task.')
else:
env.io.write(' Empty task.')
env.io.write('') | [
"def",
"_print_tasks",
"(",
"env",
",",
"tasks",
",",
"mark_active",
"=",
"False",
")",
":",
"if",
"env",
".",
"task",
".",
"active",
"and",
"mark_active",
":",
"active_task",
"=",
"env",
".",
"task",
".",
"name",
"else",
":",
"active_task",
"=",
"None",
"for",
"task",
",",
"options",
",",
"blocks",
"in",
"tasks",
":",
"# print heading",
"invalid",
"=",
"False",
"if",
"task",
"==",
"active_task",
":",
"method",
"=",
"'success'",
"else",
":",
"if",
"options",
"is",
"None",
"and",
"blocks",
"is",
"None",
":",
"method",
"=",
"'error'",
"invalid",
"=",
"True",
"else",
":",
"method",
"=",
"'write'",
"opts",
"=",
"list",
"(",
"options",
"or",
"[",
"]",
")",
"blks",
"=",
"list",
"(",
"blocks",
"or",
"[",
"]",
")",
"write",
"=",
"getattr",
"(",
"env",
".",
"io",
",",
"method",
")",
"write",
"(",
"'~'",
"*",
"80",
")",
"write",
"(",
"' '",
"+",
"task",
")",
"write",
"(",
"'~'",
"*",
"80",
")",
"env",
".",
"io",
".",
"write",
"(",
"''",
")",
"# non-block options",
"if",
"opts",
":",
"for",
"opt",
",",
"values",
"in",
"opts",
":",
"env",
".",
"io",
".",
"write",
"(",
"' {0}: {1}'",
".",
"format",
"(",
"opt",
",",
"', '",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
")",
")",
"env",
".",
"io",
".",
"write",
"(",
"''",
")",
"# block options",
"if",
"blks",
":",
"had_options",
"=",
"False",
"for",
"block",
",",
"options",
"in",
"blks",
":",
"if",
"options",
":",
"had_options",
"=",
"True",
"env",
".",
"io",
".",
"write",
"(",
"' {{ {0} }}'",
".",
"format",
"(",
"block",
")",
")",
"for",
"opt",
",",
"values",
"in",
"options",
":",
"env",
".",
"io",
".",
"write",
"(",
"' {0}: {1}'",
".",
"format",
"(",
"opt",
",",
"', '",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
")",
")",
"env",
".",
"io",
".",
"write",
"(",
"''",
")",
"if",
"not",
"had_options",
":",
"blks",
"=",
"None",
"if",
"not",
"opts",
"and",
"not",
"blks",
":",
"if",
"invalid",
":",
"env",
".",
"io",
".",
"write",
"(",
"' Invalid task.'",
")",
"else",
":",
"env",
".",
"io",
".",
"write",
"(",
"' Empty task.'",
")",
"env",
".",
"io",
".",
"write",
"(",
"''",
")"
] | Prints task information using io stream.
`env`
``Environment`` object.
`tasks`
List of tuples (task_name, options, block_options).
`mark_active`
Set to ``True`` to mark active task. | [
"Prints",
"task",
"information",
"using",
"io",
"stream",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L18-L86 |
250,229 | xtrementl/focus | focus/plugin/modules/tasks.py | _edit_task_config | def _edit_task_config(env, task_config, confirm):
""" Launches text editor to edit provided task configuration file.
`env`
Runtime ``Environment`` instance.
`task_config`
Path to task configuration file.
`confirm`
If task config is invalid after edit, prompt to re-edit.
Return boolean.
* Raises ``InvalidTaskConfig`` if edited task config fails to parse
and `confirm` is ``False``.
"""
# get editor program
if common.IS_MACOSX:
def_editor = 'open'
else:
def_editor = 'vi'
editor = os.environ.get('EDITOR', def_editor)
def _edit_file(filename):
""" Launches editor for given filename.
"""
proc = subprocess.Popen('{0} {1}'.format(editor, filename),
shell=True)
proc.communicate()
if proc.returncode == 0:
try:
# parse temp configuration file
parser_ = parser.parse_config(filename, 'task')
registration.run_option_hooks(parser_,
disable_missing=False)
except (parser.ParseError, errors.InvalidTaskConfig) as exc:
reason = unicode(getattr(exc, 'reason', exc))
raise errors.InvalidTaskConfig(task_config, reason=reason)
return True
else:
return False
try:
# create temp copy of task config
fd, tmpname = tempfile.mkstemp(suffix='.cfg', prefix='focus_')
with open(task_config, 'r') as file_:
os.write(fd, file_.read())
os.close(fd)
while True:
try:
# launch editor
if not _edit_file(tmpname):
return False
# overwrite original with temp
with open(tmpname, 'r') as temp:
with open(task_config, 'w', 0) as config:
config.write(temp.read())
return True
except errors.InvalidTaskConfig as exc:
if not confirm:
raise # reraise
# prompt to re-edit
env.io.error(unicode(exc))
while True:
try:
resp = env.io.prompt('Would you like to retry? (y/n) ')
resp = resp.strip().lower()
except KeyboardInterrupt:
return True
if resp == 'y':
break
elif resp == 'n':
return True
except OSError:
return False
finally:
common.safe_remove_file(tmpname) | python | def _edit_task_config(env, task_config, confirm):
""" Launches text editor to edit provided task configuration file.
`env`
Runtime ``Environment`` instance.
`task_config`
Path to task configuration file.
`confirm`
If task config is invalid after edit, prompt to re-edit.
Return boolean.
* Raises ``InvalidTaskConfig`` if edited task config fails to parse
and `confirm` is ``False``.
"""
# get editor program
if common.IS_MACOSX:
def_editor = 'open'
else:
def_editor = 'vi'
editor = os.environ.get('EDITOR', def_editor)
def _edit_file(filename):
""" Launches editor for given filename.
"""
proc = subprocess.Popen('{0} {1}'.format(editor, filename),
shell=True)
proc.communicate()
if proc.returncode == 0:
try:
# parse temp configuration file
parser_ = parser.parse_config(filename, 'task')
registration.run_option_hooks(parser_,
disable_missing=False)
except (parser.ParseError, errors.InvalidTaskConfig) as exc:
reason = unicode(getattr(exc, 'reason', exc))
raise errors.InvalidTaskConfig(task_config, reason=reason)
return True
else:
return False
try:
# create temp copy of task config
fd, tmpname = tempfile.mkstemp(suffix='.cfg', prefix='focus_')
with open(task_config, 'r') as file_:
os.write(fd, file_.read())
os.close(fd)
while True:
try:
# launch editor
if not _edit_file(tmpname):
return False
# overwrite original with temp
with open(tmpname, 'r') as temp:
with open(task_config, 'w', 0) as config:
config.write(temp.read())
return True
except errors.InvalidTaskConfig as exc:
if not confirm:
raise # reraise
# prompt to re-edit
env.io.error(unicode(exc))
while True:
try:
resp = env.io.prompt('Would you like to retry? (y/n) ')
resp = resp.strip().lower()
except KeyboardInterrupt:
return True
if resp == 'y':
break
elif resp == 'n':
return True
except OSError:
return False
finally:
common.safe_remove_file(tmpname) | [
"def",
"_edit_task_config",
"(",
"env",
",",
"task_config",
",",
"confirm",
")",
":",
"# get editor program",
"if",
"common",
".",
"IS_MACOSX",
":",
"def_editor",
"=",
"'open'",
"else",
":",
"def_editor",
"=",
"'vi'",
"editor",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'EDITOR'",
",",
"def_editor",
")",
"def",
"_edit_file",
"(",
"filename",
")",
":",
"\"\"\" Launches editor for given filename.\n \"\"\"",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"'{0} {1}'",
".",
"format",
"(",
"editor",
",",
"filename",
")",
",",
"shell",
"=",
"True",
")",
"proc",
".",
"communicate",
"(",
")",
"if",
"proc",
".",
"returncode",
"==",
"0",
":",
"try",
":",
"# parse temp configuration file",
"parser_",
"=",
"parser",
".",
"parse_config",
"(",
"filename",
",",
"'task'",
")",
"registration",
".",
"run_option_hooks",
"(",
"parser_",
",",
"disable_missing",
"=",
"False",
")",
"except",
"(",
"parser",
".",
"ParseError",
",",
"errors",
".",
"InvalidTaskConfig",
")",
"as",
"exc",
":",
"reason",
"=",
"unicode",
"(",
"getattr",
"(",
"exc",
",",
"'reason'",
",",
"exc",
")",
")",
"raise",
"errors",
".",
"InvalidTaskConfig",
"(",
"task_config",
",",
"reason",
"=",
"reason",
")",
"return",
"True",
"else",
":",
"return",
"False",
"try",
":",
"# create temp copy of task config",
"fd",
",",
"tmpname",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.cfg'",
",",
"prefix",
"=",
"'focus_'",
")",
"with",
"open",
"(",
"task_config",
",",
"'r'",
")",
"as",
"file_",
":",
"os",
".",
"write",
"(",
"fd",
",",
"file_",
".",
"read",
"(",
")",
")",
"os",
".",
"close",
"(",
"fd",
")",
"while",
"True",
":",
"try",
":",
"# launch editor",
"if",
"not",
"_edit_file",
"(",
"tmpname",
")",
":",
"return",
"False",
"# overwrite original with temp",
"with",
"open",
"(",
"tmpname",
",",
"'r'",
")",
"as",
"temp",
":",
"with",
"open",
"(",
"task_config",
",",
"'w'",
",",
"0",
")",
"as",
"config",
":",
"config",
".",
"write",
"(",
"temp",
".",
"read",
"(",
")",
")",
"return",
"True",
"except",
"errors",
".",
"InvalidTaskConfig",
"as",
"exc",
":",
"if",
"not",
"confirm",
":",
"raise",
"# reraise",
"# prompt to re-edit",
"env",
".",
"io",
".",
"error",
"(",
"unicode",
"(",
"exc",
")",
")",
"while",
"True",
":",
"try",
":",
"resp",
"=",
"env",
".",
"io",
".",
"prompt",
"(",
"'Would you like to retry? (y/n) '",
")",
"resp",
"=",
"resp",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"return",
"True",
"if",
"resp",
"==",
"'y'",
":",
"break",
"elif",
"resp",
"==",
"'n'",
":",
"return",
"True",
"except",
"OSError",
":",
"return",
"False",
"finally",
":",
"common",
".",
"safe_remove_file",
"(",
"tmpname",
")"
] | Launches text editor to edit provided task configuration file.
`env`
Runtime ``Environment`` instance.
`task_config`
Path to task configuration file.
`confirm`
If task config is invalid after edit, prompt to re-edit.
Return boolean.
* Raises ``InvalidTaskConfig`` if edited task config fails to parse
and `confirm` is ``False``. | [
"Launches",
"text",
"editor",
"to",
"edit",
"provided",
"task",
"configuration",
"file",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L89-L175 |
250,230 | xtrementl/focus | focus/plugin/modules/tasks.py | TaskStart.execute | def execute(self, env, args):
""" Starts a new task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
# start the task
if env.task.start(args.task_name):
env.io.success(u'Task Loaded.') | python | def execute(self, env, args):
""" Starts a new task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
# start the task
if env.task.start(args.task_name):
env.io.success(u'Task Loaded.') | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"# start the task",
"if",
"env",
".",
"task",
".",
"start",
"(",
"args",
".",
"task_name",
")",
":",
"env",
".",
"io",
".",
"success",
"(",
"u'Task Loaded.'",
")"
] | Starts a new task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. | [
"Starts",
"a",
"new",
"task",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L195-L206 |
250,231 | xtrementl/focus | focus/plugin/modules/tasks.py | TaskCreate.setup_parser | def setup_parser(self, parser):
""" Setup the argument parser.
`parser`
``FocusArgParser`` object.
"""
parser.add_argument('task_name', help='task to create')
parser.add_argument('clone_task', nargs='?',
help='existing task to clone')
parser.add_argument('--skip-edit', action='store_true',
help='skip editing of task configuration') | python | def setup_parser(self, parser):
""" Setup the argument parser.
`parser`
``FocusArgParser`` object.
"""
parser.add_argument('task_name', help='task to create')
parser.add_argument('clone_task', nargs='?',
help='existing task to clone')
parser.add_argument('--skip-edit', action='store_true',
help='skip editing of task configuration') | [
"def",
"setup_parser",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'task_name'",
",",
"help",
"=",
"'task to create'",
")",
"parser",
".",
"add_argument",
"(",
"'clone_task'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'existing task to clone'",
")",
"parser",
".",
"add_argument",
"(",
"'--skip-edit'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'skip editing of task configuration'",
")"
] | Setup the argument parser.
`parser`
``FocusArgParser`` object. | [
"Setup",
"the",
"argument",
"parser",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L238-L249 |
250,232 | xtrementl/focus | focus/plugin/modules/tasks.py | TaskCreate.execute | def execute(self, env, args):
""" Creates a new task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
task_name = args.task_name
clone_task = args.clone_task
if not env.task.create(task_name, clone_task):
raise errors.FocusError(u'Could not create task "{0}"'
.format(task_name))
# open in task config in editor
if not args.skip_edit:
task_config = env.task.get_config_path(task_name)
if not _edit_task_config(env, task_config, confirm=True):
raise errors.FocusError(u'Could not open task config: {0}'
.format(task_config)) | python | def execute(self, env, args):
""" Creates a new task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
task_name = args.task_name
clone_task = args.clone_task
if not env.task.create(task_name, clone_task):
raise errors.FocusError(u'Could not create task "{0}"'
.format(task_name))
# open in task config in editor
if not args.skip_edit:
task_config = env.task.get_config_path(task_name)
if not _edit_task_config(env, task_config, confirm=True):
raise errors.FocusError(u'Could not open task config: {0}'
.format(task_config)) | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"task_name",
"=",
"args",
".",
"task_name",
"clone_task",
"=",
"args",
".",
"clone_task",
"if",
"not",
"env",
".",
"task",
".",
"create",
"(",
"task_name",
",",
"clone_task",
")",
":",
"raise",
"errors",
".",
"FocusError",
"(",
"u'Could not create task \"{0}\"'",
".",
"format",
"(",
"task_name",
")",
")",
"# open in task config in editor",
"if",
"not",
"args",
".",
"skip_edit",
":",
"task_config",
"=",
"env",
".",
"task",
".",
"get_config_path",
"(",
"task_name",
")",
"if",
"not",
"_edit_task_config",
"(",
"env",
",",
"task_config",
",",
"confirm",
"=",
"True",
")",
":",
"raise",
"errors",
".",
"FocusError",
"(",
"u'Could not open task config: {0}'",
".",
"format",
"(",
"task_config",
")",
")"
] | Creates a new task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. | [
"Creates",
"a",
"new",
"task",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L251-L273 |
250,233 | xtrementl/focus | focus/plugin/modules/tasks.py | TaskEdit.execute | def execute(self, env, args):
""" Edits task configuration.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
task_name = args.task_name
if not env.task.exists(task_name):
raise errors.TaskNotFound(task_name)
if env.task.active and task_name == env.task.name:
raise errors.ActiveTask
# open in task config in editor
task_config = env.task.get_config_path(task_name)
if not _edit_task_config(env, task_config, confirm=True):
raise errors.FocusError(u'Could not open task config: {0}'
.format(task_config)) | python | def execute(self, env, args):
""" Edits task configuration.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
task_name = args.task_name
if not env.task.exists(task_name):
raise errors.TaskNotFound(task_name)
if env.task.active and task_name == env.task.name:
raise errors.ActiveTask
# open in task config in editor
task_config = env.task.get_config_path(task_name)
if not _edit_task_config(env, task_config, confirm=True):
raise errors.FocusError(u'Could not open task config: {0}'
.format(task_config)) | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"task_name",
"=",
"args",
".",
"task_name",
"if",
"not",
"env",
".",
"task",
".",
"exists",
"(",
"task_name",
")",
":",
"raise",
"errors",
".",
"TaskNotFound",
"(",
"task_name",
")",
"if",
"env",
".",
"task",
".",
"active",
"and",
"task_name",
"==",
"env",
".",
"task",
".",
"name",
":",
"raise",
"errors",
".",
"ActiveTask",
"# open in task config in editor",
"task_config",
"=",
"env",
".",
"task",
".",
"get_config_path",
"(",
"task_name",
")",
"if",
"not",
"_edit_task_config",
"(",
"env",
",",
"task_config",
",",
"confirm",
"=",
"True",
")",
":",
"raise",
"errors",
".",
"FocusError",
"(",
"u'Could not open task config: {0}'",
".",
"format",
"(",
"task_config",
")",
")"
] | Edits task configuration.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. | [
"Edits",
"task",
"configuration",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L293-L315 |
250,234 | xtrementl/focus | focus/plugin/modules/tasks.py | TaskList.execute | def execute(self, env, args):
""" Lists all valid tasks.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
tasks = env.task.get_list_info()
if not tasks:
env.io.write("No tasks found.")
else:
if args.verbose:
_print_tasks(env, tasks, mark_active=True)
else:
if env.task.active:
active_task = env.task.name
else:
active_task = None
for task, options, blocks in tasks:
if task == active_task:
env.io.success(task + ' *')
else:
if options is None and blocks is None:
env.io.error(task + ' ~')
else:
env.io.write(task) | python | def execute(self, env, args):
""" Lists all valid tasks.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
tasks = env.task.get_list_info()
if not tasks:
env.io.write("No tasks found.")
else:
if args.verbose:
_print_tasks(env, tasks, mark_active=True)
else:
if env.task.active:
active_task = env.task.name
else:
active_task = None
for task, options, blocks in tasks:
if task == active_task:
env.io.success(task + ' *')
else:
if options is None and blocks is None:
env.io.error(task + ' ~')
else:
env.io.write(task) | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"tasks",
"=",
"env",
".",
"task",
".",
"get_list_info",
"(",
")",
"if",
"not",
"tasks",
":",
"env",
".",
"io",
".",
"write",
"(",
"\"No tasks found.\"",
")",
"else",
":",
"if",
"args",
".",
"verbose",
":",
"_print_tasks",
"(",
"env",
",",
"tasks",
",",
"mark_active",
"=",
"True",
")",
"else",
":",
"if",
"env",
".",
"task",
".",
"active",
":",
"active_task",
"=",
"env",
".",
"task",
".",
"name",
"else",
":",
"active_task",
"=",
"None",
"for",
"task",
",",
"options",
",",
"blocks",
"in",
"tasks",
":",
"if",
"task",
"==",
"active_task",
":",
"env",
".",
"io",
".",
"success",
"(",
"task",
"+",
"' *'",
")",
"else",
":",
"if",
"options",
"is",
"None",
"and",
"blocks",
"is",
"None",
":",
"env",
".",
"io",
".",
"error",
"(",
"task",
"+",
"' ~'",
")",
"else",
":",
"env",
".",
"io",
".",
"write",
"(",
"task",
")"
] | Lists all valid tasks.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. | [
"Lists",
"all",
"valid",
"tasks",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/tasks.py#L434-L464 |
250,235 | bruth/restlib2 | restlib2/resources.py | no_content_response | def no_content_response(response):
"Cautious assessment of the response body for no content."
if not hasattr(response, '_container'):
return True
if response._container is None:
return True
if isinstance(response._container, (list, tuple)):
if len(response._container) == 1 and not response._container[0]:
return True
return False | python | def no_content_response(response):
"Cautious assessment of the response body for no content."
if not hasattr(response, '_container'):
return True
if response._container is None:
return True
if isinstance(response._container, (list, tuple)):
if len(response._container) == 1 and not response._container[0]:
return True
return False | [
"def",
"no_content_response",
"(",
"response",
")",
":",
"if",
"not",
"hasattr",
"(",
"response",
",",
"'_container'",
")",
":",
"return",
"True",
"if",
"response",
".",
"_container",
"is",
"None",
":",
"return",
"True",
"if",
"isinstance",
"(",
"response",
".",
"_container",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"len",
"(",
"response",
".",
"_container",
")",
"==",
"1",
"and",
"not",
"response",
".",
"_container",
"[",
"0",
"]",
":",
"return",
"True",
"return",
"False"
] | Cautious assessment of the response body for no content. | [
"Cautious",
"assessment",
"of",
"the",
"response",
"body",
"for",
"no",
"content",
"."
] | cb147527496ddf08263364f1fb52e7c48f215667 | https://github.com/bruth/restlib2/blob/cb147527496ddf08263364f1fb52e7c48f215667/restlib2/resources.py#L32-L44 |
250,236 | melonmanchan/ResumeOS | resumeos/ResumeOs.py | render_template_file | def render_template_file(file_name, context):
""" Renders and overrides Jinja2 template files """
with open(file_name, 'r+') as f:
template = Template(f.read())
output = template.render(context)
f.seek(0)
f.write(output)
f.truncate() | python | def render_template_file(file_name, context):
""" Renders and overrides Jinja2 template files """
with open(file_name, 'r+') as f:
template = Template(f.read())
output = template.render(context)
f.seek(0)
f.write(output)
f.truncate() | [
"def",
"render_template_file",
"(",
"file_name",
",",
"context",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'r+'",
")",
"as",
"f",
":",
"template",
"=",
"Template",
"(",
"f",
".",
"read",
"(",
")",
")",
"output",
"=",
"template",
".",
"render",
"(",
"context",
")",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"write",
"(",
"output",
")",
"f",
".",
"truncate",
"(",
")"
] | Renders and overrides Jinja2 template files | [
"Renders",
"and",
"overrides",
"Jinja2",
"template",
"files"
] | b7fbcdaa0b4bad27e06ca33eee9c10f5d89fe37c | https://github.com/melonmanchan/ResumeOS/blob/b7fbcdaa0b4bad27e06ca33eee9c10f5d89fe37c/resumeos/ResumeOs.py#L16-L23 |
250,237 | melonmanchan/ResumeOS | resumeos/ResumeOs.py | main | def main(name, output, font):
""" Easily bootstrap an OS project to fool HR departments and pad your resume. """
# The path of the directory where the final files will end up in
bootstrapped_directory = os.getcwd() + os.sep + name.lower().replace(' ', '-') + os.sep
# Copy the template files to the target directory
copy_tree(get_real_path(os.sep + 'my-cool-os-template'), bootstrapped_directory)
# Create the necessary assembly mov instructions for printing out the output on boot
start_byte = int('0xb8000', 16)
instructions_list = []
for c in output:
char_as_hex = '0x02'+ c.encode('hex')
instructions_list.append('\tmov word [{0}], {1} ; {2}'.format(hex(start_byte), char_as_hex, c))
start_byte += 2
# Render the ASCII banner to be displayed in the README (A must for any serious hobby OS project!)
banner = Figlet(font=font).renderText(name)
render_template_file(bootstrapped_directory + 'README.md', {'name' : name, 'banner' : banner})
render_template_file(bootstrapped_directory + 'grub.cfg' , {'name' : name})
render_template_file(bootstrapped_directory + 'boot.asm' , {'instructions_list' : instructions_list})
print('finished bootstrapping project into directory ' + bootstrapped_directory) | python | def main(name, output, font):
""" Easily bootstrap an OS project to fool HR departments and pad your resume. """
# The path of the directory where the final files will end up in
bootstrapped_directory = os.getcwd() + os.sep + name.lower().replace(' ', '-') + os.sep
# Copy the template files to the target directory
copy_tree(get_real_path(os.sep + 'my-cool-os-template'), bootstrapped_directory)
# Create the necessary assembly mov instructions for printing out the output on boot
start_byte = int('0xb8000', 16)
instructions_list = []
for c in output:
char_as_hex = '0x02'+ c.encode('hex')
instructions_list.append('\tmov word [{0}], {1} ; {2}'.format(hex(start_byte), char_as_hex, c))
start_byte += 2
# Render the ASCII banner to be displayed in the README (A must for any serious hobby OS project!)
banner = Figlet(font=font).renderText(name)
render_template_file(bootstrapped_directory + 'README.md', {'name' : name, 'banner' : banner})
render_template_file(bootstrapped_directory + 'grub.cfg' , {'name' : name})
render_template_file(bootstrapped_directory + 'boot.asm' , {'instructions_list' : instructions_list})
print('finished bootstrapping project into directory ' + bootstrapped_directory) | [
"def",
"main",
"(",
"name",
",",
"output",
",",
"font",
")",
":",
"# The path of the directory where the final files will end up in",
"bootstrapped_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
"+",
"os",
".",
"sep",
"+",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'-'",
")",
"+",
"os",
".",
"sep",
"# Copy the template files to the target directory",
"copy_tree",
"(",
"get_real_path",
"(",
"os",
".",
"sep",
"+",
"'my-cool-os-template'",
")",
",",
"bootstrapped_directory",
")",
"# Create the necessary assembly mov instructions for printing out the output on boot",
"start_byte",
"=",
"int",
"(",
"'0xb8000'",
",",
"16",
")",
"instructions_list",
"=",
"[",
"]",
"for",
"c",
"in",
"output",
":",
"char_as_hex",
"=",
"'0x02'",
"+",
"c",
".",
"encode",
"(",
"'hex'",
")",
"instructions_list",
".",
"append",
"(",
"'\\tmov word [{0}], {1} ; {2}'",
".",
"format",
"(",
"hex",
"(",
"start_byte",
")",
",",
"char_as_hex",
",",
"c",
")",
")",
"start_byte",
"+=",
"2",
"# Render the ASCII banner to be displayed in the README (A must for any serious hobby OS project!)",
"banner",
"=",
"Figlet",
"(",
"font",
"=",
"font",
")",
".",
"renderText",
"(",
"name",
")",
"render_template_file",
"(",
"bootstrapped_directory",
"+",
"'README.md'",
",",
"{",
"'name'",
":",
"name",
",",
"'banner'",
":",
"banner",
"}",
")",
"render_template_file",
"(",
"bootstrapped_directory",
"+",
"'grub.cfg'",
",",
"{",
"'name'",
":",
"name",
"}",
")",
"render_template_file",
"(",
"bootstrapped_directory",
"+",
"'boot.asm'",
",",
"{",
"'instructions_list'",
":",
"instructions_list",
"}",
")",
"print",
"(",
"'finished bootstrapping project into directory '",
"+",
"bootstrapped_directory",
")"
] | Easily bootstrap an OS project to fool HR departments and pad your resume. | [
"Easily",
"bootstrap",
"an",
"OS",
"project",
"to",
"fool",
"HR",
"departments",
"and",
"pad",
"your",
"resume",
"."
] | b7fbcdaa0b4bad27e06ca33eee9c10f5d89fe37c | https://github.com/melonmanchan/ResumeOS/blob/b7fbcdaa0b4bad27e06ca33eee9c10f5d89fe37c/resumeos/ResumeOs.py#L37-L62 |
250,238 | tomnor/channelpack | channelpack/pulldbf.py | dbfreader | def dbfreader(f):
"""Returns an iterator over records in a Xbase DBF file.
The first row returned contains the field names.
The second row contains field specs: (type, size, decimal places).
Subsequent rows contain the data records.
If a record is marked as deleted, it is skipped.
File should be opened for binary reads.
"""
# See DBF format spec at:
# http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT
numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32))
numfields = (lenheader - 33) // 32
fields = []
for fieldno in xrange(numfields):
name, typ, size, deci = struct.unpack('<11sc4xBB14x', f.read(32))
name = name.replace('\0', '') # eliminate NULs from string
fields.append((name, typ, size, deci))
yield [field[0] for field in fields]
yield [tuple(field[1:]) for field in fields]
# replacing missing values with np.NaN. trade-off to make integers as
# floats. See
# http://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping-array-type-as-integer-while-having-a-nan-value
# The limitation is not solved it seems. (Numpy).
terminator = f.read(1)
assert terminator == '\r'
fields.insert(0, ('DeletionFlag', 'C', 1, 0))
fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in fields])
fmtsiz = struct.calcsize(fmt)
for i in xrange(numrec):
record = struct.unpack(fmt, f.read(fmtsiz))
if record[0] != ' ':
continue # deleted record
result = []
for (name, typ, size, deci), value in itertools.izip(fields, record):
if name == 'DeletionFlag':
continue
if typ == "N":
value = value.replace('\0', '').lstrip()
if value == '':
# value = 0
value = np.NaN # 0 is a value.
elif deci:
value = float(value)
# value = decimal.Decimal(value) Not necessary.
else:
value = int(value)
elif typ == 'D':
y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8])
value = datetime.date(y, m, d)
elif typ == 'L':
value = ((value in 'YyTt' and 'T') or
(value in 'NnFf' and 'F') or '?')
elif typ == 'F': # Can this type not be null?
value = float(value)
result.append(value)
yield result | python | def dbfreader(f):
"""Returns an iterator over records in a Xbase DBF file.
The first row returned contains the field names.
The second row contains field specs: (type, size, decimal places).
Subsequent rows contain the data records.
If a record is marked as deleted, it is skipped.
File should be opened for binary reads.
"""
# See DBF format spec at:
# http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT
numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32))
numfields = (lenheader - 33) // 32
fields = []
for fieldno in xrange(numfields):
name, typ, size, deci = struct.unpack('<11sc4xBB14x', f.read(32))
name = name.replace('\0', '') # eliminate NULs from string
fields.append((name, typ, size, deci))
yield [field[0] for field in fields]
yield [tuple(field[1:]) for field in fields]
# replacing missing values with np.NaN. trade-off to make integers as
# floats. See
# http://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping-array-type-as-integer-while-having-a-nan-value
# The limitation is not solved it seems. (Numpy).
terminator = f.read(1)
assert terminator == '\r'
fields.insert(0, ('DeletionFlag', 'C', 1, 0))
fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in fields])
fmtsiz = struct.calcsize(fmt)
for i in xrange(numrec):
record = struct.unpack(fmt, f.read(fmtsiz))
if record[0] != ' ':
continue # deleted record
result = []
for (name, typ, size, deci), value in itertools.izip(fields, record):
if name == 'DeletionFlag':
continue
if typ == "N":
value = value.replace('\0', '').lstrip()
if value == '':
# value = 0
value = np.NaN # 0 is a value.
elif deci:
value = float(value)
# value = decimal.Decimal(value) Not necessary.
else:
value = int(value)
elif typ == 'D':
y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8])
value = datetime.date(y, m, d)
elif typ == 'L':
value = ((value in 'YyTt' and 'T') or
(value in 'NnFf' and 'F') or '?')
elif typ == 'F': # Can this type not be null?
value = float(value)
result.append(value)
yield result | [
"def",
"dbfreader",
"(",
"f",
")",
":",
"# See DBF format spec at:",
"# http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT",
"numrec",
",",
"lenheader",
"=",
"struct",
".",
"unpack",
"(",
"'<xxxxLH22x'",
",",
"f",
".",
"read",
"(",
"32",
")",
")",
"numfields",
"=",
"(",
"lenheader",
"-",
"33",
")",
"//",
"32",
"fields",
"=",
"[",
"]",
"for",
"fieldno",
"in",
"xrange",
"(",
"numfields",
")",
":",
"name",
",",
"typ",
",",
"size",
",",
"deci",
"=",
"struct",
".",
"unpack",
"(",
"'<11sc4xBB14x'",
",",
"f",
".",
"read",
"(",
"32",
")",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'\\0'",
",",
"''",
")",
"# eliminate NULs from string",
"fields",
".",
"append",
"(",
"(",
"name",
",",
"typ",
",",
"size",
",",
"deci",
")",
")",
"yield",
"[",
"field",
"[",
"0",
"]",
"for",
"field",
"in",
"fields",
"]",
"yield",
"[",
"tuple",
"(",
"field",
"[",
"1",
":",
"]",
")",
"for",
"field",
"in",
"fields",
"]",
"# replacing missing values with np.NaN. trade-off to make integers as",
"# floats. See",
"# http://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping-array-type-as-integer-while-having-a-nan-value",
"# The limitation is not solved it seems. (Numpy).",
"terminator",
"=",
"f",
".",
"read",
"(",
"1",
")",
"assert",
"terminator",
"==",
"'\\r'",
"fields",
".",
"insert",
"(",
"0",
",",
"(",
"'DeletionFlag'",
",",
"'C'",
",",
"1",
",",
"0",
")",
")",
"fmt",
"=",
"''",
".",
"join",
"(",
"[",
"'%ds'",
"%",
"fieldinfo",
"[",
"2",
"]",
"for",
"fieldinfo",
"in",
"fields",
"]",
")",
"fmtsiz",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"for",
"i",
"in",
"xrange",
"(",
"numrec",
")",
":",
"record",
"=",
"struct",
".",
"unpack",
"(",
"fmt",
",",
"f",
".",
"read",
"(",
"fmtsiz",
")",
")",
"if",
"record",
"[",
"0",
"]",
"!=",
"' '",
":",
"continue",
"# deleted record",
"result",
"=",
"[",
"]",
"for",
"(",
"name",
",",
"typ",
",",
"size",
",",
"deci",
")",
",",
"value",
"in",
"itertools",
".",
"izip",
"(",
"fields",
",",
"record",
")",
":",
"if",
"name",
"==",
"'DeletionFlag'",
":",
"continue",
"if",
"typ",
"==",
"\"N\"",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'\\0'",
",",
"''",
")",
".",
"lstrip",
"(",
")",
"if",
"value",
"==",
"''",
":",
"# value = 0",
"value",
"=",
"np",
".",
"NaN",
"# 0 is a value.",
"elif",
"deci",
":",
"value",
"=",
"float",
"(",
"value",
")",
"# value = decimal.Decimal(value) Not necessary.",
"else",
":",
"value",
"=",
"int",
"(",
"value",
")",
"elif",
"typ",
"==",
"'D'",
":",
"y",
",",
"m",
",",
"d",
"=",
"int",
"(",
"value",
"[",
":",
"4",
"]",
")",
",",
"int",
"(",
"value",
"[",
"4",
":",
"6",
"]",
")",
",",
"int",
"(",
"value",
"[",
"6",
":",
"8",
"]",
")",
"value",
"=",
"datetime",
".",
"date",
"(",
"y",
",",
"m",
",",
"d",
")",
"elif",
"typ",
"==",
"'L'",
":",
"value",
"=",
"(",
"(",
"value",
"in",
"'YyTt'",
"and",
"'T'",
")",
"or",
"(",
"value",
"in",
"'NnFf'",
"and",
"'F'",
")",
"or",
"'?'",
")",
"elif",
"typ",
"==",
"'F'",
":",
"# Can this type not be null?",
"value",
"=",
"float",
"(",
"value",
")",
"result",
".",
"append",
"(",
"value",
")",
"yield",
"result"
] | Returns an iterator over records in a Xbase DBF file.
The first row returned contains the field names.
The second row contains field specs: (type, size, decimal places).
Subsequent rows contain the data records.
If a record is marked as deleted, it is skipped.
File should be opened for binary reads. | [
"Returns",
"an",
"iterator",
"over",
"records",
"in",
"a",
"Xbase",
"DBF",
"file",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulldbf.py#L11-L74 |
250,239 | tomnor/channelpack | channelpack/pulldbf.py | dbf_asdict | def dbf_asdict(fn, usecols=None, keystyle='ints'):
"""Return data from dbf file fn as a dict.
fn: str
The filename string.
usecols: seqence
The columns to use, 0-based.
keystyle: str
'ints' or 'names' accepted. Should be 'ints' (default) when this
function is given to a ChannelPack as loadfunc. If 'names' is
used, keys will be the field names from the dbf file.
"""
if keystyle not in ['ints', 'names']:
raise ValueError('Unknown keyword: ' + str(keystyle))
with open(fn, 'rb') as fo:
rit = dbfreader(fo)
names = rit.next()
specs = rit.next() # NOQA
R = [tuple(r) for r in rit]
def getkey(i):
if keystyle == 'ints':
return i
else:
return names[i]
R = zip(*R)
d = dict()
for i in usecols or range(len(names)):
# d[getkey(i)] = R['f' + str(i)] # Default numpy fieldname
d[getkey(i)] = np.array(R[i])
return d | python | def dbf_asdict(fn, usecols=None, keystyle='ints'):
"""Return data from dbf file fn as a dict.
fn: str
The filename string.
usecols: seqence
The columns to use, 0-based.
keystyle: str
'ints' or 'names' accepted. Should be 'ints' (default) when this
function is given to a ChannelPack as loadfunc. If 'names' is
used, keys will be the field names from the dbf file.
"""
if keystyle not in ['ints', 'names']:
raise ValueError('Unknown keyword: ' + str(keystyle))
with open(fn, 'rb') as fo:
rit = dbfreader(fo)
names = rit.next()
specs = rit.next() # NOQA
R = [tuple(r) for r in rit]
def getkey(i):
if keystyle == 'ints':
return i
else:
return names[i]
R = zip(*R)
d = dict()
for i in usecols or range(len(names)):
# d[getkey(i)] = R['f' + str(i)] # Default numpy fieldname
d[getkey(i)] = np.array(R[i])
return d | [
"def",
"dbf_asdict",
"(",
"fn",
",",
"usecols",
"=",
"None",
",",
"keystyle",
"=",
"'ints'",
")",
":",
"if",
"keystyle",
"not",
"in",
"[",
"'ints'",
",",
"'names'",
"]",
":",
"raise",
"ValueError",
"(",
"'Unknown keyword: '",
"+",
"str",
"(",
"keystyle",
")",
")",
"with",
"open",
"(",
"fn",
",",
"'rb'",
")",
"as",
"fo",
":",
"rit",
"=",
"dbfreader",
"(",
"fo",
")",
"names",
"=",
"rit",
".",
"next",
"(",
")",
"specs",
"=",
"rit",
".",
"next",
"(",
")",
"# NOQA",
"R",
"=",
"[",
"tuple",
"(",
"r",
")",
"for",
"r",
"in",
"rit",
"]",
"def",
"getkey",
"(",
"i",
")",
":",
"if",
"keystyle",
"==",
"'ints'",
":",
"return",
"i",
"else",
":",
"return",
"names",
"[",
"i",
"]",
"R",
"=",
"zip",
"(",
"*",
"R",
")",
"d",
"=",
"dict",
"(",
")",
"for",
"i",
"in",
"usecols",
"or",
"range",
"(",
"len",
"(",
"names",
")",
")",
":",
"# d[getkey(i)] = R['f' + str(i)] # Default numpy fieldname",
"d",
"[",
"getkey",
"(",
"i",
")",
"]",
"=",
"np",
".",
"array",
"(",
"R",
"[",
"i",
"]",
")",
"return",
"d"
] | Return data from dbf file fn as a dict.
fn: str
The filename string.
usecols: seqence
The columns to use, 0-based.
keystyle: str
'ints' or 'names' accepted. Should be 'ints' (default) when this
function is given to a ChannelPack as loadfunc. If 'names' is
used, keys will be the field names from the dbf file. | [
"Return",
"data",
"from",
"dbf",
"file",
"fn",
"as",
"a",
"dict",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulldbf.py#L77-L113 |
250,240 | sbusard/wagoner | wagoner/table.py | Table.check | def check(self):
"""
Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise.
"""
for character, followers in self.items():
for follower in followers:
if follower not in self:
return False
return True | python | def check(self):
"""
Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise.
"""
for character, followers in self.items():
for follower in followers:
if follower not in self:
return False
return True | [
"def",
"check",
"(",
"self",
")",
":",
"for",
"character",
",",
"followers",
"in",
"self",
".",
"items",
"(",
")",
":",
"for",
"follower",
"in",
"followers",
":",
"if",
"follower",
"not",
"in",
"self",
":",
"return",
"False",
"return",
"True"
] | Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise. | [
"Check",
"that",
"this",
"table",
"is",
"complete",
"that",
"is",
"every",
"character",
"of",
"this",
"table",
"can",
"be",
"followed",
"by",
"a",
"new",
"character",
"."
] | 7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b | https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/table.py#L81-L92 |
250,241 | sbusard/wagoner | wagoner/table.py | Table.random_word | def random_word(self, length, prefix=0, start=False, end=False,
flatten=False):
"""
Generate a random word of length from this table.
:param length: the length of the generated word; >= 1;
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param start: if True, the generated word starts as a word of table;
:param end: if True, the generated word ends as a word of table;
:param flatten: whether or not consider the table as flattened;
:return: a random word of length generated from table.
:raises GenerationError: if no word of length can be generated.
"""
if start:
word = ">"
length += 1
return self._extend_word(word, length, prefix=prefix, end=end,
flatten=flatten)[1:]
else:
first_letters = list(k for k in self if len(k) == 1 and k != ">")
while True:
word = random.choice(first_letters)
try:
word = self._extend_word(word, length, prefix=prefix,
end=end, flatten=flatten)
return word
except GenerationError:
first_letters.remove(word[0]) | python | def random_word(self, length, prefix=0, start=False, end=False,
flatten=False):
"""
Generate a random word of length from this table.
:param length: the length of the generated word; >= 1;
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param start: if True, the generated word starts as a word of table;
:param end: if True, the generated word ends as a word of table;
:param flatten: whether or not consider the table as flattened;
:return: a random word of length generated from table.
:raises GenerationError: if no word of length can be generated.
"""
if start:
word = ">"
length += 1
return self._extend_word(word, length, prefix=prefix, end=end,
flatten=flatten)[1:]
else:
first_letters = list(k for k in self if len(k) == 1 and k != ">")
while True:
word = random.choice(first_letters)
try:
word = self._extend_word(word, length, prefix=prefix,
end=end, flatten=flatten)
return word
except GenerationError:
first_letters.remove(word[0]) | [
"def",
"random_word",
"(",
"self",
",",
"length",
",",
"prefix",
"=",
"0",
",",
"start",
"=",
"False",
",",
"end",
"=",
"False",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"start",
":",
"word",
"=",
"\">\"",
"length",
"+=",
"1",
"return",
"self",
".",
"_extend_word",
"(",
"word",
",",
"length",
",",
"prefix",
"=",
"prefix",
",",
"end",
"=",
"end",
",",
"flatten",
"=",
"flatten",
")",
"[",
"1",
":",
"]",
"else",
":",
"first_letters",
"=",
"list",
"(",
"k",
"for",
"k",
"in",
"self",
"if",
"len",
"(",
"k",
")",
"==",
"1",
"and",
"k",
"!=",
"\">\"",
")",
"while",
"True",
":",
"word",
"=",
"random",
".",
"choice",
"(",
"first_letters",
")",
"try",
":",
"word",
"=",
"self",
".",
"_extend_word",
"(",
"word",
",",
"length",
",",
"prefix",
"=",
"prefix",
",",
"end",
"=",
"end",
",",
"flatten",
"=",
"flatten",
")",
"return",
"word",
"except",
"GenerationError",
":",
"first_letters",
".",
"remove",
"(",
"word",
"[",
"0",
"]",
")"
] | Generate a random word of length from this table.
:param length: the length of the generated word; >= 1;
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param start: if True, the generated word starts as a word of table;
:param end: if True, the generated word ends as a word of table;
:param flatten: whether or not consider the table as flattened;
:return: a random word of length generated from table.
:raises GenerationError: if no word of length can be generated. | [
"Generate",
"a",
"random",
"word",
"of",
"length",
"from",
"this",
"table",
"."
] | 7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b | https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/table.py#L129-L157 |
250,242 | sbusard/wagoner | wagoner/table.py | Table._extend_word | def _extend_word(self, word, length, prefix=0, end=False, flatten=False):
"""
Extend the given word with a random suffix up to length.
:param length: the length of the extended word; >= len(word);
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param end: if True, the generated word ends as a word of table;
:param flatten: whether or not consider the table as flattened;
:return: a random word of length generated from table, extending word.
:raises GenerationError: if the generated word cannot be extended to
length.
"""
if len(word) == length:
if end and "<" not in self[word[-1]]:
raise GenerationError(word + " cannot be extended")
else:
return word
else: # len(word) < length
exclude = {"<"}
while True:
choices = self.weighted_choices(word[-prefix
if prefix > 0
else 0:],
exclude=exclude,
flatten=flatten)
if not choices:
raise GenerationError(word + " cannot be extended")
# Extend with the weighted choice
character = random_weighted_choice(choices)
word += character
try:
word = self._extend_word(word, length, prefix=prefix,
end=end, flatten=flatten)
return word
except GenerationError:
exclude.add(character)
word = word[:-1] | python | def _extend_word(self, word, length, prefix=0, end=False, flatten=False):
"""
Extend the given word with a random suffix up to length.
:param length: the length of the extended word; >= len(word);
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param end: if True, the generated word ends as a word of table;
:param flatten: whether or not consider the table as flattened;
:return: a random word of length generated from table, extending word.
:raises GenerationError: if the generated word cannot be extended to
length.
"""
if len(word) == length:
if end and "<" not in self[word[-1]]:
raise GenerationError(word + " cannot be extended")
else:
return word
else: # len(word) < length
exclude = {"<"}
while True:
choices = self.weighted_choices(word[-prefix
if prefix > 0
else 0:],
exclude=exclude,
flatten=flatten)
if not choices:
raise GenerationError(word + " cannot be extended")
# Extend with the weighted choice
character = random_weighted_choice(choices)
word += character
try:
word = self._extend_word(word, length, prefix=prefix,
end=end, flatten=flatten)
return word
except GenerationError:
exclude.add(character)
word = word[:-1] | [
"def",
"_extend_word",
"(",
"self",
",",
"word",
",",
"length",
",",
"prefix",
"=",
"0",
",",
"end",
"=",
"False",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"len",
"(",
"word",
")",
"==",
"length",
":",
"if",
"end",
"and",
"\"<\"",
"not",
"in",
"self",
"[",
"word",
"[",
"-",
"1",
"]",
"]",
":",
"raise",
"GenerationError",
"(",
"word",
"+",
"\" cannot be extended\"",
")",
"else",
":",
"return",
"word",
"else",
":",
"# len(word) < length",
"exclude",
"=",
"{",
"\"<\"",
"}",
"while",
"True",
":",
"choices",
"=",
"self",
".",
"weighted_choices",
"(",
"word",
"[",
"-",
"prefix",
"if",
"prefix",
">",
"0",
"else",
"0",
":",
"]",
",",
"exclude",
"=",
"exclude",
",",
"flatten",
"=",
"flatten",
")",
"if",
"not",
"choices",
":",
"raise",
"GenerationError",
"(",
"word",
"+",
"\" cannot be extended\"",
")",
"# Extend with the weighted choice",
"character",
"=",
"random_weighted_choice",
"(",
"choices",
")",
"word",
"+=",
"character",
"try",
":",
"word",
"=",
"self",
".",
"_extend_word",
"(",
"word",
",",
"length",
",",
"prefix",
"=",
"prefix",
",",
"end",
"=",
"end",
",",
"flatten",
"=",
"flatten",
")",
"return",
"word",
"except",
"GenerationError",
":",
"exclude",
".",
"add",
"(",
"character",
")",
"word",
"=",
"word",
"[",
":",
"-",
"1",
"]"
] | Extend the given word with a random suffix up to length.
:param length: the length of the extended word; >= len(word);
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param end: if True, the generated word ends as a word of table;
:param flatten: whether or not consider the table as flattened;
:return: a random word of length generated from table, extending word.
:raises GenerationError: if the generated word cannot be extended to
length. | [
"Extend",
"the",
"given",
"word",
"with",
"a",
"random",
"suffix",
"up",
"to",
"length",
"."
] | 7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b | https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/table.py#L159-L196 |
250,243 | exekias/droplet | droplet/util.py | import_module | def import_module(module_path):
"""
Try to import and return the given module, if it exists, None if it doesn't
exist
:raises ImportError: When imported module contains errors
"""
if six.PY2:
try:
return importlib.import_module(module_path)
except ImportError:
tb = sys.exc_info()[2]
stack = traceback.extract_tb(tb, 3)
if len(stack) > 2:
raise
else:
from importlib import find_loader
if find_loader(module_path):
return importlib.import_module(module_path) | python | def import_module(module_path):
"""
Try to import and return the given module, if it exists, None if it doesn't
exist
:raises ImportError: When imported module contains errors
"""
if six.PY2:
try:
return importlib.import_module(module_path)
except ImportError:
tb = sys.exc_info()[2]
stack = traceback.extract_tb(tb, 3)
if len(stack) > 2:
raise
else:
from importlib import find_loader
if find_loader(module_path):
return importlib.import_module(module_path) | [
"def",
"import_module",
"(",
"module_path",
")",
":",
"if",
"six",
".",
"PY2",
":",
"try",
":",
"return",
"importlib",
".",
"import_module",
"(",
"module_path",
")",
"except",
"ImportError",
":",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"stack",
"=",
"traceback",
".",
"extract_tb",
"(",
"tb",
",",
"3",
")",
"if",
"len",
"(",
"stack",
")",
">",
"2",
":",
"raise",
"else",
":",
"from",
"importlib",
"import",
"find_loader",
"if",
"find_loader",
"(",
"module_path",
")",
":",
"return",
"importlib",
".",
"import_module",
"(",
"module_path",
")"
] | Try to import and return the given module, if it exists, None if it doesn't
exist
:raises ImportError: When imported module contains errors | [
"Try",
"to",
"import",
"and",
"return",
"the",
"given",
"module",
"if",
"it",
"exists",
"None",
"if",
"it",
"doesn",
"t",
"exist"
] | aeac573a2c1c4b774e99d5414a1c79b1bb734941 | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/util.py#L28-L46 |
250,244 | exekias/droplet | droplet/util.py | make_password | def make_password(length, chars=string.letters + string.digits + '#$%&!'):
"""
Generate and return a random password
:param length: Desired length
:param chars: Character set to use
"""
return get_random_string(length, chars) | python | def make_password(length, chars=string.letters + string.digits + '#$%&!'):
"""
Generate and return a random password
:param length: Desired length
:param chars: Character set to use
"""
return get_random_string(length, chars) | [
"def",
"make_password",
"(",
"length",
",",
"chars",
"=",
"string",
".",
"letters",
"+",
"string",
".",
"digits",
"+",
"'#$%&!'",
")",
":",
"return",
"get_random_string",
"(",
"length",
",",
"chars",
")"
] | Generate and return a random password
:param length: Desired length
:param chars: Character set to use | [
"Generate",
"and",
"return",
"a",
"random",
"password"
] | aeac573a2c1c4b774e99d5414a1c79b1bb734941 | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/util.py#L49-L56 |
250,245 | tdeck/rodong | rodong.py | RodongSinmun.__load_section | def __load_section(self, section_key):
"""
Reads the set of article links for a section if they are not cached.
"""
if self._sections[section_key] is not None: return
articles = []
for page in count(1):
if page > 50:
raise Exception('Last page detection is probably broken')
url = '{domain}{section}&iMenuID=1&iSubMenuID={page}'.format(
domain = DOMAIN,
section = SECTIONS[section_key],
page = page
)
body = self._session.get(url).content
# This is a very hacky way of detecting the last page
# that will probably break again in the future
if "알수 없는 주소" in body: # "Unknown Address"
break
# Parse out all the article links
root = html.fromstring(body)
title_lines = root.find_class('ListNewsLineTitle')
for title_line in title_lines:
title_link = title_line.find('a')
# The links do a JS open in a new window, so we need to parse
# it out using this ugly, brittle junk
href = title_link.get('href')
match = re.match("javascript:article_open\('(.+)'\)", href)
if not match:
raise Exception("The site's link format has changed and is not compatible")
path = match.group(1).decode('string_escape')
articles.append(Article(
self._session,
title_link.text_content().strip(),
DOMAIN + '/en/' + path
))
self._sections[section_key] = articles | python | def __load_section(self, section_key):
"""
Reads the set of article links for a section if they are not cached.
"""
if self._sections[section_key] is not None: return
articles = []
for page in count(1):
if page > 50:
raise Exception('Last page detection is probably broken')
url = '{domain}{section}&iMenuID=1&iSubMenuID={page}'.format(
domain = DOMAIN,
section = SECTIONS[section_key],
page = page
)
body = self._session.get(url).content
# This is a very hacky way of detecting the last page
# that will probably break again in the future
if "알수 없는 주소" in body: # "Unknown Address"
break
# Parse out all the article links
root = html.fromstring(body)
title_lines = root.find_class('ListNewsLineTitle')
for title_line in title_lines:
title_link = title_line.find('a')
# The links do a JS open in a new window, so we need to parse
# it out using this ugly, brittle junk
href = title_link.get('href')
match = re.match("javascript:article_open\('(.+)'\)", href)
if not match:
raise Exception("The site's link format has changed and is not compatible")
path = match.group(1).decode('string_escape')
articles.append(Article(
self._session,
title_link.text_content().strip(),
DOMAIN + '/en/' + path
))
self._sections[section_key] = articles | [
"def",
"__load_section",
"(",
"self",
",",
"section_key",
")",
":",
"if",
"self",
".",
"_sections",
"[",
"section_key",
"]",
"is",
"not",
"None",
":",
"return",
"articles",
"=",
"[",
"]",
"for",
"page",
"in",
"count",
"(",
"1",
")",
":",
"if",
"page",
">",
"50",
":",
"raise",
"Exception",
"(",
"'Last page detection is probably broken'",
")",
"url",
"=",
"'{domain}{section}&iMenuID=1&iSubMenuID={page}'",
".",
"format",
"(",
"domain",
"=",
"DOMAIN",
",",
"section",
"=",
"SECTIONS",
"[",
"section_key",
"]",
",",
"page",
"=",
"page",
")",
"body",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"url",
")",
".",
"content",
"# This is a very hacky way of detecting the last page",
"# that will probably break again in the future",
"if",
"\"알수 없는 주소\" in body: # ",
"Un",
"nown",
" ",
"ddress\"",
"break",
"# Parse out all the article links",
"root",
"=",
"html",
".",
"fromstring",
"(",
"body",
")",
"title_lines",
"=",
"root",
".",
"find_class",
"(",
"'ListNewsLineTitle'",
")",
"for",
"title_line",
"in",
"title_lines",
":",
"title_link",
"=",
"title_line",
".",
"find",
"(",
"'a'",
")",
"# The links do a JS open in a new window, so we need to parse",
"# it out using this ugly, brittle junk",
"href",
"=",
"title_link",
".",
"get",
"(",
"'href'",
")",
"match",
"=",
"re",
".",
"match",
"(",
"\"javascript:article_open\\('(.+)'\\)\"",
",",
"href",
")",
"if",
"not",
"match",
":",
"raise",
"Exception",
"(",
"\"The site's link format has changed and is not compatible\"",
")",
"path",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"decode",
"(",
"'string_escape'",
")",
"articles",
".",
"append",
"(",
"Article",
"(",
"self",
".",
"_session",
",",
"title_link",
".",
"text_content",
"(",
")",
".",
"strip",
"(",
")",
",",
"DOMAIN",
"+",
"'/en/'",
"+",
"path",
")",
")",
"self",
".",
"_sections",
"[",
"section_key",
"]",
"=",
"articles"
] | Reads the set of article links for a section if they are not cached. | [
"Reads",
"the",
"set",
"of",
"article",
"links",
"for",
"a",
"section",
"if",
"they",
"are",
"not",
"cached",
"."
] | 6247148e585ee323925cefb2494e9833e138e293 | https://github.com/tdeck/rodong/blob/6247148e585ee323925cefb2494e9833e138e293/rodong.py#L36-L80 |
250,246 | tdeck/rodong | rodong.py | Article.__load | def __load(self):
""" Loads text and photos if they are not cached. """
if self._text is not None: return
body = self._session.get(self.url).content
root = html.fromstring(body)
self._text = "\n".join((
p_tag.text_content()
for p_tag in root.findall('.//p[@class="ArticleContent"]')
if 'justify' in p_tag.get('style', '')
))
# TODO fix this
self._photos = [] | python | def __load(self):
""" Loads text and photos if they are not cached. """
if self._text is not None: return
body = self._session.get(self.url).content
root = html.fromstring(body)
self._text = "\n".join((
p_tag.text_content()
for p_tag in root.findall('.//p[@class="ArticleContent"]')
if 'justify' in p_tag.get('style', '')
))
# TODO fix this
self._photos = [] | [
"def",
"__load",
"(",
"self",
")",
":",
"if",
"self",
".",
"_text",
"is",
"not",
"None",
":",
"return",
"body",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"self",
".",
"url",
")",
".",
"content",
"root",
"=",
"html",
".",
"fromstring",
"(",
"body",
")",
"self",
".",
"_text",
"=",
"\"\\n\"",
".",
"join",
"(",
"(",
"p_tag",
".",
"text_content",
"(",
")",
"for",
"p_tag",
"in",
"root",
".",
"findall",
"(",
"'.//p[@class=\"ArticleContent\"]'",
")",
"if",
"'justify'",
"in",
"p_tag",
".",
"get",
"(",
"'style'",
",",
"''",
")",
")",
")",
"# TODO fix this",
"self",
".",
"_photos",
"=",
"[",
"]"
] | Loads text and photos if they are not cached. | [
"Loads",
"text",
"and",
"photos",
"if",
"they",
"are",
"not",
"cached",
"."
] | 6247148e585ee323925cefb2494e9833e138e293 | https://github.com/tdeck/rodong/blob/6247148e585ee323925cefb2494e9833e138e293/rodong.py#L100-L113 |
250,247 | mgagne/wafflehaus.iweb | wafflehaus/iweb/glance/image_filter/visible.py | VisibleFilter._is_whitelisted | def _is_whitelisted(self, req):
"""Return True if role is whitelisted or roles cannot be determined."""
if not self.roles_whitelist:
return False
if not hasattr(req, 'context'):
self.log.info("No context found.")
return False
if not hasattr(req.context, 'roles'):
self.log.info("No roles found in context")
return False
roles = req.context.roles
self.log.debug("Received request from user with roles: %s",
' '.join(roles))
for key in self.roles_whitelist:
if key in roles:
self.log.debug("User role (%s) is whitelisted.", key)
return True
return False | python | def _is_whitelisted(self, req):
"""Return True if role is whitelisted or roles cannot be determined."""
if not self.roles_whitelist:
return False
if not hasattr(req, 'context'):
self.log.info("No context found.")
return False
if not hasattr(req.context, 'roles'):
self.log.info("No roles found in context")
return False
roles = req.context.roles
self.log.debug("Received request from user with roles: %s",
' '.join(roles))
for key in self.roles_whitelist:
if key in roles:
self.log.debug("User role (%s) is whitelisted.", key)
return True
return False | [
"def",
"_is_whitelisted",
"(",
"self",
",",
"req",
")",
":",
"if",
"not",
"self",
".",
"roles_whitelist",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"req",
",",
"'context'",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"No context found.\"",
")",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"req",
".",
"context",
",",
"'roles'",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"No roles found in context\"",
")",
"return",
"False",
"roles",
"=",
"req",
".",
"context",
".",
"roles",
"self",
".",
"log",
".",
"debug",
"(",
"\"Received request from user with roles: %s\"",
",",
"' '",
".",
"join",
"(",
"roles",
")",
")",
"for",
"key",
"in",
"self",
".",
"roles_whitelist",
":",
"if",
"key",
"in",
"roles",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"User role (%s) is whitelisted.\"",
",",
"key",
")",
"return",
"True",
"return",
"False"
] | Return True if role is whitelisted or roles cannot be determined. | [
"Return",
"True",
"if",
"role",
"is",
"whitelisted",
"or",
"roles",
"cannot",
"be",
"determined",
"."
] | 8ac625582c1180391fe022d1db19f70a2dfb376a | https://github.com/mgagne/wafflehaus.iweb/blob/8ac625582c1180391fe022d1db19f70a2dfb376a/wafflehaus/iweb/glance/image_filter/visible.py#L55-L77 |
250,248 | tBaxter/django-fretboard | fretboard/views/crud.py | add_topic | def add_topic(request, forum_slug=None):
""" Adds a topic to a given forum """
forum = Forum.objects.get(slug=forum_slug)
form = AddTopicForm(request.POST or None, request.FILES or None, initial={'forum': forum})
current_time = time.time()
user = request.user
if form.is_valid():
instance = form.save(commit=False)
instance.forum = forum
instance.name = strip_tags(instance.name)
instance.slug = slugify(instance.name)
instance.user = user
instance.author = user.display_name
instance.lastpost_author = user.display_name
instance.created_int = current_time
instance.modified_int = current_time
instance.save()
# and now add the child post
post = Post(
topic = instance,
text = request.POST['text'],
user = user,
post_date_int = current_time
)
if request.FILES:
post.image = request.FILES['image']
post.save()
return HttpResponseRedirect("/forum/%s/?new_topic=%s" % (forum_slug, instance.id))
return render(request, 'fretboard/add_edit.html', {
'form': form,
'form_title': 'Add a topic',
'FORUM_BASE_NAME': FORUM_BASE_NAME
}) | python | def add_topic(request, forum_slug=None):
""" Adds a topic to a given forum """
forum = Forum.objects.get(slug=forum_slug)
form = AddTopicForm(request.POST or None, request.FILES or None, initial={'forum': forum})
current_time = time.time()
user = request.user
if form.is_valid():
instance = form.save(commit=False)
instance.forum = forum
instance.name = strip_tags(instance.name)
instance.slug = slugify(instance.name)
instance.user = user
instance.author = user.display_name
instance.lastpost_author = user.display_name
instance.created_int = current_time
instance.modified_int = current_time
instance.save()
# and now add the child post
post = Post(
topic = instance,
text = request.POST['text'],
user = user,
post_date_int = current_time
)
if request.FILES:
post.image = request.FILES['image']
post.save()
return HttpResponseRedirect("/forum/%s/?new_topic=%s" % (forum_slug, instance.id))
return render(request, 'fretboard/add_edit.html', {
'form': form,
'form_title': 'Add a topic',
'FORUM_BASE_NAME': FORUM_BASE_NAME
}) | [
"def",
"add_topic",
"(",
"request",
",",
"forum_slug",
"=",
"None",
")",
":",
"forum",
"=",
"Forum",
".",
"objects",
".",
"get",
"(",
"slug",
"=",
"forum_slug",
")",
"form",
"=",
"AddTopicForm",
"(",
"request",
".",
"POST",
"or",
"None",
",",
"request",
".",
"FILES",
"or",
"None",
",",
"initial",
"=",
"{",
"'forum'",
":",
"forum",
"}",
")",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"user",
"=",
"request",
".",
"user",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"instance",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"instance",
".",
"forum",
"=",
"forum",
"instance",
".",
"name",
"=",
"strip_tags",
"(",
"instance",
".",
"name",
")",
"instance",
".",
"slug",
"=",
"slugify",
"(",
"instance",
".",
"name",
")",
"instance",
".",
"user",
"=",
"user",
"instance",
".",
"author",
"=",
"user",
".",
"display_name",
"instance",
".",
"lastpost_author",
"=",
"user",
".",
"display_name",
"instance",
".",
"created_int",
"=",
"current_time",
"instance",
".",
"modified_int",
"=",
"current_time",
"instance",
".",
"save",
"(",
")",
"# and now add the child post",
"post",
"=",
"Post",
"(",
"topic",
"=",
"instance",
",",
"text",
"=",
"request",
".",
"POST",
"[",
"'text'",
"]",
",",
"user",
"=",
"user",
",",
"post_date_int",
"=",
"current_time",
")",
"if",
"request",
".",
"FILES",
":",
"post",
".",
"image",
"=",
"request",
".",
"FILES",
"[",
"'image'",
"]",
"post",
".",
"save",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"\"/forum/%s/?new_topic=%s\"",
"%",
"(",
"forum_slug",
",",
"instance",
".",
"id",
")",
")",
"return",
"render",
"(",
"request",
",",
"'fretboard/add_edit.html'",
",",
"{",
"'form'",
":",
"form",
",",
"'form_title'",
":",
"'Add a topic'",
",",
"'FORUM_BASE_NAME'",
":",
"FORUM_BASE_NAME",
"}",
")"
] | Adds a topic to a given forum | [
"Adds",
"a",
"topic",
"to",
"a",
"given",
"forum"
] | 3c3f9557089821283f315a07f3e5a57a2725ab3b | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/views/crud.py#L19-L56 |
250,249 | tBaxter/django-fretboard | fretboard/views/crud.py | add_post | def add_post(request, t_slug, t_id, p_id = False): # topic slug, topic id, post id
"""
Creates a new post and attaches it to a topic
"""
topic = get_object_or_404(Topic, id=t_id)
topic_url = '{0}page{1}/'.format(topic.get_short_url(), topic.page_count)
user = request.user
current_time = time.time()
form_title = 'Add a post'
if topic.is_locked: # If we mistakenly allowed reply on locked topic, bail with error msg.
messages.error(request, 'Sorry, but this topic is closed')
return HttpResponseRedirect(topic_url)
q = None
if p_id: # if there's a post id, it's a quote
q = Post.objects.get(id=p_id)
form_title = "Respond to post"
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
# we're going to save this inital data now,
# rather than on the model save()
# because we only want to bother with this stuff one time
# and it will never update or change.
instance = form.save(commit=False)
instance.topic = topic
instance.user = user
instance.author_name = user.display_name
instance.avatar = user.avatar
instance.post_date_int = current_time
instance.quote = q
instance.save()
update_post_relations(user, topic)
return HttpResponseRedirect('%s?new_post=%s#post-%s' % (topic_url, t_id, instance.id))
return render(request, 'fretboard/add_edit.html', {
'form': form,
'form_title': form_title,
'quote': q,
'FORUM_BASE_NAME': FORUM_BASE_NAME
}) | python | def add_post(request, t_slug, t_id, p_id = False): # topic slug, topic id, post id
"""
Creates a new post and attaches it to a topic
"""
topic = get_object_or_404(Topic, id=t_id)
topic_url = '{0}page{1}/'.format(topic.get_short_url(), topic.page_count)
user = request.user
current_time = time.time()
form_title = 'Add a post'
if topic.is_locked: # If we mistakenly allowed reply on locked topic, bail with error msg.
messages.error(request, 'Sorry, but this topic is closed')
return HttpResponseRedirect(topic_url)
q = None
if p_id: # if there's a post id, it's a quote
q = Post.objects.get(id=p_id)
form_title = "Respond to post"
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
# we're going to save this inital data now,
# rather than on the model save()
# because we only want to bother with this stuff one time
# and it will never update or change.
instance = form.save(commit=False)
instance.topic = topic
instance.user = user
instance.author_name = user.display_name
instance.avatar = user.avatar
instance.post_date_int = current_time
instance.quote = q
instance.save()
update_post_relations(user, topic)
return HttpResponseRedirect('%s?new_post=%s#post-%s' % (topic_url, t_id, instance.id))
return render(request, 'fretboard/add_edit.html', {
'form': form,
'form_title': form_title,
'quote': q,
'FORUM_BASE_NAME': FORUM_BASE_NAME
}) | [
"def",
"add_post",
"(",
"request",
",",
"t_slug",
",",
"t_id",
",",
"p_id",
"=",
"False",
")",
":",
"# topic slug, topic id, post id",
"topic",
"=",
"get_object_or_404",
"(",
"Topic",
",",
"id",
"=",
"t_id",
")",
"topic_url",
"=",
"'{0}page{1}/'",
".",
"format",
"(",
"topic",
".",
"get_short_url",
"(",
")",
",",
"topic",
".",
"page_count",
")",
"user",
"=",
"request",
".",
"user",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"form_title",
"=",
"'Add a post'",
"if",
"topic",
".",
"is_locked",
":",
"# If we mistakenly allowed reply on locked topic, bail with error msg.",
"messages",
".",
"error",
"(",
"request",
",",
"'Sorry, but this topic is closed'",
")",
"return",
"HttpResponseRedirect",
"(",
"topic_url",
")",
"q",
"=",
"None",
"if",
"p_id",
":",
"# if there's a post id, it's a quote",
"q",
"=",
"Post",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"p_id",
")",
"form_title",
"=",
"\"Respond to post\"",
"form",
"=",
"PostForm",
"(",
"request",
".",
"POST",
"or",
"None",
",",
"request",
".",
"FILES",
"or",
"None",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"# we're going to save this inital data now,",
"# rather than on the model save()",
"# because we only want to bother with this stuff one time",
"# and it will never update or change.",
"instance",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"instance",
".",
"topic",
"=",
"topic",
"instance",
".",
"user",
"=",
"user",
"instance",
".",
"author_name",
"=",
"user",
".",
"display_name",
"instance",
".",
"avatar",
"=",
"user",
".",
"avatar",
"instance",
".",
"post_date_int",
"=",
"current_time",
"instance",
".",
"quote",
"=",
"q",
"instance",
".",
"save",
"(",
")",
"update_post_relations",
"(",
"user",
",",
"topic",
")",
"return",
"HttpResponseRedirect",
"(",
"'%s?new_post=%s#post-%s'",
"%",
"(",
"topic_url",
",",
"t_id",
",",
"instance",
".",
"id",
")",
")",
"return",
"render",
"(",
"request",
",",
"'fretboard/add_edit.html'",
",",
"{",
"'form'",
":",
"form",
",",
"'form_title'",
":",
"form_title",
",",
"'quote'",
":",
"q",
",",
"'FORUM_BASE_NAME'",
":",
"FORUM_BASE_NAME",
"}",
")"
] | Creates a new post and attaches it to a topic | [
"Creates",
"a",
"new",
"post",
"and",
"attaches",
"it",
"to",
"a",
"topic"
] | 3c3f9557089821283f315a07f3e5a57a2725ab3b | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/views/crud.py#L60-L104 |
250,250 | tBaxter/django-fretboard | fretboard/views/crud.py | edit_post | def edit_post(request, post_id):
"""
Allows user to edit an existing post.
This needs to be rewritten. Badly.
"""
post = get_object_or_404(Post, id=post_id)
user = request.user
topic = post.topic
# oughta build a get_absolute_url method for this, maybe.
post_url = '{0}page{1}/#post{2}'.format(topic.get_short_url(), topic.page_count, post.id)
if topic.is_locked:
messages.error(request, 'Sorry, but this topic is closed')
return HttpResponseRedirect(post_url)
if user.is_staff is False and user.id != post.author.id:
messages.error(request, "Sorry, but you can't edit this post.")
return HttpResponseRedirect(post_url)
if request.POST and len(request.POST['text']) > 1:
if request.is_ajax and 'body' in request.POST: # AJAX REQUEST
post.text = request.POST['body']
post.save(update_fields=['text', 'text_formatted'])
return HttpResponse(str(post.text))
post.text = request.POST['text']
post.save(update_fields=['text', 'text_formatted'])
if 'name' in request.POST: # updated topic
topic.name = request.POST['name']
topic.save(update_fields=['name'])
return HttpResponseRedirect(post_url)
# this is a get request
else:
if post == topic.post_set.all()[0]:
form = AddTopicForm(instance=topic, initial={'text': post.text})
else:
form = PostForm(instance=post)
return render(request, 'fretboard/add_edit.html', {
'quote': post.quote,
'form' : form,
'form_title': 'Edit post',
}) | python | def edit_post(request, post_id):
"""
Allows user to edit an existing post.
This needs to be rewritten. Badly.
"""
post = get_object_or_404(Post, id=post_id)
user = request.user
topic = post.topic
# oughta build a get_absolute_url method for this, maybe.
post_url = '{0}page{1}/#post{2}'.format(topic.get_short_url(), topic.page_count, post.id)
if topic.is_locked:
messages.error(request, 'Sorry, but this topic is closed')
return HttpResponseRedirect(post_url)
if user.is_staff is False and user.id != post.author.id:
messages.error(request, "Sorry, but you can't edit this post.")
return HttpResponseRedirect(post_url)
if request.POST and len(request.POST['text']) > 1:
if request.is_ajax and 'body' in request.POST: # AJAX REQUEST
post.text = request.POST['body']
post.save(update_fields=['text', 'text_formatted'])
return HttpResponse(str(post.text))
post.text = request.POST['text']
post.save(update_fields=['text', 'text_formatted'])
if 'name' in request.POST: # updated topic
topic.name = request.POST['name']
topic.save(update_fields=['name'])
return HttpResponseRedirect(post_url)
# this is a get request
else:
if post == topic.post_set.all()[0]:
form = AddTopicForm(instance=topic, initial={'text': post.text})
else:
form = PostForm(instance=post)
return render(request, 'fretboard/add_edit.html', {
'quote': post.quote,
'form' : form,
'form_title': 'Edit post',
}) | [
"def",
"edit_post",
"(",
"request",
",",
"post_id",
")",
":",
"post",
"=",
"get_object_or_404",
"(",
"Post",
",",
"id",
"=",
"post_id",
")",
"user",
"=",
"request",
".",
"user",
"topic",
"=",
"post",
".",
"topic",
"# oughta build a get_absolute_url method for this, maybe.",
"post_url",
"=",
"'{0}page{1}/#post{2}'",
".",
"format",
"(",
"topic",
".",
"get_short_url",
"(",
")",
",",
"topic",
".",
"page_count",
",",
"post",
".",
"id",
")",
"if",
"topic",
".",
"is_locked",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'Sorry, but this topic is closed'",
")",
"return",
"HttpResponseRedirect",
"(",
"post_url",
")",
"if",
"user",
".",
"is_staff",
"is",
"False",
"and",
"user",
".",
"id",
"!=",
"post",
".",
"author",
".",
"id",
":",
"messages",
".",
"error",
"(",
"request",
",",
"\"Sorry, but you can't edit this post.\"",
")",
"return",
"HttpResponseRedirect",
"(",
"post_url",
")",
"if",
"request",
".",
"POST",
"and",
"len",
"(",
"request",
".",
"POST",
"[",
"'text'",
"]",
")",
">",
"1",
":",
"if",
"request",
".",
"is_ajax",
"and",
"'body'",
"in",
"request",
".",
"POST",
":",
"# AJAX REQUEST",
"post",
".",
"text",
"=",
"request",
".",
"POST",
"[",
"'body'",
"]",
"post",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'text'",
",",
"'text_formatted'",
"]",
")",
"return",
"HttpResponse",
"(",
"str",
"(",
"post",
".",
"text",
")",
")",
"post",
".",
"text",
"=",
"request",
".",
"POST",
"[",
"'text'",
"]",
"post",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'text'",
",",
"'text_formatted'",
"]",
")",
"if",
"'name'",
"in",
"request",
".",
"POST",
":",
"# updated topic",
"topic",
".",
"name",
"=",
"request",
".",
"POST",
"[",
"'name'",
"]",
"topic",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'name'",
"]",
")",
"return",
"HttpResponseRedirect",
"(",
"post_url",
")",
"# this is a get request",
"else",
":",
"if",
"post",
"==",
"topic",
".",
"post_set",
".",
"all",
"(",
")",
"[",
"0",
"]",
":",
"form",
"=",
"AddTopicForm",
"(",
"instance",
"=",
"topic",
",",
"initial",
"=",
"{",
"'text'",
":",
"post",
".",
"text",
"}",
")",
"else",
":",
"form",
"=",
"PostForm",
"(",
"instance",
"=",
"post",
")",
"return",
"render",
"(",
"request",
",",
"'fretboard/add_edit.html'",
",",
"{",
"'quote'",
":",
"post",
".",
"quote",
",",
"'form'",
":",
"form",
",",
"'form_title'",
":",
"'Edit post'",
",",
"}",
")"
] | Allows user to edit an existing post.
This needs to be rewritten. Badly. | [
"Allows",
"user",
"to",
"edit",
"an",
"existing",
"post",
".",
"This",
"needs",
"to",
"be",
"rewritten",
".",
"Badly",
"."
] | 3c3f9557089821283f315a07f3e5a57a2725ab3b | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/views/crud.py#L108-L150 |
250,251 | tBaxter/django-fretboard | fretboard/views/crud.py | delete_post | def delete_post(request, post_id, topic_id):
"""
Deletes a post, if the user has correct permissions.
Also updates topic.post_count
"""
try:
topic = Topic.objects.get(id=topic_id)
post = Post.objects.get(id=post_id)
except:
messages.error(request, 'Sorry, but this post can not be found. It may have been deleted already.')
raise Http404
return_url = "/forum/%s/%s/%s/" % (topic.forum.slug, topic.slug, topic_id)
if request.user.is_authenticated() and (request.user.is_staff or request.user.id == post.author.id):
post.delete()
update_post_relations(request.user, topic, deleting=True)
topic_posts = topic.post_set.count()
pmax = (topic_posts / PAGINATE_BY) + 1
# if no posts are left, delete topic.
if topic_posts == 0:
topic.delete()
return HttpResponseRedirect("/forum/%s/" % topic.forum.slug)
return HttpResponseRedirect("%spage%s/" % (return_url, pmax))
else:
raise Http404 | python | def delete_post(request, post_id, topic_id):
"""
Deletes a post, if the user has correct permissions.
Also updates topic.post_count
"""
try:
topic = Topic.objects.get(id=topic_id)
post = Post.objects.get(id=post_id)
except:
messages.error(request, 'Sorry, but this post can not be found. It may have been deleted already.')
raise Http404
return_url = "/forum/%s/%s/%s/" % (topic.forum.slug, topic.slug, topic_id)
if request.user.is_authenticated() and (request.user.is_staff or request.user.id == post.author.id):
post.delete()
update_post_relations(request.user, topic, deleting=True)
topic_posts = topic.post_set.count()
pmax = (topic_posts / PAGINATE_BY) + 1
# if no posts are left, delete topic.
if topic_posts == 0:
topic.delete()
return HttpResponseRedirect("/forum/%s/" % topic.forum.slug)
return HttpResponseRedirect("%spage%s/" % (return_url, pmax))
else:
raise Http404 | [
"def",
"delete_post",
"(",
"request",
",",
"post_id",
",",
"topic_id",
")",
":",
"try",
":",
"topic",
"=",
"Topic",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"topic_id",
")",
"post",
"=",
"Post",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"post_id",
")",
"except",
":",
"messages",
".",
"error",
"(",
"request",
",",
"'Sorry, but this post can not be found. It may have been deleted already.'",
")",
"raise",
"Http404",
"return_url",
"=",
"\"/forum/%s/%s/%s/\"",
"%",
"(",
"topic",
".",
"forum",
".",
"slug",
",",
"topic",
".",
"slug",
",",
"topic_id",
")",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"(",
"request",
".",
"user",
".",
"is_staff",
"or",
"request",
".",
"user",
".",
"id",
"==",
"post",
".",
"author",
".",
"id",
")",
":",
"post",
".",
"delete",
"(",
")",
"update_post_relations",
"(",
"request",
".",
"user",
",",
"topic",
",",
"deleting",
"=",
"True",
")",
"topic_posts",
"=",
"topic",
".",
"post_set",
".",
"count",
"(",
")",
"pmax",
"=",
"(",
"topic_posts",
"/",
"PAGINATE_BY",
")",
"+",
"1",
"# if no posts are left, delete topic.",
"if",
"topic_posts",
"==",
"0",
":",
"topic",
".",
"delete",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"\"/forum/%s/\"",
"%",
"topic",
".",
"forum",
".",
"slug",
")",
"return",
"HttpResponseRedirect",
"(",
"\"%spage%s/\"",
"%",
"(",
"return_url",
",",
"pmax",
")",
")",
"else",
":",
"raise",
"Http404"
] | Deletes a post, if the user has correct permissions.
Also updates topic.post_count | [
"Deletes",
"a",
"post",
"if",
"the",
"user",
"has",
"correct",
"permissions",
".",
"Also",
"updates",
"topic",
".",
"post_count"
] | 3c3f9557089821283f315a07f3e5a57a2725ab3b | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/views/crud.py#L153-L178 |
250,252 | 20c/twentyc.tools | twentyc/tools/syslogfix.py | UTFFixedSysLogHandler.emit | def emit(self, record):
"""
Emit a record.
The record is formatted, and then sent to the syslog server. If
exception information is present, it is NOT sent to the server.
"""
msg = self.format(record) + '\000'
"""
We need to convert record level to lowercase, maybe this will
change in the future.
"""
prio = '<%d>' % self.encodePriority(self.facility,
self.mapPriority(record.levelname))
prio = prio.encode('utf-8')
# Message is a string. Convert to bytes as required by RFC 5424.
msg = msg.encode('utf-8')
if codecs:
msg = codecs.BOM_UTF8 + msg
msg = prio + msg
try:
if self.unixsocket:
try:
self.socket.send(msg)
except socket.error:
self._connect_unixsocket(self.address)
self.socket.send(msg)
elif self.socktype == socket.SOCK_DGRAM:
self.socket.sendto(msg, self.address)
else:
self.socket.sendall(msg)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) | python | def emit(self, record):
"""
Emit a record.
The record is formatted, and then sent to the syslog server. If
exception information is present, it is NOT sent to the server.
"""
msg = self.format(record) + '\000'
"""
We need to convert record level to lowercase, maybe this will
change in the future.
"""
prio = '<%d>' % self.encodePriority(self.facility,
self.mapPriority(record.levelname))
prio = prio.encode('utf-8')
# Message is a string. Convert to bytes as required by RFC 5424.
msg = msg.encode('utf-8')
if codecs:
msg = codecs.BOM_UTF8 + msg
msg = prio + msg
try:
if self.unixsocket:
try:
self.socket.send(msg)
except socket.error:
self._connect_unixsocket(self.address)
self.socket.send(msg)
elif self.socktype == socket.SOCK_DGRAM:
self.socket.sendto(msg, self.address)
else:
self.socket.sendall(msg)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"msg",
"=",
"self",
".",
"format",
"(",
"record",
")",
"+",
"'\\000'",
"\"\"\"\n\t\tWe need to convert record level to lowercase, maybe this will\n\t\tchange in the future.\n\t\t\"\"\"",
"prio",
"=",
"'<%d>'",
"%",
"self",
".",
"encodePriority",
"(",
"self",
".",
"facility",
",",
"self",
".",
"mapPriority",
"(",
"record",
".",
"levelname",
")",
")",
"prio",
"=",
"prio",
".",
"encode",
"(",
"'utf-8'",
")",
"# Message is a string. Convert to bytes as required by RFC 5424.",
"msg",
"=",
"msg",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"codecs",
":",
"msg",
"=",
"codecs",
".",
"BOM_UTF8",
"+",
"msg",
"msg",
"=",
"prio",
"+",
"msg",
"try",
":",
"if",
"self",
".",
"unixsocket",
":",
"try",
":",
"self",
".",
"socket",
".",
"send",
"(",
"msg",
")",
"except",
"socket",
".",
"error",
":",
"self",
".",
"_connect_unixsocket",
"(",
"self",
".",
"address",
")",
"self",
".",
"socket",
".",
"send",
"(",
"msg",
")",
"elif",
"self",
".",
"socktype",
"==",
"socket",
".",
"SOCK_DGRAM",
":",
"self",
".",
"socket",
".",
"sendto",
"(",
"msg",
",",
"self",
".",
"address",
")",
"else",
":",
"self",
".",
"socket",
".",
"sendall",
"(",
"msg",
")",
"except",
"(",
"KeyboardInterrupt",
",",
"SystemExit",
")",
":",
"raise",
"except",
":",
"self",
".",
"handleError",
"(",
"record",
")"
] | Emit a record.
The record is formatted, and then sent to the syslog server. If
exception information is present, it is NOT sent to the server. | [
"Emit",
"a",
"record",
".",
"The",
"record",
"is",
"formatted",
"and",
"then",
"sent",
"to",
"the",
"syslog",
"server",
".",
"If",
"exception",
"information",
"is",
"present",
"it",
"is",
"NOT",
"sent",
"to",
"the",
"server",
"."
] | f8f681e64f58d449bfc32646ba8bcc57db90a233 | https://github.com/20c/twentyc.tools/blob/f8f681e64f58d449bfc32646ba8bcc57db90a233/twentyc/tools/syslogfix.py#L21-L55 |
250,253 | ulf1/oxyba | oxyba/jackknife_loop.py | jackknife_loop | def jackknife_loop(func, data, d=1, combolimit=int(1e6)):
"""Generic Jackknife Subsampling procedure
func : function
A function pointer to a python function that
- accept an <Observations x Features> matrix
as input variable, and
- returns an array/list or scalar value as
estimate, metric, model parameter,
jackknife replicate, etc.
data : ndarray
A <Observations x Features> numpy array
d : int
The number of observations to leave out for
each Jackknife subsample, i.e. the subsample
size is N-d. (The default is d=1 for the
"Delete-1 Jackknife" procedure.)
combolimit : int
Maximum numbers of subsamples for binocoeff(N,d)
combinations. (Default combolimit=1e6)
Notes:
------
Be aware that binom(N,d) can quickly exceed
your computer's capabilities. The "Delete-d
Jackknife" approaches are reasonable for
small sample sizes, e.g. N=50 and d=3 result
in 19600 subsamples to compute.
Returns:
--------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e. C=binocoeff(N,d)
subsamples, and M parameters that are returned
by the model.
theta_full : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for the full sample.
It is a <1 x M> vecotr with the M parameters
that are returned by the model.
Example:
--------
import numpy as np
import oxyba as ox
from sklearn.datasets import load_boston
def myfunc(data):
import oxyba as ox
return ox.linreg_ols_lu( data[:,0], data[:,1:] )
tmp = load_boston()
y = tmp.target
X = tmp.data[:,[5,12]]
theta_subs, theta_full = ox.jackknife_loop(myfunc, np.c_[y, X], d=1)
"""
# load modules
import scipy.special
import warnings
import itertools
import numpy as np
# How many observations contains data?
N = data.shape[0]
# throw a warning!
numcombos = scipy.special.comb(N, d, exact=True) # binocoeff
if numcombos > 1e5:
warnings.warn((
"N={0:d} and d={1:d} result in {2:d} "
"combinations to compute").format(N, d, numcombos))
if numcombos > combolimit:
raise Exception("Number of combinations exceeds 'combolimit'.")
# list of tuples that contain all combinations of
# row indicies to leave out
leaveout = list(itertools.combinations(range(N), d))
# store all metrics, estimates, model parameters
# as list/array or scalar in one list
theta_subsample = []
# loop over all combinations
idx = np.arange(0, N)
for c in range(numcombos):
# create true/false index for the c-th subsample
# i.e. all true except the d leaveout indicies
subidx = np.isin(idx, leaveout[c], assume_unique=True, invert=True)
# compute metrics and store them
theta_subsample.append(func(data[subidx, :]))
# compute metrics on the full sample
theta_fullsample = func(data)
# done
return np.array(theta_subsample), np.array(theta_fullsample) | python | def jackknife_loop(func, data, d=1, combolimit=int(1e6)):
"""Generic Jackknife Subsampling procedure
func : function
A function pointer to a python function that
- accept an <Observations x Features> matrix
as input variable, and
- returns an array/list or scalar value as
estimate, metric, model parameter,
jackknife replicate, etc.
data : ndarray
A <Observations x Features> numpy array
d : int
The number of observations to leave out for
each Jackknife subsample, i.e. the subsample
size is N-d. (The default is d=1 for the
"Delete-1 Jackknife" procedure.)
combolimit : int
Maximum numbers of subsamples for binocoeff(N,d)
combinations. (Default combolimit=1e6)
Notes:
------
Be aware that binom(N,d) can quickly exceed
your computer's capabilities. The "Delete-d
Jackknife" approaches are reasonable for
small sample sizes, e.g. N=50 and d=3 result
in 19600 subsamples to compute.
Returns:
--------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e. C=binocoeff(N,d)
subsamples, and M parameters that are returned
by the model.
theta_full : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for the full sample.
It is a <1 x M> vecotr with the M parameters
that are returned by the model.
Example:
--------
import numpy as np
import oxyba as ox
from sklearn.datasets import load_boston
def myfunc(data):
import oxyba as ox
return ox.linreg_ols_lu( data[:,0], data[:,1:] )
tmp = load_boston()
y = tmp.target
X = tmp.data[:,[5,12]]
theta_subs, theta_full = ox.jackknife_loop(myfunc, np.c_[y, X], d=1)
"""
# load modules
import scipy.special
import warnings
import itertools
import numpy as np
# How many observations contains data?
N = data.shape[0]
# throw a warning!
numcombos = scipy.special.comb(N, d, exact=True) # binocoeff
if numcombos > 1e5:
warnings.warn((
"N={0:d} and d={1:d} result in {2:d} "
"combinations to compute").format(N, d, numcombos))
if numcombos > combolimit:
raise Exception("Number of combinations exceeds 'combolimit'.")
# list of tuples that contain all combinations of
# row indicies to leave out
leaveout = list(itertools.combinations(range(N), d))
# store all metrics, estimates, model parameters
# as list/array or scalar in one list
theta_subsample = []
# loop over all combinations
idx = np.arange(0, N)
for c in range(numcombos):
# create true/false index for the c-th subsample
# i.e. all true except the d leaveout indicies
subidx = np.isin(idx, leaveout[c], assume_unique=True, invert=True)
# compute metrics and store them
theta_subsample.append(func(data[subidx, :]))
# compute metrics on the full sample
theta_fullsample = func(data)
# done
return np.array(theta_subsample), np.array(theta_fullsample) | [
"def",
"jackknife_loop",
"(",
"func",
",",
"data",
",",
"d",
"=",
"1",
",",
"combolimit",
"=",
"int",
"(",
"1e6",
")",
")",
":",
"# load modules",
"import",
"scipy",
".",
"special",
"import",
"warnings",
"import",
"itertools",
"import",
"numpy",
"as",
"np",
"# How many observations contains data?",
"N",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"# throw a warning!",
"numcombos",
"=",
"scipy",
".",
"special",
".",
"comb",
"(",
"N",
",",
"d",
",",
"exact",
"=",
"True",
")",
"# binocoeff",
"if",
"numcombos",
">",
"1e5",
":",
"warnings",
".",
"warn",
"(",
"(",
"\"N={0:d} and d={1:d} result in {2:d} \"",
"\"combinations to compute\"",
")",
".",
"format",
"(",
"N",
",",
"d",
",",
"numcombos",
")",
")",
"if",
"numcombos",
">",
"combolimit",
":",
"raise",
"Exception",
"(",
"\"Number of combinations exceeds 'combolimit'.\"",
")",
"# list of tuples that contain all combinations of",
"# row indicies to leave out",
"leaveout",
"=",
"list",
"(",
"itertools",
".",
"combinations",
"(",
"range",
"(",
"N",
")",
",",
"d",
")",
")",
"# store all metrics, estimates, model parameters",
"# as list/array or scalar in one list",
"theta_subsample",
"=",
"[",
"]",
"# loop over all combinations",
"idx",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"N",
")",
"for",
"c",
"in",
"range",
"(",
"numcombos",
")",
":",
"# create true/false index for the c-th subsample",
"# i.e. all true except the d leaveout indicies",
"subidx",
"=",
"np",
".",
"isin",
"(",
"idx",
",",
"leaveout",
"[",
"c",
"]",
",",
"assume_unique",
"=",
"True",
",",
"invert",
"=",
"True",
")",
"# compute metrics and store them",
"theta_subsample",
".",
"append",
"(",
"func",
"(",
"data",
"[",
"subidx",
",",
":",
"]",
")",
")",
"# compute metrics on the full sample",
"theta_fullsample",
"=",
"func",
"(",
"data",
")",
"# done",
"return",
"np",
".",
"array",
"(",
"theta_subsample",
")",
",",
"np",
".",
"array",
"(",
"theta_fullsample",
")"
] | Generic Jackknife Subsampling procedure
func : function
A function pointer to a python function that
- accept an <Observations x Features> matrix
as input variable, and
- returns an array/list or scalar value as
estimate, metric, model parameter,
jackknife replicate, etc.
data : ndarray
A <Observations x Features> numpy array
d : int
The number of observations to leave out for
each Jackknife subsample, i.e. the subsample
size is N-d. (The default is d=1 for the
"Delete-1 Jackknife" procedure.)
combolimit : int
Maximum numbers of subsamples for binocoeff(N,d)
combinations. (Default combolimit=1e6)
Notes:
------
Be aware that binom(N,d) can quickly exceed
your computer's capabilities. The "Delete-d
Jackknife" approaches are reasonable for
small sample sizes, e.g. N=50 and d=3 result
in 19600 subsamples to compute.
Returns:
--------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e. C=binocoeff(N,d)
subsamples, and M parameters that are returned
by the model.
theta_full : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for the full sample.
It is a <1 x M> vecotr with the M parameters
that are returned by the model.
Example:
--------
import numpy as np
import oxyba as ox
from sklearn.datasets import load_boston
def myfunc(data):
import oxyba as ox
return ox.linreg_ols_lu( data[:,0], data[:,1:] )
tmp = load_boston()
y = tmp.target
X = tmp.data[:,[5,12]]
theta_subs, theta_full = ox.jackknife_loop(myfunc, np.c_[y, X], d=1) | [
"Generic",
"Jackknife",
"Subsampling",
"procedure"
] | b3043116050de275124365cb11e7df91fb40169d | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/jackknife_loop.py#L2-L106 |
250,254 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | create_zone | def create_zone(server, token, domain, identifier, dtype, master=None):
"""Create zone records.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
identifier: Template ID
dtype: MASTER|SLAVE|NATIVE (default: MASTER)
master: master server ip address when dtype is SLAVE
(default: None)
ContentType: application/json
x-authentication-token: token
"""
method = 'PUT'
uri = 'https://' + server + '/zone'
obj = JSONConverter(domain)
obj.generate_zone(domain, identifier, dtype, master)
connect.tonicdns_client(uri, method, token, obj.zone) | python | def create_zone(server, token, domain, identifier, dtype, master=None):
"""Create zone records.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
identifier: Template ID
dtype: MASTER|SLAVE|NATIVE (default: MASTER)
master: master server ip address when dtype is SLAVE
(default: None)
ContentType: application/json
x-authentication-token: token
"""
method = 'PUT'
uri = 'https://' + server + '/zone'
obj = JSONConverter(domain)
obj.generate_zone(domain, identifier, dtype, master)
connect.tonicdns_client(uri, method, token, obj.zone) | [
"def",
"create_zone",
"(",
"server",
",",
"token",
",",
"domain",
",",
"identifier",
",",
"dtype",
",",
"master",
"=",
"None",
")",
":",
"method",
"=",
"'PUT'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone'",
"obj",
"=",
"JSONConverter",
"(",
"domain",
")",
"obj",
".",
"generate_zone",
"(",
"domain",
",",
"identifier",
",",
"dtype",
",",
"master",
")",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"obj",
".",
"zone",
")"
] | Create zone records.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
identifier: Template ID
dtype: MASTER|SLAVE|NATIVE (default: MASTER)
master: master server ip address when dtype is SLAVE
(default: None)
ContentType: application/json
x-authentication-token: token | [
"Create",
"zone",
"records",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L29-L50 |
250,255 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | create_records | def create_records(server, token, domain, data):
"""Create records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
data: Create records
ContentType: application/json
x-authentication-token: token
"""
method = 'PUT'
uri = 'https://' + server + '/zone/' + domain
for i in data:
connect.tonicdns_client(uri, method, token, i) | python | def create_records(server, token, domain, data):
"""Create records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
data: Create records
ContentType: application/json
x-authentication-token: token
"""
method = 'PUT'
uri = 'https://' + server + '/zone/' + domain
for i in data:
connect.tonicdns_client(uri, method, token, i) | [
"def",
"create_records",
"(",
"server",
",",
"token",
",",
"domain",
",",
"data",
")",
":",
"method",
"=",
"'PUT'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone/'",
"+",
"domain",
"for",
"i",
"in",
"data",
":",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"i",
")"
] | Create records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
data: Create records
ContentType: application/json
x-authentication-token: token | [
"Create",
"records",
"of",
"specific",
"domain",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L53-L69 |
250,256 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | delete_records | def delete_records(server, token, data):
"""Delete records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
data: Delete records
ContentType: application/json
x-authentication-token: token
"""
method = 'DELETE'
uri = 'https://' + server + '/zone'
for i in data:
connect.tonicdns_client(uri, method, token, i) | python | def delete_records(server, token, data):
"""Delete records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
data: Delete records
ContentType: application/json
x-authentication-token: token
"""
method = 'DELETE'
uri = 'https://' + server + '/zone'
for i in data:
connect.tonicdns_client(uri, method, token, i) | [
"def",
"delete_records",
"(",
"server",
",",
"token",
",",
"data",
")",
":",
"method",
"=",
"'DELETE'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone'",
"for",
"i",
"in",
"data",
":",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"i",
")"
] | Delete records of specific domain.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
data: Delete records
ContentType: application/json
x-authentication-token: token | [
"Delete",
"records",
"of",
"specific",
"domain",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L72-L87 |
250,257 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | get_zone | def get_zone(server, token, domain, keyword='', raw_flag=False):
"""Retrieve zone records.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
keyword: Search keyword
x-authentication-token: token
"""
method = 'GET'
uri = 'https://' + server + '/zone/' + domain
data = connect.tonicdns_client(uri, method, token, data=False,
keyword=keyword, raw_flag=raw_flag)
return data | python | def get_zone(server, token, domain, keyword='', raw_flag=False):
"""Retrieve zone records.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
keyword: Search keyword
x-authentication-token: token
"""
method = 'GET'
uri = 'https://' + server + '/zone/' + domain
data = connect.tonicdns_client(uri, method, token, data=False,
keyword=keyword, raw_flag=raw_flag)
return data | [
"def",
"get_zone",
"(",
"server",
",",
"token",
",",
"domain",
",",
"keyword",
"=",
"''",
",",
"raw_flag",
"=",
"False",
")",
":",
"method",
"=",
"'GET'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone/'",
"+",
"domain",
"data",
"=",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"data",
"=",
"False",
",",
"keyword",
"=",
"keyword",
",",
"raw_flag",
"=",
"raw_flag",
")",
"return",
"data"
] | Retrieve zone records.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
keyword: Search keyword
x-authentication-token: token | [
"Retrieve",
"zone",
"records",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L90-L106 |
250,258 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | delete_zone | def delete_zone(server, token, domain):
"""Delete specific zone.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
x-authentication-token: token
"""
method = 'DELETE'
uri = 'https://' + server + '/zone/' + domain
connect.tonicdns_client(uri, method, token, data=False) | python | def delete_zone(server, token, domain):
"""Delete specific zone.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
x-authentication-token: token
"""
method = 'DELETE'
uri = 'https://' + server + '/zone/' + domain
connect.tonicdns_client(uri, method, token, data=False) | [
"def",
"delete_zone",
"(",
"server",
",",
"token",
",",
"domain",
")",
":",
"method",
"=",
"'DELETE'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone/'",
"+",
"domain",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"data",
"=",
"False",
")"
] | Delete specific zone.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
x-authentication-token: token | [
"Delete",
"specific",
"zone",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L124-L137 |
250,259 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | create_template | def create_template(server, token, identifier, template):
"""Create template.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
identifier: Template identifier
template: Create template datas
ContentType: application/json
x-authentication-token: token
"""
method = 'PUT'
uri = 'https://' + server + '/template/' + identifier
connect.tonicdns_client(uri, method, token, data=template) | python | def create_template(server, token, identifier, template):
"""Create template.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
identifier: Template identifier
template: Create template datas
ContentType: application/json
x-authentication-token: token
"""
method = 'PUT'
uri = 'https://' + server + '/template/' + identifier
connect.tonicdns_client(uri, method, token, data=template) | [
"def",
"create_template",
"(",
"server",
",",
"token",
",",
"identifier",
",",
"template",
")",
":",
"method",
"=",
"'PUT'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/template/'",
"+",
"identifier",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"data",
"=",
"template",
")"
] | Create template.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
identifier: Template identifier
template: Create template datas
ContentType: application/json
x-authentication-token: token | [
"Create",
"template",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L140-L155 |
250,260 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | get_all_templates | def get_all_templates(server, token):
"""Retrieve all templates.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
x-authentication-token: token
"""
method = 'GET'
uri = 'https://' + server + '/template'
connect.tonicdns_client(uri, method, token, data=False) | python | def get_all_templates(server, token):
"""Retrieve all templates.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
x-authentication-token: token
"""
method = 'GET'
uri = 'https://' + server + '/template'
connect.tonicdns_client(uri, method, token, data=False) | [
"def",
"get_all_templates",
"(",
"server",
",",
"token",
")",
":",
"method",
"=",
"'GET'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/template'",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"data",
"=",
"False",
")"
] | Retrieve all templates.
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
x-authentication-token: token | [
"Retrieve",
"all",
"templates",
"."
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L190-L202 |
250,261 | mkouhei/tonicdnscli | src/tonicdnscli/processing.py | update_soa_serial | def update_soa_serial(server, token, soa_content):
"""Update SOA serial
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
soa_content: SOA record data
x-authentication-token: token
Get SOA record
`cur_soa` is current SOA record.
`new_soa` is incremental serial SOA record.
"""
method = 'GET'
uri = 'https://' + server + '/zone/' + soa_content.get('domain')
cur_soa, new_soa = connect.tonicdns_client(
uri, method, token, data=False, keyword='serial', content=soa_content)
# set JSON
domain = soa_content.get('domain')
cur_o = JSONConverter(domain)
new_o = JSONConverter(domain)
cur_o.records = [cur_soa]
new_o.records = [new_soa]
cur_o.generata_data(False)
new_o.generata_data(True)
# Create new SOA record
uri = 'https://' + server + '/zone/' + domain
method = 'PUT'
connect.tonicdns_client(uri, method, token, new_o.dict_records[0])
# Delete current SOA record why zone has only one SOA record.
method = 'DELETE'
uri = 'https://' + server + '/zone'
connect.tonicdns_client(uri, method, token, cur_o.dict_records[0]) | python | def update_soa_serial(server, token, soa_content):
"""Update SOA serial
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
soa_content: SOA record data
x-authentication-token: token
Get SOA record
`cur_soa` is current SOA record.
`new_soa` is incremental serial SOA record.
"""
method = 'GET'
uri = 'https://' + server + '/zone/' + soa_content.get('domain')
cur_soa, new_soa = connect.tonicdns_client(
uri, method, token, data=False, keyword='serial', content=soa_content)
# set JSON
domain = soa_content.get('domain')
cur_o = JSONConverter(domain)
new_o = JSONConverter(domain)
cur_o.records = [cur_soa]
new_o.records = [new_soa]
cur_o.generata_data(False)
new_o.generata_data(True)
# Create new SOA record
uri = 'https://' + server + '/zone/' + domain
method = 'PUT'
connect.tonicdns_client(uri, method, token, new_o.dict_records[0])
# Delete current SOA record why zone has only one SOA record.
method = 'DELETE'
uri = 'https://' + server + '/zone'
connect.tonicdns_client(uri, method, token, cur_o.dict_records[0]) | [
"def",
"update_soa_serial",
"(",
"server",
",",
"token",
",",
"soa_content",
")",
":",
"method",
"=",
"'GET'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone/'",
"+",
"soa_content",
".",
"get",
"(",
"'domain'",
")",
"cur_soa",
",",
"new_soa",
"=",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"data",
"=",
"False",
",",
"keyword",
"=",
"'serial'",
",",
"content",
"=",
"soa_content",
")",
"# set JSON",
"domain",
"=",
"soa_content",
".",
"get",
"(",
"'domain'",
")",
"cur_o",
"=",
"JSONConverter",
"(",
"domain",
")",
"new_o",
"=",
"JSONConverter",
"(",
"domain",
")",
"cur_o",
".",
"records",
"=",
"[",
"cur_soa",
"]",
"new_o",
".",
"records",
"=",
"[",
"new_soa",
"]",
"cur_o",
".",
"generata_data",
"(",
"False",
")",
"new_o",
".",
"generata_data",
"(",
"True",
")",
"# Create new SOA record",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone/'",
"+",
"domain",
"method",
"=",
"'PUT'",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"new_o",
".",
"dict_records",
"[",
"0",
"]",
")",
"# Delete current SOA record why zone has only one SOA record.",
"method",
"=",
"'DELETE'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone'",
"connect",
".",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
",",
"cur_o",
".",
"dict_records",
"[",
"0",
"]",
")"
] | Update SOA serial
Argument:
server: TonicDNS API server
token: TonicDNS API authentication token
soa_content: SOA record data
x-authentication-token: token
Get SOA record
`cur_soa` is current SOA record.
`new_soa` is incremental serial SOA record. | [
"Update",
"SOA",
"serial"
] | df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/processing.py#L205-L241 |
250,262 | shaypal5/utilitime | utilitime/time/time.py | decompose_seconds_in_day | def decompose_seconds_in_day(seconds):
"""Decomposes seconds in day into hour, minute and second components.
Arguments
---------
seconds : int
A time of day by the number of seconds passed since midnight.
Returns
-------
hour : int
The hour component of the given time of day.
minut : int
The minute component of the given time of day.
second : int
The second component of the given time of day.
"""
if seconds > SECONDS_IN_DAY:
seconds = seconds - SECONDS_IN_DAY
if seconds < 0:
raise ValueError("seconds param must be non-negative!")
hour = int(seconds / 3600)
leftover = seconds - hour * 3600
minute = int(leftover / 60)
second = leftover - minute * 60
return hour, minute, second | python | def decompose_seconds_in_day(seconds):
"""Decomposes seconds in day into hour, minute and second components.
Arguments
---------
seconds : int
A time of day by the number of seconds passed since midnight.
Returns
-------
hour : int
The hour component of the given time of day.
minut : int
The minute component of the given time of day.
second : int
The second component of the given time of day.
"""
if seconds > SECONDS_IN_DAY:
seconds = seconds - SECONDS_IN_DAY
if seconds < 0:
raise ValueError("seconds param must be non-negative!")
hour = int(seconds / 3600)
leftover = seconds - hour * 3600
minute = int(leftover / 60)
second = leftover - minute * 60
return hour, minute, second | [
"def",
"decompose_seconds_in_day",
"(",
"seconds",
")",
":",
"if",
"seconds",
">",
"SECONDS_IN_DAY",
":",
"seconds",
"=",
"seconds",
"-",
"SECONDS_IN_DAY",
"if",
"seconds",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"seconds param must be non-negative!\"",
")",
"hour",
"=",
"int",
"(",
"seconds",
"/",
"3600",
")",
"leftover",
"=",
"seconds",
"-",
"hour",
"*",
"3600",
"minute",
"=",
"int",
"(",
"leftover",
"/",
"60",
")",
"second",
"=",
"leftover",
"-",
"minute",
"*",
"60",
"return",
"hour",
",",
"minute",
",",
"second"
] | Decomposes seconds in day into hour, minute and second components.
Arguments
---------
seconds : int
A time of day by the number of seconds passed since midnight.
Returns
-------
hour : int
The hour component of the given time of day.
minut : int
The minute component of the given time of day.
second : int
The second component of the given time of day. | [
"Decomposes",
"seconds",
"in",
"day",
"into",
"hour",
"minute",
"and",
"second",
"components",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/time/time.py#L10-L35 |
250,263 | shaypal5/utilitime | utilitime/time/time.py | seconds_in_day_to_time | def seconds_in_day_to_time(seconds):
"""Decomposes atime of day into hour, minute and seconds components.
Arguments
---------
seconds : int
A time of day by the number of seconds passed since midnight.
Returns
-------
datetime.time
The corresponding time of day as a datetime.time object.
Example
-------
>>> seconds_in_day_to_time(23430)
datetime.time(6, 30, 30)
"""
try:
return time(*decompose_seconds_in_day(seconds))
except ValueError:
print("Seconds = {}".format(seconds))
print("H = {}, M={}, S={}".format(*decompose_seconds_in_day(seconds)))
raise | python | def seconds_in_day_to_time(seconds):
"""Decomposes atime of day into hour, minute and seconds components.
Arguments
---------
seconds : int
A time of day by the number of seconds passed since midnight.
Returns
-------
datetime.time
The corresponding time of day as a datetime.time object.
Example
-------
>>> seconds_in_day_to_time(23430)
datetime.time(6, 30, 30)
"""
try:
return time(*decompose_seconds_in_day(seconds))
except ValueError:
print("Seconds = {}".format(seconds))
print("H = {}, M={}, S={}".format(*decompose_seconds_in_day(seconds)))
raise | [
"def",
"seconds_in_day_to_time",
"(",
"seconds",
")",
":",
"try",
":",
"return",
"time",
"(",
"*",
"decompose_seconds_in_day",
"(",
"seconds",
")",
")",
"except",
"ValueError",
":",
"print",
"(",
"\"Seconds = {}\"",
".",
"format",
"(",
"seconds",
")",
")",
"print",
"(",
"\"H = {}, M={}, S={}\"",
".",
"format",
"(",
"*",
"decompose_seconds_in_day",
"(",
"seconds",
")",
")",
")",
"raise"
] | Decomposes atime of day into hour, minute and seconds components.
Arguments
---------
seconds : int
A time of day by the number of seconds passed since midnight.
Returns
-------
datetime.time
The corresponding time of day as a datetime.time object.
Example
-------
>>> seconds_in_day_to_time(23430)
datetime.time(6, 30, 30) | [
"Decomposes",
"atime",
"of",
"day",
"into",
"hour",
"minute",
"and",
"seconds",
"components",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/time/time.py#L38-L61 |
250,264 | tjomasc/snekbol | snekbol/identified.py | Identified._as_rdf_xml | def _as_rdf_xml(self, ns):
"""
Return identity details for the element as XML nodes
"""
self.rdf_identity = self._get_identity(ns)
elements = []
elements.append(ET.Element(NS('sbol', 'persistentIdentity'),
attrib={NS('rdf', 'resource'):
self._get_persistent_identitity(ns)}))
if self.name is not None:
name = ET.Element(NS('dcterms', 'title'))
name.text = self.name
elements.append(name)
if self.display_id is not None:
display_id = ET.Element(NS('sbol', 'displayId'))
display_id.text = self.display_id
elements.append(display_id)
if self.version is not None:
version = ET.Element(NS('sbol', 'version'))
version.text = self.version
elements.append(version)
if self.was_derived_from is not None:
elements.append(ET.Element(NS('prov', 'wasDerivedFrom'),
attrib={NS('rdf', 'resource'): self.was_derived_from}))
if self.description is not None:
description = ET.Element(NS('dcterms', 'description'))
description.text = self.description
elements.append(description)
for a in self.annotations:
elements.append(a._as_rdf_xml(ns))
return elements | python | def _as_rdf_xml(self, ns):
"""
Return identity details for the element as XML nodes
"""
self.rdf_identity = self._get_identity(ns)
elements = []
elements.append(ET.Element(NS('sbol', 'persistentIdentity'),
attrib={NS('rdf', 'resource'):
self._get_persistent_identitity(ns)}))
if self.name is not None:
name = ET.Element(NS('dcterms', 'title'))
name.text = self.name
elements.append(name)
if self.display_id is not None:
display_id = ET.Element(NS('sbol', 'displayId'))
display_id.text = self.display_id
elements.append(display_id)
if self.version is not None:
version = ET.Element(NS('sbol', 'version'))
version.text = self.version
elements.append(version)
if self.was_derived_from is not None:
elements.append(ET.Element(NS('prov', 'wasDerivedFrom'),
attrib={NS('rdf', 'resource'): self.was_derived_from}))
if self.description is not None:
description = ET.Element(NS('dcterms', 'description'))
description.text = self.description
elements.append(description)
for a in self.annotations:
elements.append(a._as_rdf_xml(ns))
return elements | [
"def",
"_as_rdf_xml",
"(",
"self",
",",
"ns",
")",
":",
"self",
".",
"rdf_identity",
"=",
"self",
".",
"_get_identity",
"(",
"ns",
")",
"elements",
"=",
"[",
"]",
"elements",
".",
"append",
"(",
"ET",
".",
"Element",
"(",
"NS",
"(",
"'sbol'",
",",
"'persistentIdentity'",
")",
",",
"attrib",
"=",
"{",
"NS",
"(",
"'rdf'",
",",
"'resource'",
")",
":",
"self",
".",
"_get_persistent_identitity",
"(",
"ns",
")",
"}",
")",
")",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"name",
"=",
"ET",
".",
"Element",
"(",
"NS",
"(",
"'dcterms'",
",",
"'title'",
")",
")",
"name",
".",
"text",
"=",
"self",
".",
"name",
"elements",
".",
"append",
"(",
"name",
")",
"if",
"self",
".",
"display_id",
"is",
"not",
"None",
":",
"display_id",
"=",
"ET",
".",
"Element",
"(",
"NS",
"(",
"'sbol'",
",",
"'displayId'",
")",
")",
"display_id",
".",
"text",
"=",
"self",
".",
"display_id",
"elements",
".",
"append",
"(",
"display_id",
")",
"if",
"self",
".",
"version",
"is",
"not",
"None",
":",
"version",
"=",
"ET",
".",
"Element",
"(",
"NS",
"(",
"'sbol'",
",",
"'version'",
")",
")",
"version",
".",
"text",
"=",
"self",
".",
"version",
"elements",
".",
"append",
"(",
"version",
")",
"if",
"self",
".",
"was_derived_from",
"is",
"not",
"None",
":",
"elements",
".",
"append",
"(",
"ET",
".",
"Element",
"(",
"NS",
"(",
"'prov'",
",",
"'wasDerivedFrom'",
")",
",",
"attrib",
"=",
"{",
"NS",
"(",
"'rdf'",
",",
"'resource'",
")",
":",
"self",
".",
"was_derived_from",
"}",
")",
")",
"if",
"self",
".",
"description",
"is",
"not",
"None",
":",
"description",
"=",
"ET",
".",
"Element",
"(",
"NS",
"(",
"'dcterms'",
",",
"'description'",
")",
")",
"description",
".",
"text",
"=",
"self",
".",
"description",
"elements",
".",
"append",
"(",
"description",
")",
"for",
"a",
"in",
"self",
".",
"annotations",
":",
"elements",
".",
"append",
"(",
"a",
".",
"_as_rdf_xml",
"(",
"ns",
")",
")",
"return",
"elements"
] | Return identity details for the element as XML nodes | [
"Return",
"identity",
"details",
"for",
"the",
"element",
"as",
"XML",
"nodes"
] | 0b491aa96e0b1bd09e6c80cfb43807dd8a876c83 | https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/identified.py#L68-L98 |
250,265 | steder/pundler | pundler/core.py | get_requirement_files | def get_requirement_files(args=None):
"""
Get the "best" requirements file we can find
"""
if args and args.input_filename:
return [args.input_filename]
paths = []
for regex in settings.REQUIREMENTS_SOURCE_GLOBS:
paths.extend(glob.glob(regex))
return paths | python | def get_requirement_files(args=None):
"""
Get the "best" requirements file we can find
"""
if args and args.input_filename:
return [args.input_filename]
paths = []
for regex in settings.REQUIREMENTS_SOURCE_GLOBS:
paths.extend(glob.glob(regex))
return paths | [
"def",
"get_requirement_files",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"and",
"args",
".",
"input_filename",
":",
"return",
"[",
"args",
".",
"input_filename",
"]",
"paths",
"=",
"[",
"]",
"for",
"regex",
"in",
"settings",
".",
"REQUIREMENTS_SOURCE_GLOBS",
":",
"paths",
".",
"extend",
"(",
"glob",
".",
"glob",
"(",
"regex",
")",
")",
"return",
"paths"
] | Get the "best" requirements file we can find | [
"Get",
"the",
"best",
"requirements",
"file",
"we",
"can",
"find"
] | 68d730b08e46d5f7b8781017c9bba87c7378509d | https://github.com/steder/pundler/blob/68d730b08e46d5f7b8781017c9bba87c7378509d/pundler/core.py#L34-L44 |
250,266 | dariosky/wfcli | wfcli/wfapi.py | WebFactionAPI.list_domains | def list_domains(self):
""" Return all domains. Domain is a key, so group by them """
self.connect()
results = self.server.list_domains(self.session_id)
return {i['domain']: i['subdomains'] for i in results} | python | def list_domains(self):
""" Return all domains. Domain is a key, so group by them """
self.connect()
results = self.server.list_domains(self.session_id)
return {i['domain']: i['subdomains'] for i in results} | [
"def",
"list_domains",
"(",
"self",
")",
":",
"self",
".",
"connect",
"(",
")",
"results",
"=",
"self",
".",
"server",
".",
"list_domains",
"(",
"self",
".",
"session_id",
")",
"return",
"{",
"i",
"[",
"'domain'",
"]",
":",
"i",
"[",
"'subdomains'",
"]",
"for",
"i",
"in",
"results",
"}"
] | Return all domains. Domain is a key, so group by them | [
"Return",
"all",
"domains",
".",
"Domain",
"is",
"a",
"key",
"so",
"group",
"by",
"them"
] | 87a9ed30dbd456f801135a55099f0541b0614ccb | https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/wfapi.py#L67-L71 |
250,267 | dariosky/wfcli | wfcli/wfapi.py | WebFactionAPI.list_websites | def list_websites(self):
""" Return all websites, name is not a key """
self.connect()
results = self.server.list_websites(self.session_id)
return results | python | def list_websites(self):
""" Return all websites, name is not a key """
self.connect()
results = self.server.list_websites(self.session_id)
return results | [
"def",
"list_websites",
"(",
"self",
")",
":",
"self",
".",
"connect",
"(",
")",
"results",
"=",
"self",
".",
"server",
".",
"list_websites",
"(",
"self",
".",
"session_id",
")",
"return",
"results"
] | Return all websites, name is not a key | [
"Return",
"all",
"websites",
"name",
"is",
"not",
"a",
"key"
] | 87a9ed30dbd456f801135a55099f0541b0614ccb | https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/wfapi.py#L73-L78 |
250,268 | dariosky/wfcli | wfcli/wfapi.py | WebFactionAPI.website_exists | def website_exists(self, website, websites=None):
""" Look for websites matching the one passed """
if websites is None:
websites = self.list_websites()
if isinstance(website, str):
website = {"name": website}
ignored_fields = ('id',) # changes in these fields are ignored
results = []
for other in websites:
different = False
for key in website:
if key in ignored_fields:
continue
if other.get(key) != website.get(key):
different = True
break
if different is False:
results.append(other)
return results | python | def website_exists(self, website, websites=None):
""" Look for websites matching the one passed """
if websites is None:
websites = self.list_websites()
if isinstance(website, str):
website = {"name": website}
ignored_fields = ('id',) # changes in these fields are ignored
results = []
for other in websites:
different = False
for key in website:
if key in ignored_fields:
continue
if other.get(key) != website.get(key):
different = True
break
if different is False:
results.append(other)
return results | [
"def",
"website_exists",
"(",
"self",
",",
"website",
",",
"websites",
"=",
"None",
")",
":",
"if",
"websites",
"is",
"None",
":",
"websites",
"=",
"self",
".",
"list_websites",
"(",
")",
"if",
"isinstance",
"(",
"website",
",",
"str",
")",
":",
"website",
"=",
"{",
"\"name\"",
":",
"website",
"}",
"ignored_fields",
"=",
"(",
"'id'",
",",
")",
"# changes in these fields are ignored",
"results",
"=",
"[",
"]",
"for",
"other",
"in",
"websites",
":",
"different",
"=",
"False",
"for",
"key",
"in",
"website",
":",
"if",
"key",
"in",
"ignored_fields",
":",
"continue",
"if",
"other",
".",
"get",
"(",
"key",
")",
"!=",
"website",
".",
"get",
"(",
"key",
")",
":",
"different",
"=",
"True",
"break",
"if",
"different",
"is",
"False",
":",
"results",
".",
"append",
"(",
"other",
")",
"return",
"results"
] | Look for websites matching the one passed | [
"Look",
"for",
"websites",
"matching",
"the",
"one",
"passed"
] | 87a9ed30dbd456f801135a55099f0541b0614ccb | https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/wfapi.py#L136-L155 |
250,269 | Adman/pynameday | pynameday/core.py | NamedayMixin.get_month_namedays | def get_month_namedays(self, month=None):
"""Return names as a tuple based on given month.
If no month given, use current one"""
if month is None:
month = datetime.now().month
return self.NAMEDAYS[month-1] | python | def get_month_namedays(self, month=None):
"""Return names as a tuple based on given month.
If no month given, use current one"""
if month is None:
month = datetime.now().month
return self.NAMEDAYS[month-1] | [
"def",
"get_month_namedays",
"(",
"self",
",",
"month",
"=",
"None",
")",
":",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"month",
"return",
"self",
".",
"NAMEDAYS",
"[",
"month",
"-",
"1",
"]"
] | Return names as a tuple based on given month.
If no month given, use current one | [
"Return",
"names",
"as",
"a",
"tuple",
"based",
"on",
"given",
"month",
".",
"If",
"no",
"month",
"given",
"use",
"current",
"one"
] | a3153db3e26531dec54510705aac4ae077cf9316 | https://github.com/Adman/pynameday/blob/a3153db3e26531dec54510705aac4ae077cf9316/pynameday/core.py#L16-L21 |
250,270 | emencia/emencia-django-forum | forum/mixins.py | ModeratorCheckMixin.has_moderator_permissions | def has_moderator_permissions(self, request):
"""
Find if user have global or per object permission firstly on category instance,
if not then on thread instance
"""
return any(request.user.has_perm(perm) for perm in self.permission_required) | python | def has_moderator_permissions(self, request):
"""
Find if user have global or per object permission firstly on category instance,
if not then on thread instance
"""
return any(request.user.has_perm(perm) for perm in self.permission_required) | [
"def",
"has_moderator_permissions",
"(",
"self",
",",
"request",
")",
":",
"return",
"any",
"(",
"request",
".",
"user",
".",
"has_perm",
"(",
"perm",
")",
"for",
"perm",
"in",
"self",
".",
"permission_required",
")"
] | Find if user have global or per object permission firstly on category instance,
if not then on thread instance | [
"Find",
"if",
"user",
"have",
"global",
"or",
"per",
"object",
"permission",
"firstly",
"on",
"category",
"instance",
"if",
"not",
"then",
"on",
"thread",
"instance"
] | cda74ed7e5822675c340ee5ec71548d981bccd3b | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/mixins.py#L35-L40 |
250,271 | rochacbruno/shiftpy | shiftpy/env.py | getvar | def getvar(key, default=None, template='OPENSHIFT_{key}'):
"""
Get OPENSHIFT envvar
"""
return os.environ.get(template.format(key=key), default) | python | def getvar(key, default=None, template='OPENSHIFT_{key}'):
"""
Get OPENSHIFT envvar
"""
return os.environ.get(template.format(key=key), default) | [
"def",
"getvar",
"(",
"key",
",",
"default",
"=",
"None",
",",
"template",
"=",
"'OPENSHIFT_{key}'",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"template",
".",
"format",
"(",
"key",
"=",
"key",
")",
",",
"default",
")"
] | Get OPENSHIFT envvar | [
"Get",
"OPENSHIFT",
"envvar"
] | 6bffccf511f24b7e53dcfee9807e0e3388aa823a | https://github.com/rochacbruno/shiftpy/blob/6bffccf511f24b7e53dcfee9807e0e3388aa823a/shiftpy/env.py#L6-L10 |
250,272 | treycucco/bidon | bidon/json_patch.py | add | def add(parent, idx, value):
"""Add a value to a dict."""
if isinstance(parent, dict):
if idx in parent:
raise JSONPatchError("Item already exists")
parent[idx] = value
elif isinstance(parent, list):
if idx == "" or idx == "~":
parent.append(value)
else:
parent.insert(int(idx), value)
else:
raise JSONPathError("Invalid path for operation") | python | def add(parent, idx, value):
"""Add a value to a dict."""
if isinstance(parent, dict):
if idx in parent:
raise JSONPatchError("Item already exists")
parent[idx] = value
elif isinstance(parent, list):
if idx == "" or idx == "~":
parent.append(value)
else:
parent.insert(int(idx), value)
else:
raise JSONPathError("Invalid path for operation") | [
"def",
"add",
"(",
"parent",
",",
"idx",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"parent",
",",
"dict",
")",
":",
"if",
"idx",
"in",
"parent",
":",
"raise",
"JSONPatchError",
"(",
"\"Item already exists\"",
")",
"parent",
"[",
"idx",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"parent",
",",
"list",
")",
":",
"if",
"idx",
"==",
"\"\"",
"or",
"idx",
"==",
"\"~\"",
":",
"parent",
".",
"append",
"(",
"value",
")",
"else",
":",
"parent",
".",
"insert",
"(",
"int",
"(",
"idx",
")",
",",
"value",
")",
"else",
":",
"raise",
"JSONPathError",
"(",
"\"Invalid path for operation\"",
")"
] | Add a value to a dict. | [
"Add",
"a",
"value",
"to",
"a",
"dict",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L62-L74 |
250,273 | treycucco/bidon | bidon/json_patch.py | remove | def remove(parent, idx):
"""Remove a value from a dict."""
if isinstance(parent, dict):
del parent[idx]
elif isinstance(parent, list):
del parent[int(idx)]
else:
raise JSONPathError("Invalid path for operation") | python | def remove(parent, idx):
"""Remove a value from a dict."""
if isinstance(parent, dict):
del parent[idx]
elif isinstance(parent, list):
del parent[int(idx)]
else:
raise JSONPathError("Invalid path for operation") | [
"def",
"remove",
"(",
"parent",
",",
"idx",
")",
":",
"if",
"isinstance",
"(",
"parent",
",",
"dict",
")",
":",
"del",
"parent",
"[",
"idx",
"]",
"elif",
"isinstance",
"(",
"parent",
",",
"list",
")",
":",
"del",
"parent",
"[",
"int",
"(",
"idx",
")",
"]",
"else",
":",
"raise",
"JSONPathError",
"(",
"\"Invalid path for operation\"",
")"
] | Remove a value from a dict. | [
"Remove",
"a",
"value",
"from",
"a",
"dict",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L77-L84 |
250,274 | treycucco/bidon | bidon/json_patch.py | replace | def replace(parent, idx, value, check_value=_NO_VAL):
"""Replace a value in a dict."""
if isinstance(parent, dict):
if idx not in parent:
raise JSONPatchError("Item does not exist")
elif isinstance(parent, list):
idx = int(idx)
if idx < 0 or idx >= len(parent):
raise JSONPatchError("List index out of range")
if check_value is not _NO_VAL:
if parent[idx] != check_value:
raise JSONPatchError("Check value did not pass")
parent[idx] = value | python | def replace(parent, idx, value, check_value=_NO_VAL):
"""Replace a value in a dict."""
if isinstance(parent, dict):
if idx not in parent:
raise JSONPatchError("Item does not exist")
elif isinstance(parent, list):
idx = int(idx)
if idx < 0 or idx >= len(parent):
raise JSONPatchError("List index out of range")
if check_value is not _NO_VAL:
if parent[idx] != check_value:
raise JSONPatchError("Check value did not pass")
parent[idx] = value | [
"def",
"replace",
"(",
"parent",
",",
"idx",
",",
"value",
",",
"check_value",
"=",
"_NO_VAL",
")",
":",
"if",
"isinstance",
"(",
"parent",
",",
"dict",
")",
":",
"if",
"idx",
"not",
"in",
"parent",
":",
"raise",
"JSONPatchError",
"(",
"\"Item does not exist\"",
")",
"elif",
"isinstance",
"(",
"parent",
",",
"list",
")",
":",
"idx",
"=",
"int",
"(",
"idx",
")",
"if",
"idx",
"<",
"0",
"or",
"idx",
">=",
"len",
"(",
"parent",
")",
":",
"raise",
"JSONPatchError",
"(",
"\"List index out of range\"",
")",
"if",
"check_value",
"is",
"not",
"_NO_VAL",
":",
"if",
"parent",
"[",
"idx",
"]",
"!=",
"check_value",
":",
"raise",
"JSONPatchError",
"(",
"\"Check value did not pass\"",
")",
"parent",
"[",
"idx",
"]",
"=",
"value"
] | Replace a value in a dict. | [
"Replace",
"a",
"value",
"in",
"a",
"dict",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L87-L99 |
250,275 | treycucco/bidon | bidon/json_patch.py | merge | def merge(parent, idx, value):
"""Merge a value."""
target = get_child(parent, idx)
for key, val in value.items():
target[key] = val | python | def merge(parent, idx, value):
"""Merge a value."""
target = get_child(parent, idx)
for key, val in value.items():
target[key] = val | [
"def",
"merge",
"(",
"parent",
",",
"idx",
",",
"value",
")",
":",
"target",
"=",
"get_child",
"(",
"parent",
",",
"idx",
")",
"for",
"key",
",",
"val",
"in",
"value",
".",
"items",
"(",
")",
":",
"target",
"[",
"key",
"]",
"=",
"val"
] | Merge a value. | [
"Merge",
"a",
"value",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L102-L106 |
250,276 | treycucco/bidon | bidon/json_patch.py | copy | def copy(src_parent, src_idx, dest_parent, dest_idx):
"""Copy an item."""
if isinstance(dest_parent, list):
dest_idx = int(dest_idx)
dest_parent[dest_idx] = get_child(src_parent, src_idx) | python | def copy(src_parent, src_idx, dest_parent, dest_idx):
"""Copy an item."""
if isinstance(dest_parent, list):
dest_idx = int(dest_idx)
dest_parent[dest_idx] = get_child(src_parent, src_idx) | [
"def",
"copy",
"(",
"src_parent",
",",
"src_idx",
",",
"dest_parent",
",",
"dest_idx",
")",
":",
"if",
"isinstance",
"(",
"dest_parent",
",",
"list",
")",
":",
"dest_idx",
"=",
"int",
"(",
"dest_idx",
")",
"dest_parent",
"[",
"dest_idx",
"]",
"=",
"get_child",
"(",
"src_parent",
",",
"src_idx",
")"
] | Copy an item. | [
"Copy",
"an",
"item",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L109-L113 |
250,277 | treycucco/bidon | bidon/json_patch.py | move | def move(src_parent, src_idx, dest_parent, dest_idx):
"""Move an item."""
copy(src_parent, src_idx, dest_parent, dest_idx)
remove(src_parent, src_idx) | python | def move(src_parent, src_idx, dest_parent, dest_idx):
"""Move an item."""
copy(src_parent, src_idx, dest_parent, dest_idx)
remove(src_parent, src_idx) | [
"def",
"move",
"(",
"src_parent",
",",
"src_idx",
",",
"dest_parent",
",",
"dest_idx",
")",
":",
"copy",
"(",
"src_parent",
",",
"src_idx",
",",
"dest_parent",
",",
"dest_idx",
")",
"remove",
"(",
"src_parent",
",",
"src_idx",
")"
] | Move an item. | [
"Move",
"an",
"item",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L116-L119 |
250,278 | treycucco/bidon | bidon/json_patch.py | set_remove | def set_remove(parent, idx, value):
"""Remove an item from a list."""
lst = get_child(parent, idx)
if value in lst:
lst.remove(value) | python | def set_remove(parent, idx, value):
"""Remove an item from a list."""
lst = get_child(parent, idx)
if value in lst:
lst.remove(value) | [
"def",
"set_remove",
"(",
"parent",
",",
"idx",
",",
"value",
")",
":",
"lst",
"=",
"get_child",
"(",
"parent",
",",
"idx",
")",
"if",
"value",
"in",
"lst",
":",
"lst",
".",
"remove",
"(",
"value",
")"
] | Remove an item from a list. | [
"Remove",
"an",
"item",
"from",
"a",
"list",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L134-L138 |
250,279 | treycucco/bidon | bidon/json_patch.py | set_add | def set_add(parent, idx, value):
"""Add an item to a list if it doesn't exist."""
lst = get_child(parent, idx)
if value not in lst:
lst.append(value) | python | def set_add(parent, idx, value):
"""Add an item to a list if it doesn't exist."""
lst = get_child(parent, idx)
if value not in lst:
lst.append(value) | [
"def",
"set_add",
"(",
"parent",
",",
"idx",
",",
"value",
")",
":",
"lst",
"=",
"get_child",
"(",
"parent",
",",
"idx",
")",
"if",
"value",
"not",
"in",
"lst",
":",
"lst",
".",
"append",
"(",
"value",
")"
] | Add an item to a list if it doesn't exist. | [
"Add",
"an",
"item",
"to",
"a",
"list",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L141-L145 |
250,280 | treycucco/bidon | bidon/json_patch.py | parse_path | def parse_path(path):
"""Parse a rfc 6901 path."""
if not path:
raise ValueError("Invalid path")
if isinstance(path, str):
if path == "/":
raise ValueError("Invalid path")
if path[0] != "/":
raise ValueError("Invalid path")
return path.split(_PATH_SEP)[1:]
elif isinstance(path, (tuple, list)):
return path
else:
raise ValueError("A path must be a string, tuple or list") | python | def parse_path(path):
"""Parse a rfc 6901 path."""
if not path:
raise ValueError("Invalid path")
if isinstance(path, str):
if path == "/":
raise ValueError("Invalid path")
if path[0] != "/":
raise ValueError("Invalid path")
return path.split(_PATH_SEP)[1:]
elif isinstance(path, (tuple, list)):
return path
else:
raise ValueError("A path must be a string, tuple or list") | [
"def",
"parse_path",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"Invalid path\"",
")",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"if",
"path",
"==",
"\"/\"",
":",
"raise",
"ValueError",
"(",
"\"Invalid path\"",
")",
"if",
"path",
"[",
"0",
"]",
"!=",
"\"/\"",
":",
"raise",
"ValueError",
"(",
"\"Invalid path\"",
")",
"return",
"path",
".",
"split",
"(",
"_PATH_SEP",
")",
"[",
"1",
":",
"]",
"elif",
"isinstance",
"(",
"path",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"path",
"else",
":",
"raise",
"ValueError",
"(",
"\"A path must be a string, tuple or list\"",
")"
] | Parse a rfc 6901 path. | [
"Parse",
"a",
"rfc",
"6901",
"path",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L176-L190 |
250,281 | treycucco/bidon | bidon/json_patch.py | resolve_path | def resolve_path(root, path):
"""Resolve a rfc 6901 path, returning the parent and the last path part."""
path = parse_path(path)
parent = root
for part in path[:-1]:
parent = get_child(parent, rfc_6901_replace(part))
return (parent, rfc_6901_replace(path[-1])) | python | def resolve_path(root, path):
"""Resolve a rfc 6901 path, returning the parent and the last path part."""
path = parse_path(path)
parent = root
for part in path[:-1]:
parent = get_child(parent, rfc_6901_replace(part))
return (parent, rfc_6901_replace(path[-1])) | [
"def",
"resolve_path",
"(",
"root",
",",
"path",
")",
":",
"path",
"=",
"parse_path",
"(",
"path",
")",
"parent",
"=",
"root",
"for",
"part",
"in",
"path",
"[",
":",
"-",
"1",
"]",
":",
"parent",
"=",
"get_child",
"(",
"parent",
",",
"rfc_6901_replace",
"(",
"part",
")",
")",
"return",
"(",
"parent",
",",
"rfc_6901_replace",
"(",
"path",
"[",
"-",
"1",
"]",
")",
")"
] | Resolve a rfc 6901 path, returning the parent and the last path part. | [
"Resolve",
"a",
"rfc",
"6901",
"path",
"returning",
"the",
"parent",
"and",
"the",
"last",
"path",
"part",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L193-L202 |
250,282 | treycucco/bidon | bidon/json_patch.py | find_all | def find_all(root, path):
"""Get all children that satisfy the path."""
path = parse_path(path)
if len(path) == 1:
yield from get_children(root, path[0])
else:
for child in get_children(root, path[0]):
yield from find_all(child, path[1:]) | python | def find_all(root, path):
"""Get all children that satisfy the path."""
path = parse_path(path)
if len(path) == 1:
yield from get_children(root, path[0])
else:
for child in get_children(root, path[0]):
yield from find_all(child, path[1:]) | [
"def",
"find_all",
"(",
"root",
",",
"path",
")",
":",
"path",
"=",
"parse_path",
"(",
"path",
")",
"if",
"len",
"(",
"path",
")",
"==",
"1",
":",
"yield",
"from",
"get_children",
"(",
"root",
",",
"path",
"[",
"0",
"]",
")",
"else",
":",
"for",
"child",
"in",
"get_children",
"(",
"root",
",",
"path",
"[",
"0",
"]",
")",
":",
"yield",
"from",
"find_all",
"(",
"child",
",",
"path",
"[",
"1",
":",
"]",
")"
] | Get all children that satisfy the path. | [
"Get",
"all",
"children",
"that",
"satisfy",
"the",
"path",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L210-L218 |
250,283 | treycucco/bidon | bidon/json_patch.py | apply_patch | def apply_patch(document, patch):
"""Apply a Patch object to a document."""
# pylint: disable=too-many-return-statements
op = patch.op
parent, idx = resolve_path(document, patch.path)
if op == "add":
return add(parent, idx, patch.value)
elif op == "remove":
return remove(parent, idx)
elif op == "replace":
return replace(parent, idx, patch.value, patch.src)
elif op == "merge":
return merge(parent, idx, patch.value)
elif op == "copy":
sparent, sidx = resolve_path(document, patch.src)
return copy(sparent, sidx, parent, idx)
elif op == "move":
sparent, sidx = resolve_path(document, patch.src)
return move(sparent, sidx, parent, idx)
elif op == "test":
return test(parent, idx, patch.value)
elif op == "setremove":
return set_remove(parent, idx, patch.value)
elif op == "setadd":
return set_add(parent, idx, patch.value)
else:
raise JSONPatchError("Invalid operator") | python | def apply_patch(document, patch):
"""Apply a Patch object to a document."""
# pylint: disable=too-many-return-statements
op = patch.op
parent, idx = resolve_path(document, patch.path)
if op == "add":
return add(parent, idx, patch.value)
elif op == "remove":
return remove(parent, idx)
elif op == "replace":
return replace(parent, idx, patch.value, patch.src)
elif op == "merge":
return merge(parent, idx, patch.value)
elif op == "copy":
sparent, sidx = resolve_path(document, patch.src)
return copy(sparent, sidx, parent, idx)
elif op == "move":
sparent, sidx = resolve_path(document, patch.src)
return move(sparent, sidx, parent, idx)
elif op == "test":
return test(parent, idx, patch.value)
elif op == "setremove":
return set_remove(parent, idx, patch.value)
elif op == "setadd":
return set_add(parent, idx, patch.value)
else:
raise JSONPatchError("Invalid operator") | [
"def",
"apply_patch",
"(",
"document",
",",
"patch",
")",
":",
"# pylint: disable=too-many-return-statements",
"op",
"=",
"patch",
".",
"op",
"parent",
",",
"idx",
"=",
"resolve_path",
"(",
"document",
",",
"patch",
".",
"path",
")",
"if",
"op",
"==",
"\"add\"",
":",
"return",
"add",
"(",
"parent",
",",
"idx",
",",
"patch",
".",
"value",
")",
"elif",
"op",
"==",
"\"remove\"",
":",
"return",
"remove",
"(",
"parent",
",",
"idx",
")",
"elif",
"op",
"==",
"\"replace\"",
":",
"return",
"replace",
"(",
"parent",
",",
"idx",
",",
"patch",
".",
"value",
",",
"patch",
".",
"src",
")",
"elif",
"op",
"==",
"\"merge\"",
":",
"return",
"merge",
"(",
"parent",
",",
"idx",
",",
"patch",
".",
"value",
")",
"elif",
"op",
"==",
"\"copy\"",
":",
"sparent",
",",
"sidx",
"=",
"resolve_path",
"(",
"document",
",",
"patch",
".",
"src",
")",
"return",
"copy",
"(",
"sparent",
",",
"sidx",
",",
"parent",
",",
"idx",
")",
"elif",
"op",
"==",
"\"move\"",
":",
"sparent",
",",
"sidx",
"=",
"resolve_path",
"(",
"document",
",",
"patch",
".",
"src",
")",
"return",
"move",
"(",
"sparent",
",",
"sidx",
",",
"parent",
",",
"idx",
")",
"elif",
"op",
"==",
"\"test\"",
":",
"return",
"test",
"(",
"parent",
",",
"idx",
",",
"patch",
".",
"value",
")",
"elif",
"op",
"==",
"\"setremove\"",
":",
"return",
"set_remove",
"(",
"parent",
",",
"idx",
",",
"patch",
".",
"value",
")",
"elif",
"op",
"==",
"\"setadd\"",
":",
"return",
"set_add",
"(",
"parent",
",",
"idx",
",",
"patch",
".",
"value",
")",
"else",
":",
"raise",
"JSONPatchError",
"(",
"\"Invalid operator\"",
")"
] | Apply a Patch object to a document. | [
"Apply",
"a",
"Patch",
"object",
"to",
"a",
"document",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L226-L252 |
250,284 | treycucco/bidon | bidon/json_patch.py | apply_patches | def apply_patches(document, patches):
"""Serially apply all patches to a document."""
for i, patch in enumerate(patches):
try:
result = apply_patch(document, patch)
if patch.op == "test" and result is False:
raise JSONPatchError("Test patch {0} failed. Cancelling entire set.".format(i + 1))
except Exception as ex:
raise JSONPatchError("An error occurred with patch {0}: {1}".format(i + 1, ex)) from ex | python | def apply_patches(document, patches):
"""Serially apply all patches to a document."""
for i, patch in enumerate(patches):
try:
result = apply_patch(document, patch)
if patch.op == "test" and result is False:
raise JSONPatchError("Test patch {0} failed. Cancelling entire set.".format(i + 1))
except Exception as ex:
raise JSONPatchError("An error occurred with patch {0}: {1}".format(i + 1, ex)) from ex | [
"def",
"apply_patches",
"(",
"document",
",",
"patches",
")",
":",
"for",
"i",
",",
"patch",
"in",
"enumerate",
"(",
"patches",
")",
":",
"try",
":",
"result",
"=",
"apply_patch",
"(",
"document",
",",
"patch",
")",
"if",
"patch",
".",
"op",
"==",
"\"test\"",
"and",
"result",
"is",
"False",
":",
"raise",
"JSONPatchError",
"(",
"\"Test patch {0} failed. Cancelling entire set.\"",
".",
"format",
"(",
"i",
"+",
"1",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"JSONPatchError",
"(",
"\"An error occurred with patch {0}: {1}\"",
".",
"format",
"(",
"i",
"+",
"1",
",",
"ex",
")",
")",
"from",
"ex"
] | Serially apply all patches to a document. | [
"Serially",
"apply",
"all",
"patches",
"to",
"a",
"document",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/json_patch.py#L255-L263 |
250,285 | xtrementl/focus | focus/plugin/modules/timer.py | Timer.execute | def execute(self, env, args):
""" Displays task time left in minutes.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
msg = u'Time Left: {0}m' if not args.short else '{0}'
mins = max(0, self.total_duration - env.task.duration)
env.io.write(msg.format(mins)) | python | def execute(self, env, args):
""" Displays task time left in minutes.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
msg = u'Time Left: {0}m' if not args.short else '{0}'
mins = max(0, self.total_duration - env.task.duration)
env.io.write(msg.format(mins)) | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"msg",
"=",
"u'Time Left: {0}m'",
"if",
"not",
"args",
".",
"short",
"else",
"'{0}'",
"mins",
"=",
"max",
"(",
"0",
",",
"self",
".",
"total_duration",
"-",
"env",
".",
"task",
".",
"duration",
")",
"env",
".",
"io",
".",
"write",
"(",
"msg",
".",
"format",
"(",
"mins",
")",
")"
] | Displays task time left in minutes.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. | [
"Displays",
"task",
"time",
"left",
"in",
"minutes",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/timer.py#L42-L53 |
250,286 | xtrementl/focus | focus/plugin/modules/timer.py | Timer.parse_option | def parse_option(self, option, block_name, *values):
""" Parse duration option for timer.
"""
try:
if len(values) != 1:
raise TypeError
self.total_duration = int(values[0])
if self.total_duration <= 0:
raise ValueError
except ValueError:
pattern = u'"{0}" must be an integer > 0'
raise ValueError(pattern.format(option)) | python | def parse_option(self, option, block_name, *values):
""" Parse duration option for timer.
"""
try:
if len(values) != 1:
raise TypeError
self.total_duration = int(values[0])
if self.total_duration <= 0:
raise ValueError
except ValueError:
pattern = u'"{0}" must be an integer > 0'
raise ValueError(pattern.format(option)) | [
"def",
"parse_option",
"(",
"self",
",",
"option",
",",
"block_name",
",",
"*",
"values",
")",
":",
"try",
":",
"if",
"len",
"(",
"values",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"self",
".",
"total_duration",
"=",
"int",
"(",
"values",
"[",
"0",
"]",
")",
"if",
"self",
".",
"total_duration",
"<=",
"0",
":",
"raise",
"ValueError",
"except",
"ValueError",
":",
"pattern",
"=",
"u'\"{0}\" must be an integer > 0'",
"raise",
"ValueError",
"(",
"pattern",
".",
"format",
"(",
"option",
")",
")"
] | Parse duration option for timer. | [
"Parse",
"duration",
"option",
"for",
"timer",
"."
] | cbbbc0b49a7409f9e0dc899de5b7e057f50838e4 | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/timer.py#L55-L69 |
250,287 | samirelanduk/quickplots | quickplots/series.py | Series.add_data_point | def add_data_point(self, x, y):
"""Adds a data point to the series.
:param x: The numerical x value to be added.
:param y: The numerical y value to be added."""
if not is_numeric(x):
raise TypeError("x value must be numeric, not '%s'" % str(x))
if not is_numeric(y):
raise TypeError("y value must be numeric, not '%s'" % str(y))
current_last_x = self._data[-1][0]
self._data.append((x, y))
if x < current_last_x:
self._data = sorted(self._data, key=lambda k: k[0]) | python | def add_data_point(self, x, y):
"""Adds a data point to the series.
:param x: The numerical x value to be added.
:param y: The numerical y value to be added."""
if not is_numeric(x):
raise TypeError("x value must be numeric, not '%s'" % str(x))
if not is_numeric(y):
raise TypeError("y value must be numeric, not '%s'" % str(y))
current_last_x = self._data[-1][0]
self._data.append((x, y))
if x < current_last_x:
self._data = sorted(self._data, key=lambda k: k[0]) | [
"def",
"add_data_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"not",
"is_numeric",
"(",
"x",
")",
":",
"raise",
"TypeError",
"(",
"\"x value must be numeric, not '%s'\"",
"%",
"str",
"(",
"x",
")",
")",
"if",
"not",
"is_numeric",
"(",
"y",
")",
":",
"raise",
"TypeError",
"(",
"\"y value must be numeric, not '%s'\"",
"%",
"str",
"(",
"y",
")",
")",
"current_last_x",
"=",
"self",
".",
"_data",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"self",
".",
"_data",
".",
"append",
"(",
"(",
"x",
",",
"y",
")",
")",
"if",
"x",
"<",
"current_last_x",
":",
"self",
".",
"_data",
"=",
"sorted",
"(",
"self",
".",
"_data",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
"[",
"0",
"]",
")"
] | Adds a data point to the series.
:param x: The numerical x value to be added.
:param y: The numerical y value to be added. | [
"Adds",
"a",
"data",
"point",
"to",
"the",
"series",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/series.py#L148-L161 |
250,288 | samirelanduk/quickplots | quickplots/series.py | Series.remove_data_point | def remove_data_point(self, x, y):
"""Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
a series."""
if len(self._data) == 1:
raise ValueError("You cannot remove a Series' last data point")
self._data.remove((x, y)) | python | def remove_data_point(self, x, y):
"""Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
a series."""
if len(self._data) == 1:
raise ValueError("You cannot remove a Series' last data point")
self._data.remove((x, y)) | [
"def",
"remove_data_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"You cannot remove a Series' last data point\"",
")",
"self",
".",
"_data",
".",
"remove",
"(",
"(",
"x",
",",
"y",
")",
")"
] | Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
a series. | [
"Removes",
"the",
"given",
"data",
"point",
"from",
"the",
"series",
"."
] | 59f5e6ff367b2c1c24ba7cf1805d03552034c6d8 | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/series.py#L164-L174 |
250,289 | hmartiniano/faz | faz/main.py | faz | def faz(input_file, variables=None):
"""
FAZ entry point.
"""
logging.debug("input file:\n {0}\n".format(input_file))
tasks = parse_input_file(input_file, variables=variables)
print("Found {0} tasks.".format(len(tasks)))
graph = DependencyGraph(tasks)
graph.show_tasks()
graph.execute() | python | def faz(input_file, variables=None):
"""
FAZ entry point.
"""
logging.debug("input file:\n {0}\n".format(input_file))
tasks = parse_input_file(input_file, variables=variables)
print("Found {0} tasks.".format(len(tasks)))
graph = DependencyGraph(tasks)
graph.show_tasks()
graph.execute() | [
"def",
"faz",
"(",
"input_file",
",",
"variables",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"\"input file:\\n {0}\\n\"",
".",
"format",
"(",
"input_file",
")",
")",
"tasks",
"=",
"parse_input_file",
"(",
"input_file",
",",
"variables",
"=",
"variables",
")",
"print",
"(",
"\"Found {0} tasks.\"",
".",
"format",
"(",
"len",
"(",
"tasks",
")",
")",
")",
"graph",
"=",
"DependencyGraph",
"(",
"tasks",
")",
"graph",
".",
"show_tasks",
"(",
")",
"graph",
".",
"execute",
"(",
")"
] | FAZ entry point. | [
"FAZ",
"entry",
"point",
"."
] | 36a58c45e8c0718d38cb3c533542c8743e7e7a65 | https://github.com/hmartiniano/faz/blob/36a58c45e8c0718d38cb3c533542c8743e7e7a65/faz/main.py#L34-L43 |
250,290 | blubberdiblub/eztemplate | setup.py | get_version | def get_version():
"""Build version number from git repository tag."""
try:
f = open('eztemplate/version.py', 'r')
except IOError as e:
if e.errno != errno.ENOENT:
raise
m = None
else:
m = re.match('^\s*__version__\s*=\s*(?P<version>.*)$', f.read(), re.M)
f.close()
__version__ = ast.literal_eval(m.group('version')) if m else None
try:
git_version = subprocess.check_output(['git', 'describe', '--dirty'])
except:
if __version__ is None:
raise ValueError("cannot determine version number")
return __version__
m = re.match(r'^\s*'
r'(?P<version>\S+?)'
r'(-(?P<post>\d+)-(?P<commit>g[0-9a-f]+))?'
r'(-(?P<dirty>dirty))?'
r'\s*$', git_version.decode())
if not m:
raise ValueError("cannot parse git describe output")
git_version = m.group('version')
post = m.group('post')
commit = m.group('commit')
dirty = m.group('dirty')
local = []
if post:
post = int(post)
if post:
git_version += '.post%d' % (post,)
if commit:
local.append(commit)
if dirty:
local.append(dirty)
if local:
git_version += '+' + '.'.join(local)
if git_version != __version__:
with open('eztemplate/version.py', 'w') as f:
f.write("__version__ = %r\n" % (str(git_version),))
return git_version | python | def get_version():
"""Build version number from git repository tag."""
try:
f = open('eztemplate/version.py', 'r')
except IOError as e:
if e.errno != errno.ENOENT:
raise
m = None
else:
m = re.match('^\s*__version__\s*=\s*(?P<version>.*)$', f.read(), re.M)
f.close()
__version__ = ast.literal_eval(m.group('version')) if m else None
try:
git_version = subprocess.check_output(['git', 'describe', '--dirty'])
except:
if __version__ is None:
raise ValueError("cannot determine version number")
return __version__
m = re.match(r'^\s*'
r'(?P<version>\S+?)'
r'(-(?P<post>\d+)-(?P<commit>g[0-9a-f]+))?'
r'(-(?P<dirty>dirty))?'
r'\s*$', git_version.decode())
if not m:
raise ValueError("cannot parse git describe output")
git_version = m.group('version')
post = m.group('post')
commit = m.group('commit')
dirty = m.group('dirty')
local = []
if post:
post = int(post)
if post:
git_version += '.post%d' % (post,)
if commit:
local.append(commit)
if dirty:
local.append(dirty)
if local:
git_version += '+' + '.'.join(local)
if git_version != __version__:
with open('eztemplate/version.py', 'w') as f:
f.write("__version__ = %r\n" % (str(git_version),))
return git_version | [
"def",
"get_version",
"(",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"'eztemplate/version.py'",
",",
"'r'",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"m",
"=",
"None",
"else",
":",
"m",
"=",
"re",
".",
"match",
"(",
"'^\\s*__version__\\s*=\\s*(?P<version>.*)$'",
",",
"f",
".",
"read",
"(",
")",
",",
"re",
".",
"M",
")",
"f",
".",
"close",
"(",
")",
"__version__",
"=",
"ast",
".",
"literal_eval",
"(",
"m",
".",
"group",
"(",
"'version'",
")",
")",
"if",
"m",
"else",
"None",
"try",
":",
"git_version",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'describe'",
",",
"'--dirty'",
"]",
")",
"except",
":",
"if",
"__version__",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"cannot determine version number\"",
")",
"return",
"__version__",
"m",
"=",
"re",
".",
"match",
"(",
"r'^\\s*'",
"r'(?P<version>\\S+?)'",
"r'(-(?P<post>\\d+)-(?P<commit>g[0-9a-f]+))?'",
"r'(-(?P<dirty>dirty))?'",
"r'\\s*$'",
",",
"git_version",
".",
"decode",
"(",
")",
")",
"if",
"not",
"m",
":",
"raise",
"ValueError",
"(",
"\"cannot parse git describe output\"",
")",
"git_version",
"=",
"m",
".",
"group",
"(",
"'version'",
")",
"post",
"=",
"m",
".",
"group",
"(",
"'post'",
")",
"commit",
"=",
"m",
".",
"group",
"(",
"'commit'",
")",
"dirty",
"=",
"m",
".",
"group",
"(",
"'dirty'",
")",
"local",
"=",
"[",
"]",
"if",
"post",
":",
"post",
"=",
"int",
"(",
"post",
")",
"if",
"post",
":",
"git_version",
"+=",
"'.post%d'",
"%",
"(",
"post",
",",
")",
"if",
"commit",
":",
"local",
".",
"append",
"(",
"commit",
")",
"if",
"dirty",
":",
"local",
".",
"append",
"(",
"dirty",
")",
"if",
"local",
":",
"git_version",
"+=",
"'+'",
"+",
"'.'",
".",
"join",
"(",
"local",
")",
"if",
"git_version",
"!=",
"__version__",
":",
"with",
"open",
"(",
"'eztemplate/version.py'",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"__version__ = %r\\n\"",
"%",
"(",
"str",
"(",
"git_version",
")",
",",
")",
")",
"return",
"git_version"
] | Build version number from git repository tag. | [
"Build",
"version",
"number",
"from",
"git",
"repository",
"tag",
"."
] | ab5b2b4987c045116d130fd83e216704b8edfb5d | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/setup.py#L15-L68 |
250,291 | blubberdiblub/eztemplate | setup.py | get_long_description | def get_long_description():
"""Provide README.md converted to reStructuredText format."""
try:
with open('README.md', 'r') as f:
description = f.read()
except OSError as e:
if e.errno != errno.ENOENT:
raise
return None
try:
process = subprocess.Popen([
'pandoc',
'-f', 'markdown_github',
'-t', 'rst',
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
)
except OSError as e:
if e.errno == errno.ENOENT:
return None
raise
description, __ = process.communicate(input=description)
if process.poll() is None:
process.kill()
raise Exception("pandoc did not terminate")
if process.poll():
raise Exception("pandoc terminated abnormally")
return description | python | def get_long_description():
"""Provide README.md converted to reStructuredText format."""
try:
with open('README.md', 'r') as f:
description = f.read()
except OSError as e:
if e.errno != errno.ENOENT:
raise
return None
try:
process = subprocess.Popen([
'pandoc',
'-f', 'markdown_github',
'-t', 'rst',
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
)
except OSError as e:
if e.errno == errno.ENOENT:
return None
raise
description, __ = process.communicate(input=description)
if process.poll() is None:
process.kill()
raise Exception("pandoc did not terminate")
if process.poll():
raise Exception("pandoc terminated abnormally")
return description | [
"def",
"get_long_description",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"'README.md'",
",",
"'r'",
")",
"as",
"f",
":",
"description",
"=",
"f",
".",
"read",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"return",
"None",
"try",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'pandoc'",
",",
"'-f'",
",",
"'markdown_github'",
",",
"'-t'",
",",
"'rst'",
",",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"universal_newlines",
"=",
"True",
",",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"None",
"raise",
"description",
",",
"__",
"=",
"process",
".",
"communicate",
"(",
"input",
"=",
"description",
")",
"if",
"process",
".",
"poll",
"(",
")",
"is",
"None",
":",
"process",
".",
"kill",
"(",
")",
"raise",
"Exception",
"(",
"\"pandoc did not terminate\"",
")",
"if",
"process",
".",
"poll",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"pandoc terminated abnormally\"",
")",
"return",
"description"
] | Provide README.md converted to reStructuredText format. | [
"Provide",
"README",
".",
"md",
"converted",
"to",
"reStructuredText",
"format",
"."
] | ab5b2b4987c045116d130fd83e216704b8edfb5d | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/setup.py#L71-L103 |
250,292 | anti1869/sunhead | src/sunhead/workers/http/ext/runtime.py | RuntimeStatsView.get | async def get(self):
"""Printing runtime statistics in JSON"""
context_data = self.get_context_data()
context_data.update(getattr(self.request.app, "stats", {}))
response = self.json_response(context_data)
return response | python | async def get(self):
"""Printing runtime statistics in JSON"""
context_data = self.get_context_data()
context_data.update(getattr(self.request.app, "stats", {}))
response = self.json_response(context_data)
return response | [
"async",
"def",
"get",
"(",
"self",
")",
":",
"context_data",
"=",
"self",
".",
"get_context_data",
"(",
")",
"context_data",
".",
"update",
"(",
"getattr",
"(",
"self",
".",
"request",
".",
"app",
",",
"\"stats\"",
",",
"{",
"}",
")",
")",
"response",
"=",
"self",
".",
"json_response",
"(",
"context_data",
")",
"return",
"response"
] | Printing runtime statistics in JSON | [
"Printing",
"runtime",
"statistics",
"in",
"JSON"
] | 5117ec797a38eb82d955241d20547d125efe80f3 | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/workers/http/ext/runtime.py#L56-L63 |
250,293 | sci-bots/mpm | mpm/bin/api.py | _dump_list | def _dump_list(list_data, jsonify, stream=sys.stdout):
'''
Dump list to output stream, optionally encoded as JSON.
Parameters
----------
list_data : list
jsonify : bool
stream : file-like
'''
if not jsonify and list_data:
print >> stream, '\n'.join(list_data)
else:
print >> stream, json.dumps(list_data) | python | def _dump_list(list_data, jsonify, stream=sys.stdout):
'''
Dump list to output stream, optionally encoded as JSON.
Parameters
----------
list_data : list
jsonify : bool
stream : file-like
'''
if not jsonify and list_data:
print >> stream, '\n'.join(list_data)
else:
print >> stream, json.dumps(list_data) | [
"def",
"_dump_list",
"(",
"list_data",
",",
"jsonify",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"not",
"jsonify",
"and",
"list_data",
":",
"print",
">>",
"stream",
",",
"'\\n'",
".",
"join",
"(",
"list_data",
")",
"else",
":",
"print",
">>",
"stream",
",",
"json",
".",
"dumps",
"(",
"list_data",
")"
] | Dump list to output stream, optionally encoded as JSON.
Parameters
----------
list_data : list
jsonify : bool
stream : file-like | [
"Dump",
"list",
"to",
"output",
"stream",
"optionally",
"encoded",
"as",
"JSON",
"."
] | a69651cda4b37ee6b17df4fe0809249e7f4dc536 | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/bin/api.py#L43-L56 |
250,294 | b3j0f/annotation | b3j0f/annotation/async.py | Asynchronous._threaded | def _threaded(self, *args, **kwargs):
"""Call the target and put the result in the Queue."""
for target in self.targets:
result = target(*args, **kwargs)
self.queue.put(result) | python | def _threaded(self, *args, **kwargs):
"""Call the target and put the result in the Queue."""
for target in self.targets:
result = target(*args, **kwargs)
self.queue.put(result) | [
"def",
"_threaded",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"result",
"=",
"target",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"queue",
".",
"put",
"(",
"result",
")"
] | Call the target and put the result in the Queue. | [
"Call",
"the",
"target",
"and",
"put",
"the",
"result",
"in",
"the",
"Queue",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/async.py#L97-L102 |
250,295 | b3j0f/annotation | b3j0f/annotation/async.py | Asynchronous.start | def start(self, *args, **kwargs):
"""Start execution of the function."""
self.queue = Queue()
thread = Thread(target=self._threaded, args=args, kwargs=kwargs)
thread.start()
return Asynchronous.Result(self.queue, thread) | python | def start(self, *args, **kwargs):
"""Start execution of the function."""
self.queue = Queue()
thread = Thread(target=self._threaded, args=args, kwargs=kwargs)
thread.start()
return Asynchronous.Result(self.queue, thread) | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queue",
"=",
"Queue",
"(",
")",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_threaded",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"thread",
".",
"start",
"(",
")",
"return",
"Asynchronous",
".",
"Result",
"(",
"self",
".",
"queue",
",",
"thread",
")"
] | Start execution of the function. | [
"Start",
"execution",
"of",
"the",
"function",
"."
] | 738035a974e4092696d9dc1bbd149faa21c8c51f | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/async.py#L111-L118 |
250,296 | Bekt/flask-pusher | flask_pusher.py | Pusher.init_app | def init_app(self, app, **options):
"""Configures the application."""
sd = options.setdefault
conf = app.config
sd('app_id', conf.get('PUSHER_APP_ID'))
sd('key', conf.get('PUSHER_KEY'))
sd('secret', conf.get('PUSHER_SECRET'))
sd('ssl', conf.get('PUSHER_SSL', True))
sd('host', conf.get('PUSHER_HOST'))
sd('port', conf.get('PUSHER_PORT'))
sd('cluster', conf.get('PUSHER_CLUSTER'))
sd('backend', conf.get('PUSHER_BACKEND'))
sd('json_encoder', (conf.get('PUSHER_JSON_ENCODER')
or app.json_encoder))
sd('json_decoder', (conf.get('PUSHER_JSON_DECODER')
or app.json_decoder))
if conf.get('PUSHER_TIMEOUT'):
sd('timeout', conf.get('PUSHER_TIMEOUT'))
super(Pusher, self).__init__(**options)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['pusher'] = self | python | def init_app(self, app, **options):
"""Configures the application."""
sd = options.setdefault
conf = app.config
sd('app_id', conf.get('PUSHER_APP_ID'))
sd('key', conf.get('PUSHER_KEY'))
sd('secret', conf.get('PUSHER_SECRET'))
sd('ssl', conf.get('PUSHER_SSL', True))
sd('host', conf.get('PUSHER_HOST'))
sd('port', conf.get('PUSHER_PORT'))
sd('cluster', conf.get('PUSHER_CLUSTER'))
sd('backend', conf.get('PUSHER_BACKEND'))
sd('json_encoder', (conf.get('PUSHER_JSON_ENCODER')
or app.json_encoder))
sd('json_decoder', (conf.get('PUSHER_JSON_DECODER')
or app.json_decoder))
if conf.get('PUSHER_TIMEOUT'):
sd('timeout', conf.get('PUSHER_TIMEOUT'))
super(Pusher, self).__init__(**options)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['pusher'] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"*",
"*",
"options",
")",
":",
"sd",
"=",
"options",
".",
"setdefault",
"conf",
"=",
"app",
".",
"config",
"sd",
"(",
"'app_id'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_APP_ID'",
")",
")",
"sd",
"(",
"'key'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_KEY'",
")",
")",
"sd",
"(",
"'secret'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_SECRET'",
")",
")",
"sd",
"(",
"'ssl'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_SSL'",
",",
"True",
")",
")",
"sd",
"(",
"'host'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_HOST'",
")",
")",
"sd",
"(",
"'port'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_PORT'",
")",
")",
"sd",
"(",
"'cluster'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_CLUSTER'",
")",
")",
"sd",
"(",
"'backend'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_BACKEND'",
")",
")",
"sd",
"(",
"'json_encoder'",
",",
"(",
"conf",
".",
"get",
"(",
"'PUSHER_JSON_ENCODER'",
")",
"or",
"app",
".",
"json_encoder",
")",
")",
"sd",
"(",
"'json_decoder'",
",",
"(",
"conf",
".",
"get",
"(",
"'PUSHER_JSON_DECODER'",
")",
"or",
"app",
".",
"json_decoder",
")",
")",
"if",
"conf",
".",
"get",
"(",
"'PUSHER_TIMEOUT'",
")",
":",
"sd",
"(",
"'timeout'",
",",
"conf",
".",
"get",
"(",
"'PUSHER_TIMEOUT'",
")",
")",
"super",
"(",
"Pusher",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"*",
"options",
")",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions",
"[",
"'pusher'",
"]",
"=",
"self"
] | Configures the application. | [
"Configures",
"the",
"application",
"."
] | 7ee077687fb01011b19a5cae65ccb35512d4e0c5 | https://github.com/Bekt/flask-pusher/blob/7ee077687fb01011b19a5cae65ccb35512d4e0c5/flask_pusher.py#L11-L35 |
250,297 | minhhoit/yacms | yacms/blog/management/commands/import_tumblr.py | title_from_content | def title_from_content(content):
"""
Try and extract the first sentence from a block of test to use as a title.
"""
for end in (". ", "?", "!", "<br />", "\n", "</p>"):
if end in content:
content = content.split(end)[0] + end
break
return strip_tags(content) | python | def title_from_content(content):
"""
Try and extract the first sentence from a block of test to use as a title.
"""
for end in (". ", "?", "!", "<br />", "\n", "</p>"):
if end in content:
content = content.split(end)[0] + end
break
return strip_tags(content) | [
"def",
"title_from_content",
"(",
"content",
")",
":",
"for",
"end",
"in",
"(",
"\". \"",
",",
"\"?\"",
",",
"\"!\"",
",",
"\"<br />\"",
",",
"\"\\n\"",
",",
"\"</p>\"",
")",
":",
"if",
"end",
"in",
"content",
":",
"content",
"=",
"content",
".",
"split",
"(",
"end",
")",
"[",
"0",
"]",
"+",
"end",
"break",
"return",
"strip_tags",
"(",
"content",
")"
] | Try and extract the first sentence from a block of test to use as a title. | [
"Try",
"and",
"extract",
"the",
"first",
"sentence",
"from",
"a",
"block",
"of",
"test",
"to",
"use",
"as",
"a",
"title",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/commands/import_tumblr.py#L25-L33 |
250,298 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/action_plugins/pause.py | ActionModule.run | def run(self, conn, tmp, module_name, module_args, inject):
''' run the pause actionmodule '''
hosts = ', '.join(self.runner.host_set)
args = parse_kv(template(self.runner.basedir, module_args, inject))
# Are 'minutes' or 'seconds' keys that exist in 'args'?
if 'minutes' in args or 'seconds' in args:
try:
if 'minutes' in args:
self.pause_type = 'minutes'
# The time() command operates in seconds so we need to
# recalculate for minutes=X values.
self.seconds = int(args['minutes']) * 60
else:
self.pause_type = 'seconds'
self.seconds = int(args['seconds'])
self.duration_unit = 'seconds'
except ValueError, e:
raise ae("non-integer value given for prompt duration:\n%s" % str(e))
# Is 'prompt' a key in 'args'?
elif 'prompt' in args:
self.pause_type = 'prompt'
self.prompt = "[%s]\n%s: " % (hosts, args['prompt'])
# Is 'args' empty, then this is the default prompted pause
elif len(args.keys()) == 0:
self.pause_type = 'prompt'
self.prompt = "[%s]\nPress enter to continue: " % hosts
# I have no idea what you're trying to do. But it's so wrong.
else:
raise ae("invalid pause type given. must be one of: %s" % \
", ".join(self.PAUSE_TYPES))
vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
(self.pause_type, self.duration_unit, self.seconds, self.prompt))
########################################################################
# Begin the hard work!
try:
self._start()
if not self.pause_type == 'prompt':
print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
time.sleep(self.seconds)
else:
# Clear out any unflushed buffered input which would
# otherwise be consumed by raw_input() prematurely.
tcflush(sys.stdin, TCIFLUSH)
raw_input(self.prompt)
except KeyboardInterrupt:
while True:
print '\nAction? (a)bort/(c)ontinue: '
c = getch()
if c == 'c':
# continue playbook evaluation
break
elif c == 'a':
# abort further playbook evaluation
raise ae('user requested abort!')
finally:
self._stop()
return ReturnData(conn=conn, result=self.result) | python | def run(self, conn, tmp, module_name, module_args, inject):
''' run the pause actionmodule '''
hosts = ', '.join(self.runner.host_set)
args = parse_kv(template(self.runner.basedir, module_args, inject))
# Are 'minutes' or 'seconds' keys that exist in 'args'?
if 'minutes' in args or 'seconds' in args:
try:
if 'minutes' in args:
self.pause_type = 'minutes'
# The time() command operates in seconds so we need to
# recalculate for minutes=X values.
self.seconds = int(args['minutes']) * 60
else:
self.pause_type = 'seconds'
self.seconds = int(args['seconds'])
self.duration_unit = 'seconds'
except ValueError, e:
raise ae("non-integer value given for prompt duration:\n%s" % str(e))
# Is 'prompt' a key in 'args'?
elif 'prompt' in args:
self.pause_type = 'prompt'
self.prompt = "[%s]\n%s: " % (hosts, args['prompt'])
# Is 'args' empty, then this is the default prompted pause
elif len(args.keys()) == 0:
self.pause_type = 'prompt'
self.prompt = "[%s]\nPress enter to continue: " % hosts
# I have no idea what you're trying to do. But it's so wrong.
else:
raise ae("invalid pause type given. must be one of: %s" % \
", ".join(self.PAUSE_TYPES))
vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
(self.pause_type, self.duration_unit, self.seconds, self.prompt))
########################################################################
# Begin the hard work!
try:
self._start()
if not self.pause_type == 'prompt':
print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
time.sleep(self.seconds)
else:
# Clear out any unflushed buffered input which would
# otherwise be consumed by raw_input() prematurely.
tcflush(sys.stdin, TCIFLUSH)
raw_input(self.prompt)
except KeyboardInterrupt:
while True:
print '\nAction? (a)bort/(c)ontinue: '
c = getch()
if c == 'c':
# continue playbook evaluation
break
elif c == 'a':
# abort further playbook evaluation
raise ae('user requested abort!')
finally:
self._stop()
return ReturnData(conn=conn, result=self.result) | [
"def",
"run",
"(",
"self",
",",
"conn",
",",
"tmp",
",",
"module_name",
",",
"module_args",
",",
"inject",
")",
":",
"hosts",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"runner",
".",
"host_set",
")",
"args",
"=",
"parse_kv",
"(",
"template",
"(",
"self",
".",
"runner",
".",
"basedir",
",",
"module_args",
",",
"inject",
")",
")",
"# Are 'minutes' or 'seconds' keys that exist in 'args'?",
"if",
"'minutes'",
"in",
"args",
"or",
"'seconds'",
"in",
"args",
":",
"try",
":",
"if",
"'minutes'",
"in",
"args",
":",
"self",
".",
"pause_type",
"=",
"'minutes'",
"# The time() command operates in seconds so we need to",
"# recalculate for minutes=X values.",
"self",
".",
"seconds",
"=",
"int",
"(",
"args",
"[",
"'minutes'",
"]",
")",
"*",
"60",
"else",
":",
"self",
".",
"pause_type",
"=",
"'seconds'",
"self",
".",
"seconds",
"=",
"int",
"(",
"args",
"[",
"'seconds'",
"]",
")",
"self",
".",
"duration_unit",
"=",
"'seconds'",
"except",
"ValueError",
",",
"e",
":",
"raise",
"ae",
"(",
"\"non-integer value given for prompt duration:\\n%s\"",
"%",
"str",
"(",
"e",
")",
")",
"# Is 'prompt' a key in 'args'?",
"elif",
"'prompt'",
"in",
"args",
":",
"self",
".",
"pause_type",
"=",
"'prompt'",
"self",
".",
"prompt",
"=",
"\"[%s]\\n%s: \"",
"%",
"(",
"hosts",
",",
"args",
"[",
"'prompt'",
"]",
")",
"# Is 'args' empty, then this is the default prompted pause",
"elif",
"len",
"(",
"args",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"self",
".",
"pause_type",
"=",
"'prompt'",
"self",
".",
"prompt",
"=",
"\"[%s]\\nPress enter to continue: \"",
"%",
"hosts",
"# I have no idea what you're trying to do. But it's so wrong.",
"else",
":",
"raise",
"ae",
"(",
"\"invalid pause type given. must be one of: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"self",
".",
"PAUSE_TYPES",
")",
")",
"vv",
"(",
"\"created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s\"",
"%",
"(",
"self",
".",
"pause_type",
",",
"self",
".",
"duration_unit",
",",
"self",
".",
"seconds",
",",
"self",
".",
"prompt",
")",
")",
"########################################################################",
"# Begin the hard work!",
"try",
":",
"self",
".",
"_start",
"(",
")",
"if",
"not",
"self",
".",
"pause_type",
"==",
"'prompt'",
":",
"print",
"\"[%s]\\nPausing for %s seconds\"",
"%",
"(",
"hosts",
",",
"self",
".",
"seconds",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"seconds",
")",
"else",
":",
"# Clear out any unflushed buffered input which would",
"# otherwise be consumed by raw_input() prematurely.",
"tcflush",
"(",
"sys",
".",
"stdin",
",",
"TCIFLUSH",
")",
"raw_input",
"(",
"self",
".",
"prompt",
")",
"except",
"KeyboardInterrupt",
":",
"while",
"True",
":",
"print",
"'\\nAction? (a)bort/(c)ontinue: '",
"c",
"=",
"getch",
"(",
")",
"if",
"c",
"==",
"'c'",
":",
"# continue playbook evaluation",
"break",
"elif",
"c",
"==",
"'a'",
":",
"# abort further playbook evaluation",
"raise",
"ae",
"(",
"'user requested abort!'",
")",
"finally",
":",
"self",
".",
"_stop",
"(",
")",
"return",
"ReturnData",
"(",
"conn",
"=",
"conn",
",",
"result",
"=",
"self",
".",
"result",
")"
] | run the pause actionmodule | [
"run",
"the",
"pause",
"actionmodule"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/action_plugins/pause.py#L49-L109 |
250,299 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/action_plugins/pause.py | ActionModule._start | def _start(self):
''' mark the time of execution for duration calculations later '''
self.start = time.time()
self.result['start'] = str(datetime.datetime.now())
if not self.pause_type == 'prompt':
print "(^C-c = continue early, ^C-a = abort)" | python | def _start(self):
''' mark the time of execution for duration calculations later '''
self.start = time.time()
self.result['start'] = str(datetime.datetime.now())
if not self.pause_type == 'prompt':
print "(^C-c = continue early, ^C-a = abort)" | [
"def",
"_start",
"(",
"self",
")",
":",
"self",
".",
"start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"result",
"[",
"'start'",
"]",
"=",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"if",
"not",
"self",
".",
"pause_type",
"==",
"'prompt'",
":",
"print",
"\"(^C-c = continue early, ^C-a = abort)\""
] | mark the time of execution for duration calculations later | [
"mark",
"the",
"time",
"of",
"execution",
"for",
"duration",
"calculations",
"later"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/action_plugins/pause.py#L111-L116 |
Subsets and Splits