nwo
stringlengths 5
58
| sha
stringlengths 40
40
| path
stringlengths 5
172
| language
stringclasses 1
value | identifier
stringlengths 1
100
| parameters
stringlengths 2
3.5k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
21.5k
| docstring
stringlengths 2
17k
| docstring_summary
stringlengths 0
6.58k
| docstring_tokens
sequence | function
stringlengths 35
55.6k
| function_tokens
sequence | url
stringlengths 89
269
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/Formulator/Form.py | python | ZMIForm._get_field_ids | (self, group, REQUEST) | return field_ids | Get the checked field_ids that we're operating on | Get the checked field_ids that we're operating on | [
"Get",
"the",
"checked",
"field_ids",
"that",
"we",
"re",
"operating",
"on"
] | def _get_field_ids(self, group, REQUEST):
"""Get the checked field_ids that we're operating on
"""
field_ids = []
for field in self.get_fields_in_group(group, include_disabled=True):
if REQUEST.form.has_key(field.id):
field_ids.append(field.id)
return field_ids | [
"def",
"_get_field_ids",
"(",
"self",
",",
"group",
",",
"REQUEST",
")",
":",
"field_ids",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"get_fields_in_group",
"(",
"group",
",",
"include_disabled",
"=",
"True",
")",
":",
"if",
"REQUEST",
".",
"form",
".",
"has_key",
"(",
"field",
".",
"id",
")",
":",
"field_ids",
".",
"append",
"(",
"field",
".",
"id",
")",
"return",
"field_ids"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Formulator/Form.py#L832-L839 |
|
google/blockly | 423d2e58a13620c255532a24f8005707bad9d7b6 | closure/bin/calcdeps.py | python | BuildDependenciesFromFiles | (files) | return result | Build a list of dependencies from a list of files.
Description:
Takes a list of files, extracts their provides and requires, and builds
out a list of dependency objects.
Args:
files: a list of files to be parsed for goog.provides and goog.requires.
Returns:
A list of dependency objects, one for each file in the files argument. | Build a list of dependencies from a list of files. | [
"Build",
"a",
"list",
"of",
"dependencies",
"from",
"a",
"list",
"of",
"files",
"."
] | def BuildDependenciesFromFiles(files):
"""Build a list of dependencies from a list of files.
Description:
Takes a list of files, extracts their provides and requires, and builds
out a list of dependency objects.
Args:
files: a list of files to be parsed for goog.provides and goog.requires.
Returns:
A list of dependency objects, one for each file in the files argument.
"""
result = []
filenames = set()
for filename in files:
if filename in filenames:
continue
# Python 3 requires the file encoding to be specified
if (sys.version_info[0] < 3):
file_handle = open(filename, 'r')
else:
file_handle = open(filename, 'r', encoding='utf8')
try:
dep = CreateDependencyInfo(filename, file_handle)
result.append(dep)
finally:
file_handle.close()
filenames.add(filename)
return result | [
"def",
"BuildDependenciesFromFiles",
"(",
"files",
")",
":",
"result",
"=",
"[",
"]",
"filenames",
"=",
"set",
"(",
")",
"for",
"filename",
"in",
"files",
":",
"if",
"filename",
"in",
"filenames",
":",
"continue",
"# Python 3 requires the file encoding to be specified",
"if",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
")",
":",
"file_handle",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"else",
":",
"file_handle",
"=",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"try",
":",
"dep",
"=",
"CreateDependencyInfo",
"(",
"filename",
",",
"file_handle",
")",
"result",
".",
"append",
"(",
"dep",
")",
"finally",
":",
"file_handle",
".",
"close",
"(",
")",
"filenames",
".",
"add",
"(",
"filename",
")",
"return",
"result"
] | https://github.com/google/blockly/blob/423d2e58a13620c255532a24f8005707bad9d7b6/closure/bin/calcdeps.py#L101-L134 |
|
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | 3rd_party/python2/site-packages/cherrypy/lib/auth_digest.py | python | get_ha1_file_htdigest | (filename) | return get_ha1 | Returns a get_ha1 function which obtains a HA1 password hash from a
flat file with lines of the same format as that produced by the Apache
htdigest utility. For example, for realm 'wonderland', username 'alice',
and password '4x5istwelve', the htdigest line would be::
alice:wonderland:3238cdfe91a8b2ed8e39646921a02d4c
If you want to use an Apache htdigest file as the credentials store,
then use get_ha1_file_htdigest(my_htdigest_file) as the value for the
get_ha1 argument to digest_auth(). It is recommended that the filename
argument be an absolute path, to avoid problems. | Returns a get_ha1 function which obtains a HA1 password hash from a
flat file with lines of the same format as that produced by the Apache
htdigest utility. For example, for realm 'wonderland', username 'alice',
and password '4x5istwelve', the htdigest line would be:: | [
"Returns",
"a",
"get_ha1",
"function",
"which",
"obtains",
"a",
"HA1",
"password",
"hash",
"from",
"a",
"flat",
"file",
"with",
"lines",
"of",
"the",
"same",
"format",
"as",
"that",
"produced",
"by",
"the",
"Apache",
"htdigest",
"utility",
".",
"For",
"example",
"for",
"realm",
"wonderland",
"username",
"alice",
"and",
"password",
"4x5istwelve",
"the",
"htdigest",
"line",
"would",
"be",
"::"
] | def get_ha1_file_htdigest(filename):
"""Returns a get_ha1 function which obtains a HA1 password hash from a
flat file with lines of the same format as that produced by the Apache
htdigest utility. For example, for realm 'wonderland', username 'alice',
and password '4x5istwelve', the htdigest line would be::
alice:wonderland:3238cdfe91a8b2ed8e39646921a02d4c
If you want to use an Apache htdigest file as the credentials store,
then use get_ha1_file_htdigest(my_htdigest_file) as the value for the
get_ha1 argument to digest_auth(). It is recommended that the filename
argument be an absolute path, to avoid problems.
"""
def get_ha1(realm, username):
result = None
f = open(filename, 'r')
for line in f:
u, r, ha1 = line.rstrip().split(':')
if u == username and r == realm:
result = ha1
break
f.close()
return result
return get_ha1 | [
"def",
"get_ha1_file_htdigest",
"(",
"filename",
")",
":",
"def",
"get_ha1",
"(",
"realm",
",",
"username",
")",
":",
"result",
"=",
"None",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"for",
"line",
"in",
"f",
":",
"u",
",",
"r",
",",
"ha1",
"=",
"line",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"':'",
")",
"if",
"u",
"==",
"username",
"and",
"r",
"==",
"realm",
":",
"result",
"=",
"ha1",
"break",
"f",
".",
"close",
"(",
")",
"return",
"result",
"return",
"get_ha1"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python2/site-packages/cherrypy/lib/auth_digest.py#L84-L108 |
|
gallantlab/pycortex | d492d139f7cced0cbaa64953a191cf9f4fefe249 | cortex/quickflat/utils.py | python | _color2hex | (color) | return hexcol | Convert arbitrary color input to hex string | Convert arbitrary color input to hex string | [
"Convert",
"arbitrary",
"color",
"input",
"to",
"hex",
"string"
] | def _color2hex(color):
"""Convert arbitrary color input to hex string"""
from matplotlib import colors
cc = colors.ColorConverter()
rgba = cc.to_rgba(color)
hexcol = colors.rgb2hex(rgba)
return hexcol | [
"def",
"_color2hex",
"(",
"color",
")",
":",
"from",
"matplotlib",
"import",
"colors",
"cc",
"=",
"colors",
".",
"ColorConverter",
"(",
")",
"rgba",
"=",
"cc",
".",
"to_rgba",
"(",
"color",
")",
"hexcol",
"=",
"colors",
".",
"rgb2hex",
"(",
"rgba",
")",
"return",
"hexcol"
] | https://github.com/gallantlab/pycortex/blob/d492d139f7cced0cbaa64953a191cf9f4fefe249/cortex/quickflat/utils.py#L204-L210 |
|
mozilla/ichnaea | 63a2bf1ba057c1b90931f6bf0f88c570c21aaf27 | ichnaea/data/monitor.py | python | QueueSizeAndRateControl.update_rate_with_rate_controller | (self, backlog) | Generate a new sample rate. | Generate a new sample rate. | [
"Generate",
"a",
"new",
"sample",
"rate",
"."
] | def update_rate_with_rate_controller(self, backlog):
"""Generate a new sample rate."""
assert self.rc_controller
output = self.rc_controller(backlog)
self.rate = 100.0 * max(0.0, min(1.0, output / self.rc_target)) | [
"def",
"update_rate_with_rate_controller",
"(",
"self",
",",
"backlog",
")",
":",
"assert",
"self",
".",
"rc_controller",
"output",
"=",
"self",
".",
"rc_controller",
"(",
"backlog",
")",
"self",
".",
"rate",
"=",
"100.0",
"*",
"max",
"(",
"0.0",
",",
"min",
"(",
"1.0",
",",
"output",
"/",
"self",
".",
"rc_target",
")",
")"
] | https://github.com/mozilla/ichnaea/blob/63a2bf1ba057c1b90931f6bf0f88c570c21aaf27/ichnaea/data/monitor.py#L354-L358 |
||
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | api/src/opentrons/protocol_api/labware.py | python | Well.__eq__ | (self, other: object) | return self.top().point == other.top().point | Assuming that equality of wells in this system is having the same
absolute coordinates for the top. | Assuming that equality of wells in this system is having the same
absolute coordinates for the top. | [
"Assuming",
"that",
"equality",
"of",
"wells",
"in",
"this",
"system",
"is",
"having",
"the",
"same",
"absolute",
"coordinates",
"for",
"the",
"top",
"."
] | def __eq__(self, other: object) -> bool:
"""
Assuming that equality of wells in this system is having the same
absolute coordinates for the top.
"""
if not isinstance(other, Well):
return NotImplemented
return self.top().point == other.top().point | [
"def",
"__eq__",
"(",
"self",
",",
"other",
":",
"object",
")",
"->",
"bool",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Well",
")",
":",
"return",
"NotImplemented",
"return",
"self",
".",
"top",
"(",
")",
".",
"point",
"==",
"other",
".",
"top",
"(",
")",
".",
"point"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/protocol_api/labware.py#L204-L211 |
|
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/jedi/api/__init__.py | python | Script.goto_assignments | (self, follow_imports=False) | return helpers.sorted_definitions(defs) | Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
dynamic language, which means depending on an option you can have two
different versions of a function.
:rtype: list of :class:`classes.Definition` | Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
dynamic language, which means depending on an option you can have two
different versions of a function. | [
"Return",
"the",
"first",
"definition",
"found",
"while",
"optionally",
"following",
"imports",
".",
"Multiple",
"objects",
"may",
"be",
"returned",
"because",
"Python",
"itself",
"is",
"a",
"dynamic",
"language",
"which",
"means",
"depending",
"on",
"an",
"option",
"you",
"can",
"have",
"two",
"different",
"versions",
"of",
"a",
"function",
"."
] | def goto_assignments(self, follow_imports=False):
"""
Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
dynamic language, which means depending on an option you can have two
different versions of a function.
:rtype: list of :class:`classes.Definition`
"""
def filter_follow_imports(names, check):
for name in names:
if check(name):
for result in filter_follow_imports(name.goto(), check):
yield result
else:
yield name
tree_name = self._module_node.get_name_of_position(self._pos)
if tree_name is None:
return []
context = self._evaluator.create_context(self._get_module(), tree_name)
names = list(self._evaluator.goto(context, tree_name))
if follow_imports:
def check(name):
return name.is_import()
else:
def check(name):
return isinstance(name, imports.SubModuleName)
names = filter_follow_imports(names, check)
defs = [classes.Definition(self._evaluator, d) for d in set(names)]
return helpers.sorted_definitions(defs) | [
"def",
"goto_assignments",
"(",
"self",
",",
"follow_imports",
"=",
"False",
")",
":",
"def",
"filter_follow_imports",
"(",
"names",
",",
"check",
")",
":",
"for",
"name",
"in",
"names",
":",
"if",
"check",
"(",
"name",
")",
":",
"for",
"result",
"in",
"filter_follow_imports",
"(",
"name",
".",
"goto",
"(",
")",
",",
"check",
")",
":",
"yield",
"result",
"else",
":",
"yield",
"name",
"tree_name",
"=",
"self",
".",
"_module_node",
".",
"get_name_of_position",
"(",
"self",
".",
"_pos",
")",
"if",
"tree_name",
"is",
"None",
":",
"return",
"[",
"]",
"context",
"=",
"self",
".",
"_evaluator",
".",
"create_context",
"(",
"self",
".",
"_get_module",
"(",
")",
",",
"tree_name",
")",
"names",
"=",
"list",
"(",
"self",
".",
"_evaluator",
".",
"goto",
"(",
"context",
",",
"tree_name",
")",
")",
"if",
"follow_imports",
":",
"def",
"check",
"(",
"name",
")",
":",
"return",
"name",
".",
"is_import",
"(",
")",
"else",
":",
"def",
"check",
"(",
"name",
")",
":",
"return",
"isinstance",
"(",
"name",
",",
"imports",
".",
"SubModuleName",
")",
"names",
"=",
"filter_follow_imports",
"(",
"names",
",",
"check",
")",
"defs",
"=",
"[",
"classes",
".",
"Definition",
"(",
"self",
".",
"_evaluator",
",",
"d",
")",
"for",
"d",
"in",
"set",
"(",
"names",
")",
"]",
"return",
"helpers",
".",
"sorted_definitions",
"(",
"defs",
")"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/jedi/api/__init__.py#L206-L239 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/__init__.py | python | Script.goto_assignments | (self, follow_imports=False) | return helpers.sorted_definitions(defs) | Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
dynamic language, which means depending on an option you can have two
different versions of a function.
:rtype: list of :class:`classes.Definition` | Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
dynamic language, which means depending on an option you can have two
different versions of a function. | [
"Return",
"the",
"first",
"definition",
"found",
"while",
"optionally",
"following",
"imports",
".",
"Multiple",
"objects",
"may",
"be",
"returned",
"because",
"Python",
"itself",
"is",
"a",
"dynamic",
"language",
"which",
"means",
"depending",
"on",
"an",
"option",
"you",
"can",
"have",
"two",
"different",
"versions",
"of",
"a",
"function",
"."
] | def goto_assignments(self, follow_imports=False):
"""
Return the first definition found, while optionally following imports.
Multiple objects may be returned, because Python itself is a
dynamic language, which means depending on an option you can have two
different versions of a function.
:rtype: list of :class:`classes.Definition`
"""
def filter_follow_imports(names, check):
for name in names:
if check(name):
for result in filter_follow_imports(name.goto(), check):
yield result
else:
yield name
tree_name = self._module_node.get_name_of_position(self._pos)
if tree_name is None:
return []
context = self._evaluator.create_context(self._get_module(), tree_name)
names = list(self._evaluator.goto(context, tree_name))
if follow_imports:
def check(name):
return name.is_import()
else:
def check(name):
return isinstance(name, imports.SubModuleName)
names = filter_follow_imports(names, check)
defs = [classes.Definition(self._evaluator, d) for d in set(names)]
return helpers.sorted_definitions(defs) | [
"def",
"goto_assignments",
"(",
"self",
",",
"follow_imports",
"=",
"False",
")",
":",
"def",
"filter_follow_imports",
"(",
"names",
",",
"check",
")",
":",
"for",
"name",
"in",
"names",
":",
"if",
"check",
"(",
"name",
")",
":",
"for",
"result",
"in",
"filter_follow_imports",
"(",
"name",
".",
"goto",
"(",
")",
",",
"check",
")",
":",
"yield",
"result",
"else",
":",
"yield",
"name",
"tree_name",
"=",
"self",
".",
"_module_node",
".",
"get_name_of_position",
"(",
"self",
".",
"_pos",
")",
"if",
"tree_name",
"is",
"None",
":",
"return",
"[",
"]",
"context",
"=",
"self",
".",
"_evaluator",
".",
"create_context",
"(",
"self",
".",
"_get_module",
"(",
")",
",",
"tree_name",
")",
"names",
"=",
"list",
"(",
"self",
".",
"_evaluator",
".",
"goto",
"(",
"context",
",",
"tree_name",
")",
")",
"if",
"follow_imports",
":",
"def",
"check",
"(",
"name",
")",
":",
"return",
"name",
".",
"is_import",
"(",
")",
"else",
":",
"def",
"check",
"(",
"name",
")",
":",
"return",
"isinstance",
"(",
"name",
",",
"imports",
".",
"SubModuleName",
")",
"names",
"=",
"filter_follow_imports",
"(",
"names",
",",
"check",
")",
"defs",
"=",
"[",
"classes",
".",
"Definition",
"(",
"self",
".",
"_evaluator",
",",
"d",
")",
"for",
"d",
"in",
"set",
"(",
"names",
")",
"]",
"return",
"helpers",
".",
"sorted_definitions",
"(",
"defs",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/__init__.py#L206-L239 |
|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/cachecontrol/serialize.py | python | Serializer.prepare_response | (self, request, cached) | return HTTPResponse(body=body, preload_content=False, **cached["response"]) | Verify our vary headers match and construct a real urllib3
HTTPResponse object. | Verify our vary headers match and construct a real urllib3
HTTPResponse object. | [
"Verify",
"our",
"vary",
"headers",
"match",
"and",
"construct",
"a",
"real",
"urllib3",
"HTTPResponse",
"object",
"."
] | def prepare_response(self, request, cached):
"""Verify our vary headers match and construct a real urllib3
HTTPResponse object.
"""
# Special case the '*' Vary value as it means we cannot actually
# determine if the cached response is suitable for this request.
if "*" in cached.get("vary", {}):
return
# Ensure that the Vary headers for the cached response match our
# request
for header, value in cached.get("vary", {}).items():
if request.headers.get(header, None) != value:
return
body_raw = cached["response"].pop("body")
headers = CaseInsensitiveDict(data=cached["response"]["headers"])
if headers.get("transfer-encoding", "") == "chunked":
headers.pop("transfer-encoding")
cached["response"]["headers"] = headers
try:
body = io.BytesIO(body_raw)
except TypeError:
# This can happen if cachecontrol serialized to v1 format (pickle)
# using Python 2. A Python 2 str(byte string) will be unpickled as
# a Python 3 str (unicode string), which will cause the above to
# fail with:
#
# TypeError: 'str' does not support the buffer interface
body = io.BytesIO(body_raw.encode("utf8"))
return HTTPResponse(body=body, preload_content=False, **cached["response"]) | [
"def",
"prepare_response",
"(",
"self",
",",
"request",
",",
"cached",
")",
":",
"# Special case the '*' Vary value as it means we cannot actually",
"# determine if the cached response is suitable for this request.",
"if",
"\"*\"",
"in",
"cached",
".",
"get",
"(",
"\"vary\"",
",",
"{",
"}",
")",
":",
"return",
"# Ensure that the Vary headers for the cached response match our",
"# request",
"for",
"header",
",",
"value",
"in",
"cached",
".",
"get",
"(",
"\"vary\"",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"request",
".",
"headers",
".",
"get",
"(",
"header",
",",
"None",
")",
"!=",
"value",
":",
"return",
"body_raw",
"=",
"cached",
"[",
"\"response\"",
"]",
".",
"pop",
"(",
"\"body\"",
")",
"headers",
"=",
"CaseInsensitiveDict",
"(",
"data",
"=",
"cached",
"[",
"\"response\"",
"]",
"[",
"\"headers\"",
"]",
")",
"if",
"headers",
".",
"get",
"(",
"\"transfer-encoding\"",
",",
"\"\"",
")",
"==",
"\"chunked\"",
":",
"headers",
".",
"pop",
"(",
"\"transfer-encoding\"",
")",
"cached",
"[",
"\"response\"",
"]",
"[",
"\"headers\"",
"]",
"=",
"headers",
"try",
":",
"body",
"=",
"io",
".",
"BytesIO",
"(",
"body_raw",
")",
"except",
"TypeError",
":",
"# This can happen if cachecontrol serialized to v1 format (pickle)",
"# using Python 2. A Python 2 str(byte string) will be unpickled as",
"# a Python 3 str (unicode string), which will cause the above to",
"# fail with:",
"#",
"# TypeError: 'str' does not support the buffer interface",
"body",
"=",
"io",
".",
"BytesIO",
"(",
"body_raw",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"return",
"HTTPResponse",
"(",
"body",
"=",
"body",
",",
"preload_content",
"=",
"False",
",",
"*",
"*",
"cached",
"[",
"\"response\"",
"]",
")"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/cachecontrol/serialize.py#L104-L138 |
|
NorthFoxz/whatsthis | 8fb3cb602d7583f17134373330c3d40987039309 | server/inceptionServer.py | python | SimpleHTTPRequestHandler.list_directory | (self, path) | return f | Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head(). | Helper to produce a directory listing (absent index.html). | [
"Helper",
"to",
"produce",
"a",
"directory",
"listing",
"(",
"absent",
"index",
".",
"html",
")",
"."
] | def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().
"""
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
f.write("<hr>\n")
f.write("<form ENCTYPE=\"multipart/form-data\" method=\"post\">")
f.write("<input name=\"file\" type=\"file\"/>")
f.write("<input type=\"submit\" value=\"upload\"/></form>\n")
f.write("<hr>\n<ul>\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<li><a href="%s">%s</a>\n'
% (urllib.quote(linkname), cgi.escape(displayname)))
f.write("</ul>\n<hr>\n</body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f | [
"def",
"list_directory",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"list",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"except",
"os",
".",
"error",
":",
"self",
".",
"send_error",
"(",
"404",
",",
"\"No permission to list directory\"",
")",
"return",
"None",
"list",
".",
"sort",
"(",
"key",
"=",
"lambda",
"a",
":",
"a",
".",
"lower",
"(",
")",
")",
"f",
"=",
"StringIO",
"(",
")",
"displaypath",
"=",
"cgi",
".",
"escape",
"(",
"urllib",
".",
"unquote",
"(",
"self",
".",
"path",
")",
")",
"f",
".",
"write",
"(",
"'<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">'",
")",
"f",
".",
"write",
"(",
"\"<html>\\n<title>Directory listing for %s</title>\\n\"",
"%",
"displaypath",
")",
"f",
".",
"write",
"(",
"\"<body>\\n<h2>Directory listing for %s</h2>\\n\"",
"%",
"displaypath",
")",
"f",
".",
"write",
"(",
"\"<hr>\\n\"",
")",
"f",
".",
"write",
"(",
"\"<form ENCTYPE=\\\"multipart/form-data\\\" method=\\\"post\\\">\"",
")",
"f",
".",
"write",
"(",
"\"<input name=\\\"file\\\" type=\\\"file\\\"/>\"",
")",
"f",
".",
"write",
"(",
"\"<input type=\\\"submit\\\" value=\\\"upload\\\"/></form>\\n\"",
")",
"f",
".",
"write",
"(",
"\"<hr>\\n<ul>\\n\"",
")",
"for",
"name",
"in",
"list",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"displayname",
"=",
"linkname",
"=",
"name",
"# Append / for directories or @ for symbolic links",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullname",
")",
":",
"displayname",
"=",
"name",
"+",
"\"/\"",
"linkname",
"=",
"name",
"+",
"\"/\"",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"fullname",
")",
":",
"displayname",
"=",
"name",
"+",
"\"@\"",
"# Note: a link to a directory displays with @ and links with /",
"f",
".",
"write",
"(",
"'<li><a href=\"%s\">%s</a>\\n'",
"%",
"(",
"urllib",
".",
"quote",
"(",
"linkname",
")",
",",
"cgi",
".",
"escape",
"(",
"displayname",
")",
")",
")",
"f",
".",
"write",
"(",
"\"</ul>\\n<hr>\\n</body>\\n</html>\\n\"",
")",
"length",
"=",
"f",
".",
"tell",
"(",
")",
"f",
".",
"seek",
"(",
"0",
")",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"\"Content-type\"",
",",
"\"text/html\"",
")",
"self",
".",
"send_header",
"(",
"\"Content-Length\"",
",",
"str",
"(",
"length",
")",
")",
"self",
".",
"end_headers",
"(",
")",
"return",
"f"
] | https://github.com/NorthFoxz/whatsthis/blob/8fb3cb602d7583f17134373330c3d40987039309/server/inceptionServer.py#L178-L221 |
|
mapillary/OpenSfM | 9766a11e11544fc71fe689f33b34d0610cca2944 | opensfm/features.py | python | FeaturesData.from_file | (cls, fileobject: Any, config: Dict[str, Any]) | return getattr(cls, "_from_file_v%d" % version)(s, config) | Load features from file (path like or file object like) | Load features from file (path like or file object like) | [
"Load",
"features",
"from",
"file",
"(",
"path",
"like",
"or",
"file",
"object",
"like",
")"
] | def from_file(cls, fileobject: Any, config: Dict[str, Any]) -> "FeaturesData":
"""Load features from file (path like or file object like)"""
s = np.load(fileobject, allow_pickle=True)
version = cls._features_file_version(s)
return getattr(cls, "_from_file_v%d" % version)(s, config) | [
"def",
"from_file",
"(",
"cls",
",",
"fileobject",
":",
"Any",
",",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"\"FeaturesData\"",
":",
"s",
"=",
"np",
".",
"load",
"(",
"fileobject",
",",
"allow_pickle",
"=",
"True",
")",
"version",
"=",
"cls",
".",
"_features_file_version",
"(",
"s",
")",
"return",
"getattr",
"(",
"cls",
",",
"\"_from_file_v%d\"",
"%",
"version",
")",
"(",
"s",
",",
"config",
")"
] | https://github.com/mapillary/OpenSfM/blob/9766a11e11544fc71fe689f33b34d0610cca2944/opensfm/features.py#L139-L143 |
|
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | 3rd_party/python3/site-packages/cherrypy/lib/httputil.py | python | AcceptElement.qvalue | (self) | The qvalue, or priority, of this value. | The qvalue, or priority, of this value. | [
"The",
"qvalue",
"or",
"priority",
"of",
"this",
"value",
"."
] | def qvalue(self):
'The qvalue, or priority, of this value.'
val = self.params.get('q', '1')
if isinstance(val, HeaderElement):
val = val.value
try:
return float(val)
except ValueError as val_err:
"""Fail client requests with invalid quality value.
Ref: https://github.com/cherrypy/cherrypy/issues/1370
"""
raise cherrypy.HTTPError(
400,
'Malformed HTTP header: `{}`'.
format(str(self)),
) from val_err | [
"def",
"qvalue",
"(",
"self",
")",
":",
"val",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'q'",
",",
"'1'",
")",
"if",
"isinstance",
"(",
"val",
",",
"HeaderElement",
")",
":",
"val",
"=",
"val",
".",
"value",
"try",
":",
"return",
"float",
"(",
"val",
")",
"except",
"ValueError",
"as",
"val_err",
":",
"\"\"\"Fail client requests with invalid quality value.\n\n Ref: https://github.com/cherrypy/cherrypy/issues/1370\n \"\"\"",
"raise",
"cherrypy",
".",
"HTTPError",
"(",
"400",
",",
"'Malformed HTTP header: `{}`'",
".",
"format",
"(",
"str",
"(",
"self",
")",
")",
",",
")",
"from",
"val_err"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cherrypy/lib/httputil.py#L198-L214 |
||
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ERP5Type/mixin/matrix.py | python | Matrix.hasCellContent | (self, base_id='cell') | return 0 | Checks if matrix corresponding to base_id contains cells. | Checks if matrix corresponding to base_id contains cells. | [
"Checks",
"if",
"matrix",
"corresponding",
"to",
"base_id",
"contains",
"cells",
"."
] | def hasCellContent(self, base_id='cell'):
"""
Checks if matrix corresponding to base_id contains cells.
"""
aq_self = aq_base(self)
if getattr(aq_self, 'index', None) is None:
return 0
if not self.index.has_key(base_id):
return 0
for i in self.getCellIds(base_id=base_id):
if hasattr(self, i): # We should try to use aq_self if possible but XXX
return 1
return 0 | [
"def",
"hasCellContent",
"(",
"self",
",",
"base_id",
"=",
"'cell'",
")",
":",
"aq_self",
"=",
"aq_base",
"(",
"self",
")",
"if",
"getattr",
"(",
"aq_self",
",",
"'index'",
",",
"None",
")",
"is",
"None",
":",
"return",
"0",
"if",
"not",
"self",
".",
"index",
".",
"has_key",
"(",
"base_id",
")",
":",
"return",
"0",
"for",
"i",
"in",
"self",
".",
"getCellIds",
"(",
"base_id",
"=",
"base_id",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"i",
")",
":",
"# We should try to use aq_self if possible but XXX",
"return",
"1",
"return",
"0"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Type/mixin/matrix.py#L91-L107 |
|
stdlib-js/stdlib | e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df | lib/node_modules/@stdlib/stats/base/dists/beta/quantile/benchmark/python/benchmark.scipy.py | python | print_results | (elapsed) | Print benchmark results.
# Arguments
* `elapsed`: elapsed time (in seconds)
# Examples
``` python
python> print_results(0.131009101868)
``` | Print benchmark results. | [
"Print",
"benchmark",
"results",
"."
] | def print_results(elapsed):
"""Print benchmark results.
# Arguments
* `elapsed`: elapsed time (in seconds)
# Examples
``` python
python> print_results(0.131009101868)
```
"""
rate = ITERATIONS / elapsed
print(" ---")
print(" iterations: " + str(ITERATIONS))
print(" elapsed: " + str(elapsed))
print(" rate: " + str(rate))
print(" ...") | [
"def",
"print_results",
"(",
"elapsed",
")",
":",
"rate",
"=",
"ITERATIONS",
"/",
"elapsed",
"print",
"(",
"\" ---\"",
")",
"print",
"(",
"\" iterations: \"",
"+",
"str",
"(",
"ITERATIONS",
")",
")",
"print",
"(",
"\" elapsed: \"",
"+",
"str",
"(",
"elapsed",
")",
")",
"print",
"(",
"\" rate: \"",
"+",
"str",
"(",
"rate",
")",
")",
"print",
"(",
"\" ...\"",
")"
] | https://github.com/stdlib-js/stdlib/blob/e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df/lib/node_modules/@stdlib/stats/base/dists/beta/quantile/benchmark/python/benchmark.scipy.py#L51-L70 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/v8/gypfiles/vs_toolchain.py | python | _CopyRuntime2015 | (target_dir, source_dir, dll_pattern, suffix) | Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't
exist, but the target directory does exist. | Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't
exist, but the target directory does exist. | [
"Copy",
"both",
"the",
"msvcp",
"and",
"vccorlib",
"runtime",
"DLLs",
"only",
"if",
"the",
"target",
"doesn",
"t",
"exist",
"but",
"the",
"target",
"directory",
"does",
"exist",
"."
] | def _CopyRuntime2015(target_dir, source_dir, dll_pattern, suffix):
"""Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't
exist, but the target directory does exist."""
for file_part in ('msvcp', 'vccorlib', 'vcruntime'):
dll = dll_pattern % file_part
target = os.path.join(target_dir, dll)
source = os.path.join(source_dir, dll)
_CopyRuntimeImpl(target, source)
ucrt_src_dir = os.path.join(source_dir, 'api-ms-win-*.dll')
print 'Copying %s to %s...' % (ucrt_src_dir, target_dir)
for ucrt_src_file in glob.glob(ucrt_src_dir):
file_part = os.path.basename(ucrt_src_file)
ucrt_dst_file = os.path.join(target_dir, file_part)
_CopyRuntimeImpl(ucrt_dst_file, ucrt_src_file, False)
_CopyRuntimeImpl(os.path.join(target_dir, 'ucrtbase' + suffix),
os.path.join(source_dir, 'ucrtbase' + suffix)) | [
"def",
"_CopyRuntime2015",
"(",
"target_dir",
",",
"source_dir",
",",
"dll_pattern",
",",
"suffix",
")",
":",
"for",
"file_part",
"in",
"(",
"'msvcp'",
",",
"'vccorlib'",
",",
"'vcruntime'",
")",
":",
"dll",
"=",
"dll_pattern",
"%",
"file_part",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"dll",
")",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"dll",
")",
"_CopyRuntimeImpl",
"(",
"target",
",",
"source",
")",
"ucrt_src_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"'api-ms-win-*.dll'",
")",
"print",
"'Copying %s to %s...'",
"%",
"(",
"ucrt_src_dir",
",",
"target_dir",
")",
"for",
"ucrt_src_file",
"in",
"glob",
".",
"glob",
"(",
"ucrt_src_dir",
")",
":",
"file_part",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"ucrt_src_file",
")",
"ucrt_dst_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"file_part",
")",
"_CopyRuntimeImpl",
"(",
"ucrt_dst_file",
",",
"ucrt_src_file",
",",
"False",
")",
"_CopyRuntimeImpl",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"'ucrtbase'",
"+",
"suffix",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"'ucrtbase'",
"+",
"suffix",
")",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/v8/gypfiles/vs_toolchain.py#L181-L196 |
||
eweitz/ideogram | f8a2644c9eada64a0d845f153d57226a8e73f21b | scripts/python/cache/gene_cache.py | python | GeneCache.write | (self, genes, organism, prefix, gtf_url) | Save fetched and transformed gene data to cache file | Save fetched and transformed gene data to cache file | [
"Save",
"fetched",
"and",
"transformed",
"gene",
"data",
"to",
"cache",
"file"
] | def write(self, genes, organism, prefix, gtf_url):
"""Save fetched and transformed gene data to cache file
"""
headers = (
f"## Ideogram.js gene cache for {organism}\n" +
f"## Derived from {gtf_url}\n"
f"## prefix: {prefix}\n"
f"# chr\tstart\tlength\tslim_id\tsymbol\n"
)
gene_lines = "\n".join(["\t".join(g) for g in genes])
content = headers + gene_lines
org_lch = organism.lower().replace(" ", "-")
output_path = f"{self.output_dir}{org_lch}-genes.tsv"
with open(output_path, "w") as f:
f.write(content)
print(f"Wrote gene cache: {output_path}") | [
"def",
"write",
"(",
"self",
",",
"genes",
",",
"organism",
",",
"prefix",
",",
"gtf_url",
")",
":",
"headers",
"=",
"(",
"f\"## Ideogram.js gene cache for {organism}\\n\"",
"+",
"f\"## Derived from {gtf_url}\\n\"",
"f\"## prefix: {prefix}\\n\"",
"f\"# chr\\tstart\\tlength\\tslim_id\\tsymbol\\n\"",
")",
"gene_lines",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"\\t\"",
".",
"join",
"(",
"g",
")",
"for",
"g",
"in",
"genes",
"]",
")",
"content",
"=",
"headers",
"+",
"gene_lines",
"org_lch",
"=",
"organism",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"-\"",
")",
"output_path",
"=",
"f\"{self.output_dir}{org_lch}-genes.tsv\"",
"with",
"open",
"(",
"output_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")",
"print",
"(",
"f\"Wrote gene cache: {output_path}\"",
")"
] | https://github.com/eweitz/ideogram/blob/f8a2644c9eada64a0d845f153d57226a8e73f21b/scripts/python/cache/gene_cache.py#L231-L247 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/json/__init__.py | python | dump | (obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw) | Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. | Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object). | [
"Serialize",
"obj",
"as",
"a",
"JSON",
"formatted",
"stream",
"to",
"fp",
"(",
"a",
".",
"write",
"()",
"-",
"supporting",
"file",
"-",
"like",
"object",
")",
"."
] | def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding,
default=default, **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk) | [
"def",
"dump",
"(",
"obj",
",",
"fp",
",",
"skipkeys",
"=",
"False",
",",
"ensure_ascii",
"=",
"True",
",",
"check_circular",
"=",
"True",
",",
"allow_nan",
"=",
"True",
",",
"cls",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"# cached encoder",
"if",
"(",
"not",
"skipkeys",
"and",
"ensure_ascii",
"and",
"check_circular",
"and",
"allow_nan",
"and",
"cls",
"is",
"None",
"and",
"indent",
"is",
"None",
"and",
"separators",
"is",
"None",
"and",
"encoding",
"==",
"'utf-8'",
"and",
"default",
"is",
"None",
"and",
"not",
"kw",
")",
":",
"iterable",
"=",
"_default_encoder",
".",
"iterencode",
"(",
"obj",
")",
"else",
":",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"JSONEncoder",
"iterable",
"=",
"cls",
"(",
"skipkeys",
"=",
"skipkeys",
",",
"ensure_ascii",
"=",
"ensure_ascii",
",",
"check_circular",
"=",
"check_circular",
",",
"allow_nan",
"=",
"allow_nan",
",",
"indent",
"=",
"indent",
",",
"separators",
"=",
"separators",
",",
"encoding",
"=",
"encoding",
",",
"default",
"=",
"default",
",",
"*",
"*",
"kw",
")",
".",
"iterencode",
"(",
"obj",
")",
"# could accelerate with writelines in some versions of Python, at",
"# a debuggability cost",
"for",
"chunk",
"in",
"iterable",
":",
"fp",
".",
"write",
"(",
"chunk",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/json/__init__.py#L122-L182 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/distutils/command/register.py | python | register.send_metadata | (self) | Send the metadata to the package index server.
Well, do the following:
1. figure who the user is, and then
2. send the data as a Basic auth'ed POST.
First we try to read the username/password from $HOME/.pypirc,
which is a ConfigParser-formatted file with a section
[distutils] containing username and password entries (both
in clear text). Eg:
[distutils]
index-servers =
pypi
[pypi]
username: fred
password: sekrit
Otherwise, to figure who the user is, we offer the user three
choices:
1. use existing login,
2. register as a new user, or
3. set the password to a random string and email the user. | Send the metadata to the package index server. | [
"Send",
"the",
"metadata",
"to",
"the",
"package",
"index",
"server",
"."
] | def send_metadata(self):
''' Send the metadata to the package index server.
Well, do the following:
1. figure who the user is, and then
2. send the data as a Basic auth'ed POST.
First we try to read the username/password from $HOME/.pypirc,
which is a ConfigParser-formatted file with a section
[distutils] containing username and password entries (both
in clear text). Eg:
[distutils]
index-servers =
pypi
[pypi]
username: fred
password: sekrit
Otherwise, to figure who the user is, we offer the user three
choices:
1. use existing login,
2. register as a new user, or
3. set the password to a random string and email the user.
'''
# see if we can short-cut and get the username/password from the
# config
if self.has_config:
choice = '1'
username = self.username
password = self.password
else:
choice = 'x'
username = password = ''
# get the user's login info
choices = '1 2 3 4'.split()
while choice not in choices:
self.announce('''\
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
Your selection [default 1]: ''', log.INFO)
choice = raw_input()
if not choice:
choice = '1'
elif choice not in choices:
print 'Please choose one of the four options!'
if choice == '1':
# get the username and password
while not username:
username = raw_input('Username: ')
while not password:
password = getpass.getpass('Password: ')
# set up the authentication
auth = urllib2.HTTPPasswordMgr()
host = urlparse.urlparse(self.repository)[1]
auth.add_password(self.realm, host, username, password)
# send the info to the server and report the result
code, result = self.post_to_server(self.build_post_data('submit'),
auth)
self.announce('Server response (%s): %s' % (code, result),
log.INFO)
# possibly save the login
if code == 200:
if self.has_config:
# sharing the password in the distribution instance
# so the upload command can reuse it
self.distribution.password = password
else:
self.announce(('I can store your PyPI login so future '
'submissions will be faster.'), log.INFO)
self.announce('(the login will be stored in %s)' % \
self._get_rc_file(), log.INFO)
choice = 'X'
while choice.lower() not in 'yn':
choice = raw_input('Save your login (y/N)?')
if not choice:
choice = 'n'
if choice.lower() == 'y':
self._store_pypirc(username, password)
elif choice == '2':
data = {':action': 'user'}
data['name'] = data['password'] = data['email'] = ''
data['confirm'] = None
while not data['name']:
data['name'] = raw_input('Username: ')
while data['password'] != data['confirm']:
while not data['password']:
data['password'] = getpass.getpass('Password: ')
while not data['confirm']:
data['confirm'] = getpass.getpass(' Confirm: ')
if data['password'] != data['confirm']:
data['password'] = ''
data['confirm'] = None
print "Password and confirm don't match!"
while not data['email']:
data['email'] = raw_input(' EMail: ')
code, result = self.post_to_server(data)
if code != 200:
log.info('Server response (%s): %s' % (code, result))
else:
log.info('You will receive an email shortly.')
log.info(('Follow the instructions in it to '
'complete registration.'))
elif choice == '3':
data = {':action': 'password_reset'}
data['email'] = ''
while not data['email']:
data['email'] = raw_input('Your email address: ')
code, result = self.post_to_server(data)
log.info('Server response (%s): %s' % (code, result)) | [
"def",
"send_metadata",
"(",
"self",
")",
":",
"# see if we can short-cut and get the username/password from the",
"# config",
"if",
"self",
".",
"has_config",
":",
"choice",
"=",
"'1'",
"username",
"=",
"self",
".",
"username",
"password",
"=",
"self",
".",
"password",
"else",
":",
"choice",
"=",
"'x'",
"username",
"=",
"password",
"=",
"''",
"# get the user's login info",
"choices",
"=",
"'1 2 3 4'",
".",
"split",
"(",
")",
"while",
"choice",
"not",
"in",
"choices",
":",
"self",
".",
"announce",
"(",
"'''\\\nWe need to know who you are, so please choose either:\n 1. use your existing login,\n 2. register as a new user,\n 3. have the server generate a new password for you (and email it to you), or\n 4. quit\nYour selection [default 1]: '''",
",",
"log",
".",
"INFO",
")",
"choice",
"=",
"raw_input",
"(",
")",
"if",
"not",
"choice",
":",
"choice",
"=",
"'1'",
"elif",
"choice",
"not",
"in",
"choices",
":",
"print",
"'Please choose one of the four options!'",
"if",
"choice",
"==",
"'1'",
":",
"# get the username and password",
"while",
"not",
"username",
":",
"username",
"=",
"raw_input",
"(",
"'Username: '",
")",
"while",
"not",
"password",
":",
"password",
"=",
"getpass",
".",
"getpass",
"(",
"'Password: '",
")",
"# set up the authentication",
"auth",
"=",
"urllib2",
".",
"HTTPPasswordMgr",
"(",
")",
"host",
"=",
"urlparse",
".",
"urlparse",
"(",
"self",
".",
"repository",
")",
"[",
"1",
"]",
"auth",
".",
"add_password",
"(",
"self",
".",
"realm",
",",
"host",
",",
"username",
",",
"password",
")",
"# send the info to the server and report the result",
"code",
",",
"result",
"=",
"self",
".",
"post_to_server",
"(",
"self",
".",
"build_post_data",
"(",
"'submit'",
")",
",",
"auth",
")",
"self",
".",
"announce",
"(",
"'Server response (%s): %s'",
"%",
"(",
"code",
",",
"result",
")",
",",
"log",
".",
"INFO",
")",
"# possibly save the login",
"if",
"code",
"==",
"200",
":",
"if",
"self",
".",
"has_config",
":",
"# sharing the password in the distribution instance",
"# so the upload command can reuse it",
"self",
".",
"distribution",
".",
"password",
"=",
"password",
"else",
":",
"self",
".",
"announce",
"(",
"(",
"'I can store your PyPI login so future '",
"'submissions will be faster.'",
")",
",",
"log",
".",
"INFO",
")",
"self",
".",
"announce",
"(",
"'(the login will be stored in %s)'",
"%",
"self",
".",
"_get_rc_file",
"(",
")",
",",
"log",
".",
"INFO",
")",
"choice",
"=",
"'X'",
"while",
"choice",
".",
"lower",
"(",
")",
"not",
"in",
"'yn'",
":",
"choice",
"=",
"raw_input",
"(",
"'Save your login (y/N)?'",
")",
"if",
"not",
"choice",
":",
"choice",
"=",
"'n'",
"if",
"choice",
".",
"lower",
"(",
")",
"==",
"'y'",
":",
"self",
".",
"_store_pypirc",
"(",
"username",
",",
"password",
")",
"elif",
"choice",
"==",
"'2'",
":",
"data",
"=",
"{",
"':action'",
":",
"'user'",
"}",
"data",
"[",
"'name'",
"]",
"=",
"data",
"[",
"'password'",
"]",
"=",
"data",
"[",
"'email'",
"]",
"=",
"''",
"data",
"[",
"'confirm'",
"]",
"=",
"None",
"while",
"not",
"data",
"[",
"'name'",
"]",
":",
"data",
"[",
"'name'",
"]",
"=",
"raw_input",
"(",
"'Username: '",
")",
"while",
"data",
"[",
"'password'",
"]",
"!=",
"data",
"[",
"'confirm'",
"]",
":",
"while",
"not",
"data",
"[",
"'password'",
"]",
":",
"data",
"[",
"'password'",
"]",
"=",
"getpass",
".",
"getpass",
"(",
"'Password: '",
")",
"while",
"not",
"data",
"[",
"'confirm'",
"]",
":",
"data",
"[",
"'confirm'",
"]",
"=",
"getpass",
".",
"getpass",
"(",
"' Confirm: '",
")",
"if",
"data",
"[",
"'password'",
"]",
"!=",
"data",
"[",
"'confirm'",
"]",
":",
"data",
"[",
"'password'",
"]",
"=",
"''",
"data",
"[",
"'confirm'",
"]",
"=",
"None",
"print",
"\"Password and confirm don't match!\"",
"while",
"not",
"data",
"[",
"'email'",
"]",
":",
"data",
"[",
"'email'",
"]",
"=",
"raw_input",
"(",
"' EMail: '",
")",
"code",
",",
"result",
"=",
"self",
".",
"post_to_server",
"(",
"data",
")",
"if",
"code",
"!=",
"200",
":",
"log",
".",
"info",
"(",
"'Server response (%s): %s'",
"%",
"(",
"code",
",",
"result",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'You will receive an email shortly.'",
")",
"log",
".",
"info",
"(",
"(",
"'Follow the instructions in it to '",
"'complete registration.'",
")",
")",
"elif",
"choice",
"==",
"'3'",
":",
"data",
"=",
"{",
"':action'",
":",
"'password_reset'",
"}",
"data",
"[",
"'email'",
"]",
"=",
"''",
"while",
"not",
"data",
"[",
"'email'",
"]",
":",
"data",
"[",
"'email'",
"]",
"=",
"raw_input",
"(",
"'Your email address: '",
")",
"code",
",",
"result",
"=",
"self",
".",
"post_to_server",
"(",
"data",
")",
"log",
".",
"info",
"(",
"'Server response (%s): %s'",
"%",
"(",
"code",
",",
"result",
")",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/distutils/command/register.py#L101-L222 |
||
klaasnicolaas/Smarthome-homeassistant-config | 610bd35f4e8cdb4a1f41165b0ccb9251c76f5644 | custom_components/hacs/helpers/get_defaults.py | python | get_default_repos_orgs | (github: type(GitHub), category: str) | return repositories | Gets default org repositories. | Gets default org repositories. | [
"Gets",
"default",
"org",
"repositories",
"."
] | async def get_default_repos_orgs(github: type(GitHub), category: str) -> dict:
"""Gets default org repositories."""
repositories = []
logger = Logger("hacs")
orgs = {
"plugin": "custom-cards",
"integration": "custom-components",
"theme": "home-assistant-community-themes",
}
if category not in orgs:
return repositories
try:
repos = await github.get_org_repos(orgs[category])
for repo in repos:
repositories.append(repo.full_name)
except AIOGitHubAPIException as exception:
logger.error(exception)
return repositories | [
"async",
"def",
"get_default_repos_orgs",
"(",
"github",
":",
"type",
"(",
"GitHub",
")",
",",
"category",
":",
"str",
")",
"->",
"dict",
":",
"repositories",
"=",
"[",
"]",
"logger",
"=",
"Logger",
"(",
"\"hacs\"",
")",
"orgs",
"=",
"{",
"\"plugin\"",
":",
"\"custom-cards\"",
",",
"\"integration\"",
":",
"\"custom-components\"",
",",
"\"theme\"",
":",
"\"home-assistant-community-themes\"",
",",
"}",
"if",
"category",
"not",
"in",
"orgs",
":",
"return",
"repositories",
"try",
":",
"repos",
"=",
"await",
"github",
".",
"get_org_repos",
"(",
"orgs",
"[",
"category",
"]",
")",
"for",
"repo",
"in",
"repos",
":",
"repositories",
".",
"append",
"(",
"repo",
".",
"full_name",
")",
"except",
"AIOGitHubAPIException",
"as",
"exception",
":",
"logger",
".",
"error",
"(",
"exception",
")",
"return",
"repositories"
] | https://github.com/klaasnicolaas/Smarthome-homeassistant-config/blob/610bd35f4e8cdb4a1f41165b0ccb9251c76f5644/custom_components/hacs/helpers/get_defaults.py#L9-L29 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py | python | InvertRelativePath | (path, toplevel_dir=None) | return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path)) | Given a path like foo/bar that is relative to toplevel_dir, return
the inverse relative path back to the toplevel_dir.
E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
should always produce the empty string, unless the path contains symlinks. | Given a path like foo/bar that is relative to toplevel_dir, return
the inverse relative path back to the toplevel_dir. | [
"Given",
"a",
"path",
"like",
"foo",
"/",
"bar",
"that",
"is",
"relative",
"to",
"toplevel_dir",
"return",
"the",
"inverse",
"relative",
"path",
"back",
"to",
"the",
"toplevel_dir",
"."
] | def InvertRelativePath(path, toplevel_dir=None):
"""Given a path like foo/bar that is relative to toplevel_dir, return
the inverse relative path back to the toplevel_dir.
E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
should always produce the empty string, unless the path contains symlinks.
"""
if not path:
return path
toplevel_dir = "." if toplevel_dir is None else toplevel_dir
return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path)) | [
"def",
"InvertRelativePath",
"(",
"path",
",",
"toplevel_dir",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"path",
"toplevel_dir",
"=",
"\".\"",
"if",
"toplevel_dir",
"is",
"None",
"else",
"toplevel_dir",
"return",
"RelativePath",
"(",
"toplevel_dir",
",",
"os",
".",
"path",
".",
"join",
"(",
"toplevel_dir",
",",
"path",
")",
")"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py#L184-L194 |
|
jumpserver/coco | 0b2ae31eb2221127ab81775a4f985bf00abaec45 | coco/conf.py | python | Config.get_namespace | (self, namespace, lowercase=True, trim_namespace=True) | return rv | Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store_config` would look like::
{
'types': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11 | Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:: | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"subset",
"of",
"configuration",
"options",
"that",
"match",
"the",
"specified",
"namespace",
"/",
"prefix",
".",
"Example",
"usage",
"::"
] | def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store_config` would look like::
{
'types': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11
"""
rv = {}
for k, v in self.items():
if not k.startswith(namespace):
continue
if trim_namespace:
key = k[len(namespace):]
else:
key = k
if lowercase:
key = key.lower()
rv[key] = v
return rv | [
"def",
"get_namespace",
"(",
"self",
",",
"namespace",
",",
"lowercase",
"=",
"True",
",",
"trim_namespace",
"=",
"True",
")",
":",
"rv",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"namespace",
")",
":",
"continue",
"if",
"trim_namespace",
":",
"key",
"=",
"k",
"[",
"len",
"(",
"namespace",
")",
":",
"]",
"else",
":",
"key",
"=",
"k",
"if",
"lowercase",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"rv",
"[",
"key",
"]",
"=",
"v",
"return",
"rv"
] | https://github.com/jumpserver/coco/blob/0b2ae31eb2221127ab81775a4f985bf00abaec45/coco/conf.py#L249-L288 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ZSQLCatalog/SQLCatalog.py | python | Catalog.getColumnMap | (self) | return result | Calls the show column method and returns dictionnary of
Field Ids | Calls the show column method and returns dictionnary of
Field Ids | [
"Calls",
"the",
"show",
"column",
"method",
"and",
"returns",
"dictionnary",
"of",
"Field",
"Ids"
] | def getColumnMap(self):
"""
Calls the show column method and returns dictionnary of
Field Ids
"""
result = {}
table_dict = self._getCatalogSchema()
for table in self.getCatalogSearchTableIds():
for field in table_dict.get(table, ()):
result.setdefault(field, []).append(table)
result.setdefault('%s.%s' % (table, field), []).append(table) # Is this inconsistent ?
return result | [
"def",
"getColumnMap",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"table_dict",
"=",
"self",
".",
"_getCatalogSchema",
"(",
")",
"for",
"table",
"in",
"self",
".",
"getCatalogSearchTableIds",
"(",
")",
":",
"for",
"field",
"in",
"table_dict",
".",
"get",
"(",
"table",
",",
"(",
")",
")",
":",
"result",
".",
"setdefault",
"(",
"field",
",",
"[",
"]",
")",
".",
"append",
"(",
"table",
")",
"result",
".",
"setdefault",
"(",
"'%s.%s'",
"%",
"(",
"table",
",",
"field",
")",
",",
"[",
"]",
")",
".",
"append",
"(",
"table",
")",
"# Is this inconsistent ?",
"return",
"result"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ZSQLCatalog/SQLCatalog.py#L1011-L1022 |
|
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | tools/gyp/pylib/gyp/generator/cmake.py | python | Compilable | (filename) | return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS) | Return true if the file is compilable (should be in OBJS). | Return true if the file is compilable (should be in OBJS). | [
"Return",
"true",
"if",
"the",
"file",
"is",
"compilable",
"(",
"should",
"be",
"in",
"OBJS",
")",
"."
] | def Compilable(filename):
"""Return true if the file is compilable (should be in OBJS)."""
return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS) | [
"def",
"Compilable",
"(",
"filename",
")",
":",
"return",
"any",
"(",
"filename",
".",
"endswith",
"(",
"e",
")",
"for",
"e",
"in",
"COMPILABLE_EXTENSIONS",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/tools/gyp/pylib/gyp/generator/cmake.py#L84-L86 |
|
JoneXiong/DjangoX | c2a723e209ef13595f571923faac7eb29e4c8150 | xadmin/utils/mail.py | python | send_email_with_attachment | (subject, content, emails,
attachment=None, mime='plain',
sender=None, password=None) | return True | Send emails with attachment.
attachment - attachment should have the structure below:
{
"application": "...", // e.g. vnd.ms-excel
"content": 'attachment content",
"Content-Disposition": "...",
// e.g. \'attachment;filename=order_statistics.xls'
} | Send emails with attachment. | [
"Send",
"emails",
"with",
"attachment",
"."
] | def send_email_with_attachment(subject, content, emails,
attachment=None, mime='plain',
sender=None, password=None):
"""Send emails with attachment.
attachment - attachment should have the structure below:
{
"application": "...", // e.g. vnd.ms-excel
"content": 'attachment content",
"Content-Disposition": "...",
// e.g. \'attachment;filename=order_statistics.xls'
}
"""
if not sender:
mail_user = "alarm@mfhui.com"
else:
mail_user = sender
if not password:
mail_pass = "9e134790f32297ad2f1134a816f05258"
else:
mail_pass = password
mail_host = "smtp.exmail.qq.com"
mail_postfix = "@mfhui.com"
sender = '%s<%s@%s>' % (mail_user, mail_user, mail_postfix)
file_msg = None
if attachment:
file_msg = MIMEBase("application",
attachment["application"])
file_msg.set_payload(attachment["content"].getvalue())
attachment["content"].close()
encoders.encode_base64(file_msg)
file_msg.add_header(
"Content-Disposition",
attachment["Content-Disposition"]
)
content_msg = MIMEText(content, mime, "utf-8")
for email in emails:
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = email
msg.attach(content_msg)
# Attach attachment
if file_msg:
msg.attach(file_msg)
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user, mail_pass)
server.sendmail(sender, email, msg.as_string())
server.close()
return True | [
"def",
"send_email_with_attachment",
"(",
"subject",
",",
"content",
",",
"emails",
",",
"attachment",
"=",
"None",
",",
"mime",
"=",
"'plain'",
",",
"sender",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"not",
"sender",
":",
"mail_user",
"=",
"\"alarm@mfhui.com\"",
"else",
":",
"mail_user",
"=",
"sender",
"if",
"not",
"password",
":",
"mail_pass",
"=",
"\"9e134790f32297ad2f1134a816f05258\"",
"else",
":",
"mail_pass",
"=",
"password",
"mail_host",
"=",
"\"smtp.exmail.qq.com\"",
"mail_postfix",
"=",
"\"@mfhui.com\"",
"sender",
"=",
"'%s<%s@%s>'",
"%",
"(",
"mail_user",
",",
"mail_user",
",",
"mail_postfix",
")",
"file_msg",
"=",
"None",
"if",
"attachment",
":",
"file_msg",
"=",
"MIMEBase",
"(",
"\"application\"",
",",
"attachment",
"[",
"\"application\"",
"]",
")",
"file_msg",
".",
"set_payload",
"(",
"attachment",
"[",
"\"content\"",
"]",
".",
"getvalue",
"(",
")",
")",
"attachment",
"[",
"\"content\"",
"]",
".",
"close",
"(",
")",
"encoders",
".",
"encode_base64",
"(",
"file_msg",
")",
"file_msg",
".",
"add_header",
"(",
"\"Content-Disposition\"",
",",
"attachment",
"[",
"\"Content-Disposition\"",
"]",
")",
"content_msg",
"=",
"MIMEText",
"(",
"content",
",",
"mime",
",",
"\"utf-8\"",
")",
"for",
"email",
"in",
"emails",
":",
"msg",
"=",
"MIMEMultipart",
"(",
"\"alternative\"",
")",
"msg",
"[",
"\"Subject\"",
"]",
"=",
"subject",
"msg",
"[",
"\"From\"",
"]",
"=",
"sender",
"msg",
"[",
"\"To\"",
"]",
"=",
"email",
"msg",
".",
"attach",
"(",
"content_msg",
")",
"# Attach attachment",
"if",
"file_msg",
":",
"msg",
".",
"attach",
"(",
"file_msg",
")",
"server",
"=",
"smtplib",
".",
"SMTP",
"(",
")",
"server",
".",
"connect",
"(",
"mail_host",
")",
"server",
".",
"login",
"(",
"mail_user",
",",
"mail_pass",
")",
"server",
".",
"sendmail",
"(",
"sender",
",",
"email",
",",
"msg",
".",
"as_string",
"(",
")",
")",
"server",
".",
"close",
"(",
")",
"return",
"True"
] | https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/utils/mail.py#L40-L95 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | tools/inspector_protocol/jinja2/utils.py | python | LRUCache.setdefault | (self, key, default=None) | Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key. | Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key. | [
"Set",
"default",
"if",
"the",
"key",
"is",
"not",
"in",
"the",
"cache",
"otherwise",
"leave",
"unchanged",
".",
"Return",
"the",
"value",
"of",
"this",
"key",
"."
] | def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._wlock.release() | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"try",
":",
"return",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"self",
"[",
"key",
"]",
"=",
"default",
"return",
"default",
"finally",
":",
"self",
".",
"_wlock",
".",
"release",
"(",
")"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/inspector_protocol/jinja2/utils.py#L355-L367 |
||
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/cpplint.py | python | CleanseComments | (line) | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed. | Removes //-comments and single-line C-style /* */ comments. | [
"Removes",
"//",
"-",
"comments",
"and",
"single",
"-",
"line",
"C",
"-",
"style",
"/",
"*",
"*",
"/",
"comments",
"."
] | def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | [
"def",
"CleanseComments",
"(",
"line",
")",
":",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
"and",
"not",
"IsCppString",
"(",
"line",
"[",
":",
"commentpos",
"]",
")",
":",
"line",
"=",
"line",
"[",
":",
"commentpos",
"]",
".",
"rstrip",
"(",
")",
"# get rid of /* ... */",
"return",
"_RE_PATTERN_CLEANSE_LINE_C_COMMENTS",
".",
"sub",
"(",
"''",
",",
"line",
")"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/cpplint.py#L1342-L1355 |
|
google/earthengine-api | c4b73712ef7f0cbbb3720bd7ae9282530d00c78f | python/ee/mapclient.py | python | MapClient.addOverlay | (self, overlay) | Add an overlay to the map. | Add an overlay to the map. | [
"Add",
"an",
"overlay",
"to",
"the",
"map",
"."
] | def addOverlay(self, overlay): # pylint: disable=g-bad-name
"""Add an overlay to the map."""
self.overlays.append(overlay)
self.LoadTiles() | [
"def",
"addOverlay",
"(",
"self",
",",
"overlay",
")",
":",
"# pylint: disable=g-bad-name",
"self",
".",
"overlays",
".",
"append",
"(",
"overlay",
")",
"self",
".",
"LoadTiles",
"(",
")"
] | https://github.com/google/earthengine-api/blob/c4b73712ef7f0cbbb3720bd7ae9282530d00c78f/python/ee/mapclient.py#L151-L154 |
||
pinterest/pinball | c54a206cf6e3dbadb056c189f741d75828c02f98 | pinball/ui/data_builder.py | python | DataBuilder.get_workflows | (self) | return self._workflows_data_from_job_tokens(all_tokens) | Get all workflows data from the store.
Returns:
List of workflows data. | Get all workflows data from the store. | [
"Get",
"all",
"workflows",
"data",
"from",
"the",
"store",
"."
] | def get_workflows(self):
"""Get all workflows data from the store.
Returns:
List of workflows data.
"""
if self.use_cache:
return self._get_workflows_using_cache()
all_tokens = self._get_job_tokens()
if not all_tokens:
return []
return self._workflows_data_from_job_tokens(all_tokens) | [
"def",
"get_workflows",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_cache",
":",
"return",
"self",
".",
"_get_workflows_using_cache",
"(",
")",
"all_tokens",
"=",
"self",
".",
"_get_job_tokens",
"(",
")",
"if",
"not",
"all_tokens",
":",
"return",
"[",
"]",
"return",
"self",
".",
"_workflows_data_from_job_tokens",
"(",
"all_tokens",
")"
] | https://github.com/pinterest/pinball/blob/c54a206cf6e3dbadb056c189f741d75828c02f98/pinball/ui/data_builder.py#L569-L580 |
|
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/stubs/_django_manager_body.py | python | create | (self, *args, **kwargs) | Creates a new object with the given kwargs, saving it to the database
and returning the created object. | Creates a new object with the given kwargs, saving it to the database
and returning the created object. | [
"Creates",
"a",
"new",
"object",
"with",
"the",
"given",
"kwargs",
"saving",
"it",
"to",
"the",
"database",
"and",
"returning",
"the",
"created",
"object",
"."
] | def create(self, *args, **kwargs):
"""
Creates a new object with the given kwargs, saving it to the database
and returning the created object.
""" | [
"def",
"create",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/stubs/_django_manager_body.py#L145-L149 |
||
domogik/domogik | fefd584d354875bcb15f351cbc455abffaa6501f | src/domogik/common/configloader.py | python | Loader.set | (self, section, key, value) | Set a key value for a section in config file and write it
WARNING : using this function make config fil change :
- items are reordered
- comments are lost
@param section : section of config file
@param key : key
@param value : value | Set a key value for a section in config file and write it
WARNING : using this function make config fil change :
- items are reordered
- comments are lost | [
"Set",
"a",
"key",
"value",
"for",
"a",
"section",
"in",
"config",
"file",
"and",
"write",
"it",
"WARNING",
":",
"using",
"this",
"function",
"make",
"config",
"fil",
"change",
":",
"-",
"items",
"are",
"reordered",
"-",
"comments",
"are",
"lost"
] | def set(self, section, key, value):
""" Set a key value for a section in config file and write it
WARNING : using this function make config fil change :
- items are reordered
- comments are lost
@param section : section of config file
@param key : key
@param value : value
"""
# Check load is called before this function
if self.config is None:
raise Exception("ConfigLoader : you must use load() before set() function")
self.config.set(section, key, value)
with open(self.cfile, "wb") as configfile:
self.config.write(configfile) | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
")",
":",
"# Check load is called before this function",
"if",
"self",
".",
"config",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"ConfigLoader : you must use load() before set() function\"",
")",
"self",
".",
"config",
".",
"set",
"(",
"section",
",",
"key",
",",
"value",
")",
"with",
"open",
"(",
"self",
".",
"cfile",
",",
"\"wb\"",
")",
"as",
"configfile",
":",
"self",
".",
"config",
".",
"write",
"(",
"configfile",
")"
] | https://github.com/domogik/domogik/blob/fefd584d354875bcb15f351cbc455abffaa6501f/src/domogik/common/configloader.py#L145-L159 |
||
HumanCompatibleAI/overcooked_ai | 7e774a1aa29c28b7b69dc0a8903822ac2c6b4f23 | src/overcooked_ai_py/mdp/overcooked_mdp.py | python | OvercookedGridworld.compute_new_positions_and_orientations | (self, old_player_states, joint_action) | return new_positions, new_orientations | Compute new positions and orientations ignoring collisions | Compute new positions and orientations ignoring collisions | [
"Compute",
"new",
"positions",
"and",
"orientations",
"ignoring",
"collisions"
] | def compute_new_positions_and_orientations(self, old_player_states, joint_action):
"""Compute new positions and orientations ignoring collisions"""
new_positions, new_orientations = list(zip(*[
self._move_if_direction(p.position, p.orientation, a) \
for p, a in zip(old_player_states, joint_action)]))
old_positions = tuple(p.position for p in old_player_states)
new_positions = self._handle_collisions(old_positions, new_positions)
return new_positions, new_orientations | [
"def",
"compute_new_positions_and_orientations",
"(",
"self",
",",
"old_player_states",
",",
"joint_action",
")",
":",
"new_positions",
",",
"new_orientations",
"=",
"list",
"(",
"zip",
"(",
"*",
"[",
"self",
".",
"_move_if_direction",
"(",
"p",
".",
"position",
",",
"p",
".",
"orientation",
",",
"a",
")",
"for",
"p",
",",
"a",
"in",
"zip",
"(",
"old_player_states",
",",
"joint_action",
")",
"]",
")",
")",
"old_positions",
"=",
"tuple",
"(",
"p",
".",
"position",
"for",
"p",
"in",
"old_player_states",
")",
"new_positions",
"=",
"self",
".",
"_handle_collisions",
"(",
"old_positions",
",",
"new_positions",
")",
"return",
"new_positions",
",",
"new_orientations"
] | https://github.com/HumanCompatibleAI/overcooked_ai/blob/7e774a1aa29c28b7b69dc0a8903822ac2c6b4f23/src/overcooked_ai_py/mdp/overcooked_mdp.py#L1262-L1269 |
|
jingning42/ustc-course | a5b3c7adfae593dc668b84c85a8ecf15b95b470a | app/models/user.py | python | User.authenticate | (cls,login,password) | return user, authenticated, user.confirmed if user else False | A classmethod for authenticating users
It returns true if the user exists and has entered a correct password
:param login: This can be either a username or a email address.
:param password: The password that is connected to username and email. | A classmethod for authenticating users
It returns true if the user exists and has entered a correct password
:param login: This can be either a username or a email address.
:param password: The password that is connected to username and email. | [
"A",
"classmethod",
"for",
"authenticating",
"users",
"It",
"returns",
"true",
"if",
"the",
"user",
"exists",
"and",
"has",
"entered",
"a",
"correct",
"password",
":",
"param",
"login",
":",
"This",
"can",
"be",
"either",
"a",
"username",
"or",
"a",
"email",
"address",
".",
":",
"param",
"password",
":",
"The",
"password",
"that",
"is",
"connected",
"to",
"username",
"and",
"email",
"."
] | def authenticate(cls,login,password):
"""A classmethod for authenticating users
It returns true if the user exists and has entered a correct password
:param login: This can be either a username or a email address.
:param password: The password that is connected to username and email.
"""
user = cls.query.filter(db.or_(User.username == login,
User.email == login)).first()
if user and user.confirmed:
authenticated = user.check_password(password)
else:
authenticated = False
return user, authenticated, user.confirmed if user else False | [
"def",
"authenticate",
"(",
"cls",
",",
"login",
",",
"password",
")",
":",
"user",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"db",
".",
"or_",
"(",
"User",
".",
"username",
"==",
"login",
",",
"User",
".",
"email",
"==",
"login",
")",
")",
".",
"first",
"(",
")",
"if",
"user",
"and",
"user",
".",
"confirmed",
":",
"authenticated",
"=",
"user",
".",
"check_password",
"(",
"password",
")",
"else",
":",
"authenticated",
"=",
"False",
"return",
"user",
",",
"authenticated",
",",
"user",
".",
"confirmed",
"if",
"user",
"else",
"False"
] | https://github.com/jingning42/ustc-course/blob/a5b3c7adfae593dc668b84c85a8ecf15b95b470a/app/models/user.py#L219-L233 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | deps/v8/third_party/jinja2/utils.py | python | Cycler.reset | (self) | Resets the current item to the first item. | Resets the current item to the first item. | [
"Resets",
"the",
"current",
"item",
"to",
"the",
"first",
"item",
"."
] | def reset(self):
"""Resets the current item to the first item."""
self.pos = 0 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"pos",
"=",
"0"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/deps/v8/third_party/jinja2/utils.py#L660-L662 |
||
nodejs/node-convergence-archive | e11fe0c2777561827cdb7207d46b0917ef3c42a7 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | PBXCopyFilesBuildPhase.SetDestination | (self, path) | Set the dstSubfolderSpec and dstPath properties from path.
path may be specified in the same notation used for XCHierarchicalElements,
specifically, "$(DIR)/path". | Set the dstSubfolderSpec and dstPath properties from path. | [
"Set",
"the",
"dstSubfolderSpec",
"and",
"dstPath",
"properties",
"from",
"path",
"."
] | def SetDestination(self, path):
"""Set the dstSubfolderSpec and dstPath properties from path.
path may be specified in the same notation used for XCHierarchicalElements,
specifically, "$(DIR)/path".
"""
path_tree_match = self.path_tree_re.search(path)
if path_tree_match:
# Everything else needs to be relative to an Xcode variable.
path_tree = path_tree_match.group(1)
relative_path = path_tree_match.group(3)
if path_tree in self.path_tree_to_subfolder:
subfolder = self.path_tree_to_subfolder[path_tree]
if relative_path is None:
relative_path = ''
else:
# The path starts with an unrecognized Xcode variable
# name like $(SRCROOT). Xcode will still handle this
# as an "absolute path" that starts with the variable.
subfolder = 0
relative_path = path
elif path.startswith('/'):
# Special case. Absolute paths are in dstSubfolderSpec 0.
subfolder = 0
relative_path = path[1:]
else:
raise ValueError, 'Can\'t use path %s in a %s' % \
(path, self.__class__.__name__)
self._properties['dstPath'] = relative_path
self._properties['dstSubfolderSpec'] = subfolder | [
"def",
"SetDestination",
"(",
"self",
",",
"path",
")",
":",
"path_tree_match",
"=",
"self",
".",
"path_tree_re",
".",
"search",
"(",
"path",
")",
"if",
"path_tree_match",
":",
"# Everything else needs to be relative to an Xcode variable.",
"path_tree",
"=",
"path_tree_match",
".",
"group",
"(",
"1",
")",
"relative_path",
"=",
"path_tree_match",
".",
"group",
"(",
"3",
")",
"if",
"path_tree",
"in",
"self",
".",
"path_tree_to_subfolder",
":",
"subfolder",
"=",
"self",
".",
"path_tree_to_subfolder",
"[",
"path_tree",
"]",
"if",
"relative_path",
"is",
"None",
":",
"relative_path",
"=",
"''",
"else",
":",
"# The path starts with an unrecognized Xcode variable",
"# name like $(SRCROOT). Xcode will still handle this",
"# as an \"absolute path\" that starts with the variable.",
"subfolder",
"=",
"0",
"relative_path",
"=",
"path",
"elif",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# Special case. Absolute paths are in dstSubfolderSpec 0.",
"subfolder",
"=",
"0",
"relative_path",
"=",
"path",
"[",
"1",
":",
"]",
"else",
":",
"raise",
"ValueError",
",",
"'Can\\'t use path %s in a %s'",
"%",
"(",
"path",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"self",
".",
"_properties",
"[",
"'dstPath'",
"]",
"=",
"relative_path",
"self",
".",
"_properties",
"[",
"'dstSubfolderSpec'",
"]",
"=",
"subfolder"
] | https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L1974-L2006 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/decimal.py | python | Decimal.__int__ | (self) | Converts self to an int, truncating if necessary. | Converts self to an int, truncating if necessary. | [
"Converts",
"self",
"to",
"an",
"int",
"truncating",
"if",
"necessary",
"."
] | def __int__(self):
"""Converts self to an int, truncating if necessary."""
if self._is_special:
if self._isnan():
raise ValueError("Cannot convert NaN to integer")
elif self._isinfinity():
raise OverflowError("Cannot convert infinity to integer")
s = (-1)**self._sign
if self._exp >= 0:
return s*int(self._int)*10**self._exp
else:
return s*int(self._int[:self._exp] or '0') | [
"def",
"__int__",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_special",
":",
"if",
"self",
".",
"_isnan",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot convert NaN to integer\"",
")",
"elif",
"self",
".",
"_isinfinity",
"(",
")",
":",
"raise",
"OverflowError",
"(",
"\"Cannot convert infinity to integer\"",
")",
"s",
"=",
"(",
"-",
"1",
")",
"**",
"self",
".",
"_sign",
"if",
"self",
".",
"_exp",
">=",
"0",
":",
"return",
"s",
"*",
"int",
"(",
"self",
".",
"_int",
")",
"*",
"10",
"**",
"self",
".",
"_exp",
"else",
":",
"return",
"s",
"*",
"int",
"(",
"self",
".",
"_int",
"[",
":",
"self",
".",
"_exp",
"]",
"or",
"'0'",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/decimal.py#L1586-L1597 |
||
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Packages/python-markdown/st3/markdown/blockparser.py | python | BlockParser.parseBlocks | (self, parent, blocks) | Process blocks of markdown text and attach to given etree node.
Given a list of ``blocks``, each blockprocessor is stepped through
until there are no blocks left. While an extension could potentially
call this method directly, it's generally expected to be used
internally.
This is a public method as an extension may need to add/alter
additional BlockProcessors which call this method to recursively
parse a nested block. | Process blocks of markdown text and attach to given etree node. | [
"Process",
"blocks",
"of",
"markdown",
"text",
"and",
"attach",
"to",
"given",
"etree",
"node",
"."
] | def parseBlocks(self, parent, blocks):
""" Process blocks of markdown text and attach to given etree node.
Given a list of ``blocks``, each blockprocessor is stepped through
until there are no blocks left. While an extension could potentially
call this method directly, it's generally expected to be used
internally.
This is a public method as an extension may need to add/alter
additional BlockProcessors which call this method to recursively
parse a nested block.
"""
while blocks:
for processor in self.blockprocessors.values():
if processor.test(parent, blocks[0]):
if processor.run(parent, blocks) is not False:
# run returns True or None
break | [
"def",
"parseBlocks",
"(",
"self",
",",
"parent",
",",
"blocks",
")",
":",
"while",
"blocks",
":",
"for",
"processor",
"in",
"self",
".",
"blockprocessors",
".",
"values",
"(",
")",
":",
"if",
"processor",
".",
"test",
"(",
"parent",
",",
"blocks",
"[",
"0",
"]",
")",
":",
"if",
"processor",
".",
"run",
"(",
"parent",
",",
"blocks",
")",
"is",
"not",
"False",
":",
"# run returns True or None",
"break"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/python-markdown/st3/markdown/blockparser.py#L82-L100 |
||
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ERP5Form/CaptchaField.py | python | ICaptchaProvider.generate | (self, field) | Returns a tuple (key, valid_answer) for this captcha.
That key is never sent directly to the client, it is always hashed before. | Returns a tuple (key, valid_answer) for this captcha.
That key is never sent directly to the client, it is always hashed before. | [
"Returns",
"a",
"tuple",
"(",
"key",
"valid_answer",
")",
"for",
"this",
"captcha",
".",
"That",
"key",
"is",
"never",
"sent",
"directly",
"to",
"the",
"client",
"it",
"is",
"always",
"hashed",
"before",
"."
] | def generate(self, field):
"""Returns a tuple (key, valid_answer) for this captcha.
That key is never sent directly to the client, it is always hashed before.""" | [
"def",
"generate",
"(",
"self",
",",
"field",
")",
":"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Form/CaptchaField.py#L50-L52 |
||
SEL-Columbia/formhub | 578fc2c5e9febe8dc68b37f7d2e85a76dc2c4c04 | odk_viewer/pandas_mongo_bridge.py | python | AbstractDataFrameBuilder._split_select_multiples | (cls, record, select_multiples) | return record | Prefix contains the xpath and slash if we are within a repeat so that we can figure out which select multiples belong to which repeat | Prefix contains the xpath and slash if we are within a repeat so that we can figure out which select multiples belong to which repeat | [
"Prefix",
"contains",
"the",
"xpath",
"and",
"slash",
"if",
"we",
"are",
"within",
"a",
"repeat",
"so",
"that",
"we",
"can",
"figure",
"out",
"which",
"select",
"multiples",
"belong",
"to",
"which",
"repeat"
] | def _split_select_multiples(cls, record, select_multiples):
""" Prefix contains the xpath and slash if we are within a repeat so that we can figure out which select multiples belong to which repeat
"""
for key, choices in select_multiples.items():
# the select multiple might be blank or not exist in the record, need to make those False
selections = []
if key in record:
# split selected choices by spaces and join by / to the
# element's xpath
selections = ["%s/%s" % (key, r) for r in\
record[key].split(" ")]
# remove the column since we are adding separate columns
# for each choice
record.pop(key)
# add columns to record for every choice, with default
# False and set to True for items in selections
record.update(dict([(choice, choice in selections)\
for choice in choices]))
# recurs into repeats
for record_key, record_item in record.items():
if type(record_item) == list:
for list_item in record_item:
if type(list_item) == dict:
cls._split_select_multiples(list_item,
select_multiples)
return record | [
"def",
"_split_select_multiples",
"(",
"cls",
",",
"record",
",",
"select_multiples",
")",
":",
"for",
"key",
",",
"choices",
"in",
"select_multiples",
".",
"items",
"(",
")",
":",
"# the select multiple might be blank or not exist in the record, need to make those False",
"selections",
"=",
"[",
"]",
"if",
"key",
"in",
"record",
":",
"# split selected choices by spaces and join by / to the",
"# element's xpath",
"selections",
"=",
"[",
"\"%s/%s\"",
"%",
"(",
"key",
",",
"r",
")",
"for",
"r",
"in",
"record",
"[",
"key",
"]",
".",
"split",
"(",
"\" \"",
")",
"]",
"# remove the column since we are adding separate columns",
"# for each choice",
"record",
".",
"pop",
"(",
"key",
")",
"# add columns to record for every choice, with default",
"# False and set to True for items in selections",
"record",
".",
"update",
"(",
"dict",
"(",
"[",
"(",
"choice",
",",
"choice",
"in",
"selections",
")",
"for",
"choice",
"in",
"choices",
"]",
")",
")",
"# recurs into repeats",
"for",
"record_key",
",",
"record_item",
"in",
"record",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"record_item",
")",
"==",
"list",
":",
"for",
"list_item",
"in",
"record_item",
":",
"if",
"type",
"(",
"list_item",
")",
"==",
"dict",
":",
"cls",
".",
"_split_select_multiples",
"(",
"list_item",
",",
"select_multiples",
")",
"return",
"record"
] | https://github.com/SEL-Columbia/formhub/blob/578fc2c5e9febe8dc68b37f7d2e85a76dc2c4c04/odk_viewer/pandas_mongo_bridge.py#L105-L131 |
|
TeamvisionCorp/TeamVision | aa2a57469e430ff50cce21174d8f280efa0a83a7 | distribute/0.0.4/build_shell/teamvision/teamvision/ci/viewmodels/vm_ci_task_basic_section.py | python | VM_BasicSection.__init__ | (self,basic_section) | Constructor | Constructor | [
"Constructor"
] | def __init__(self,basic_section):
'''
Constructor
'''
self.basic_section=basic_section | [
"def",
"__init__",
"(",
"self",
",",
"basic_section",
")",
":",
"self",
".",
"basic_section",
"=",
"basic_section"
] | https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.4/build_shell/teamvision/teamvision/ci/viewmodels/vm_ci_task_basic_section.py#L18-L22 |
||
IonicChina/ioniclub | 208d5298939672ef44076bb8a7e8e6df5278e286 | node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Children | (self) | return children | Returns a list of all of this object's owned (strong) children. | Returns a list of all of this object's owned (strong) children. | [
"Returns",
"a",
"list",
"of",
"all",
"of",
"this",
"object",
"s",
"owned",
"(",
"strong",
")",
"children",
"."
] | def Children(self):
"""Returns a list of all of this object's owned (strong) children."""
children = []
for property, attributes in self._schema.iteritems():
(is_list, property_type, is_strong) = attributes[0:3]
if is_strong and property in self._properties:
if not is_list:
children.append(self._properties[property])
else:
children.extend(self._properties[property])
return children | [
"def",
"Children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"for",
"property",
",",
"attributes",
"in",
"self",
".",
"_schema",
".",
"iteritems",
"(",
")",
":",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
")",
"=",
"attributes",
"[",
"0",
":",
"3",
"]",
"if",
"is_strong",
"and",
"property",
"in",
"self",
".",
"_properties",
":",
"if",
"not",
"is_list",
":",
"children",
".",
"append",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"else",
":",
"children",
".",
"extend",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"return",
"children"
] | https://github.com/IonicChina/ioniclub/blob/208d5298939672ef44076bb8a7e8e6df5278e286/node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/xcodeproj_file.py#L475-L486 |
|
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | deps/jscshim/webkit/Tools/Scripts/webkitpy/common/system/executive.py | python | Executive.run_command | (self,
args,
cwd=None,
env=None,
input=None,
error_handler=None,
ignore_errors=False,
return_exit_code=False,
return_stderr=True,
decode_output=True) | return output | Popen wrapper for convenience and to work around python bugs. | Popen wrapper for convenience and to work around python bugs. | [
"Popen",
"wrapper",
"for",
"convenience",
"and",
"to",
"work",
"around",
"python",
"bugs",
"."
] | def run_command(self,
args,
cwd=None,
env=None,
input=None,
error_handler=None,
ignore_errors=False,
return_exit_code=False,
return_stderr=True,
decode_output=True):
"""Popen wrapper for convenience and to work around python bugs."""
assert(isinstance(args, list) or isinstance(args, tuple))
start_time = time.time()
stdin, string_to_communicate = self._compute_stdin(input)
stderr = self.STDOUT if return_stderr else None
process = self.popen(args,
stdin=stdin,
stdout=self.PIPE,
stderr=stderr,
cwd=cwd,
env=env,
close_fds=self._should_close_fds())
output = process.communicate(string_to_communicate)[0]
# run_command automatically decodes to unicode() and converts CRLF to LF unless explicitly told not to.
if decode_output:
output = output.decode(self._child_process_encoding()).replace('\r\n', '\n')
# wait() is not threadsafe and can throw OSError due to:
# http://bugs.python.org/issue1731717
exit_code = process.wait()
_log.debug('"%s" took %.2fs' % (self.command_for_printing(args), time.time() - start_time))
if return_exit_code:
return exit_code
if exit_code:
script_error = ScriptError(script_args=args,
exit_code=exit_code,
output=output,
cwd=cwd)
if ignore_errors:
assert error_handler is None, "don't specify error_handler if ignore_errors is True"
error_handler = Executive.ignore_error
(error_handler or self.default_error_handler)(script_error)
return output | [
"def",
"run_command",
"(",
"self",
",",
"args",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"input",
"=",
"None",
",",
"error_handler",
"=",
"None",
",",
"ignore_errors",
"=",
"False",
",",
"return_exit_code",
"=",
"False",
",",
"return_stderr",
"=",
"True",
",",
"decode_output",
"=",
"True",
")",
":",
"assert",
"(",
"isinstance",
"(",
"args",
",",
"list",
")",
"or",
"isinstance",
"(",
"args",
",",
"tuple",
")",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"stdin",
",",
"string_to_communicate",
"=",
"self",
".",
"_compute_stdin",
"(",
"input",
")",
"stderr",
"=",
"self",
".",
"STDOUT",
"if",
"return_stderr",
"else",
"None",
"process",
"=",
"self",
".",
"popen",
"(",
"args",
",",
"stdin",
"=",
"stdin",
",",
"stdout",
"=",
"self",
".",
"PIPE",
",",
"stderr",
"=",
"stderr",
",",
"cwd",
"=",
"cwd",
",",
"env",
"=",
"env",
",",
"close_fds",
"=",
"self",
".",
"_should_close_fds",
"(",
")",
")",
"output",
"=",
"process",
".",
"communicate",
"(",
"string_to_communicate",
")",
"[",
"0",
"]",
"# run_command automatically decodes to unicode() and converts CRLF to LF unless explicitly told not to.",
"if",
"decode_output",
":",
"output",
"=",
"output",
".",
"decode",
"(",
"self",
".",
"_child_process_encoding",
"(",
")",
")",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"# wait() is not threadsafe and can throw OSError due to:",
"# http://bugs.python.org/issue1731717",
"exit_code",
"=",
"process",
".",
"wait",
"(",
")",
"_log",
".",
"debug",
"(",
"'\"%s\" took %.2fs'",
"%",
"(",
"self",
".",
"command_for_printing",
"(",
"args",
")",
",",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
")",
"if",
"return_exit_code",
":",
"return",
"exit_code",
"if",
"exit_code",
":",
"script_error",
"=",
"ScriptError",
"(",
"script_args",
"=",
"args",
",",
"exit_code",
"=",
"exit_code",
",",
"output",
"=",
"output",
",",
"cwd",
"=",
"cwd",
")",
"if",
"ignore_errors",
":",
"assert",
"error_handler",
"is",
"None",
",",
"\"don't specify error_handler if ignore_errors is True\"",
"error_handler",
"=",
"Executive",
".",
"ignore_error",
"(",
"error_handler",
"or",
"self",
".",
"default_error_handler",
")",
"(",
"script_error",
")",
"return",
"output"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/jscshim/webkit/Tools/Scripts/webkitpy/common/system/executive.py#L363-L413 |
|
catmaid/CATMAID | 9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf | django/applications/catmaid/control/client.py | python | ClientDataList.delete | (self, request:Request, name=None) | return Response({
'n_deleted': n_deleted,
}) | Delete all key-value store datastores for the client.
The request user must not be anonymous and must have browse, annotate
or administer permissions for at least one project.
---
parameters:
- name: project_id
description: |
ID of a project to delete data from, if any.
required: false
type: integer
paramType: form
- name: ignore_user
description: |
Whether to clear dataassociated with the instance or the request
user. Only project administrators can do this for project-associated
instance data, and only super users can do this for global data
(instance data not associated with any project).
required: false
type: boolean
default: false
paramType: form | Delete all key-value store datastores for the client. | [
"Delete",
"all",
"key",
"-",
"value",
"store",
"datastores",
"for",
"the",
"client",
"."
] | def delete(self, request:Request, name=None) -> Response:
"""Delete all key-value store datastores for the client.
The request user must not be anonymous and must have browse, annotate
or administer permissions for at least one project.
---
parameters:
- name: project_id
description: |
ID of a project to delete data from, if any.
required: false
type: integer
paramType: form
- name: ignore_user
description: |
Whether to clear dataassociated with the instance or the request
user. Only project administrators can do this for project-associated
instance data, and only super users can do this for global data
(instance data not associated with any project).
required: false
type: boolean
default: false
paramType: form
"""
if request.user == get_anonymous_user() or not request.user.is_authenticated:
raise PermissionDenied('Unauthenticated or anonymous users ' \
'can not delete datastores.')
project_id = request.data.get('project_id', None)
project = None
if project_id:
project_id = int(project_id)
project = get_object_or_404(Project, pk=project_id)
if not check_user_role(request.user,
project,
[UserRole.Browse, UserRole.Annotate]):
raise PermissionDenied('User lacks the appropriate ' \
'permissions for this project.')
ignore_user = get_request_bool(request.data, 'ignore_user', False)
if ignore_user and not project_id:
if not request.user.is_superuser:
raise PermissionDenied('Only super users can delete instance ' \
'data.')
if ignore_user:
if not check_user_role(request.user,
project,
[UserRole.Admin]):
raise PermissionDenied('Only administrators can delete ' \
'project default data.')
user = None if ignore_user else request.user
datastore = ClientDatastore(name=name)
n_deleted, _ = ClientData.objects.filter(datastore=datastore,
project=project, user=user).delete()
return Response({
'n_deleted': n_deleted,
}) | [
"def",
"delete",
"(",
"self",
",",
"request",
":",
"Request",
",",
"name",
"=",
"None",
")",
"->",
"Response",
":",
"if",
"request",
".",
"user",
"==",
"get_anonymous_user",
"(",
")",
"or",
"not",
"request",
".",
"user",
".",
"is_authenticated",
":",
"raise",
"PermissionDenied",
"(",
"'Unauthenticated or anonymous users '",
"'can not delete datastores.'",
")",
"project_id",
"=",
"request",
".",
"data",
".",
"get",
"(",
"'project_id'",
",",
"None",
")",
"project",
"=",
"None",
"if",
"project_id",
":",
"project_id",
"=",
"int",
"(",
"project_id",
")",
"project",
"=",
"get_object_or_404",
"(",
"Project",
",",
"pk",
"=",
"project_id",
")",
"if",
"not",
"check_user_role",
"(",
"request",
".",
"user",
",",
"project",
",",
"[",
"UserRole",
".",
"Browse",
",",
"UserRole",
".",
"Annotate",
"]",
")",
":",
"raise",
"PermissionDenied",
"(",
"'User lacks the appropriate '",
"'permissions for this project.'",
")",
"ignore_user",
"=",
"get_request_bool",
"(",
"request",
".",
"data",
",",
"'ignore_user'",
",",
"False",
")",
"if",
"ignore_user",
"and",
"not",
"project_id",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_superuser",
":",
"raise",
"PermissionDenied",
"(",
"'Only super users can delete instance '",
"'data.'",
")",
"if",
"ignore_user",
":",
"if",
"not",
"check_user_role",
"(",
"request",
".",
"user",
",",
"project",
",",
"[",
"UserRole",
".",
"Admin",
"]",
")",
":",
"raise",
"PermissionDenied",
"(",
"'Only administrators can delete '",
"'project default data.'",
")",
"user",
"=",
"None",
"if",
"ignore_user",
"else",
"request",
".",
"user",
"datastore",
"=",
"ClientDatastore",
"(",
"name",
"=",
"name",
")",
"n_deleted",
",",
"_",
"=",
"ClientData",
".",
"objects",
".",
"filter",
"(",
"datastore",
"=",
"datastore",
",",
"project",
"=",
"project",
",",
"user",
"=",
"user",
")",
".",
"delete",
"(",
")",
"return",
"Response",
"(",
"{",
"'n_deleted'",
":",
"n_deleted",
",",
"}",
")"
] | https://github.com/catmaid/CATMAID/blob/9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf/django/applications/catmaid/control/client.py#L272-L329 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetBundleResourceFolder | (self) | return os.path.join(self.GetBundleContentsFolderPath(), "Resources") | Returns the qualified path to the bundle's resource folder. E.g.
Chromium.app/Contents/Resources. Only valid for bundles. | Returns the qualified path to the bundle's resource folder. E.g.
Chromium.app/Contents/Resources. Only valid for bundles. | [
"Returns",
"the",
"qualified",
"path",
"to",
"the",
"bundle",
"s",
"resource",
"folder",
".",
"E",
".",
"g",
".",
"Chromium",
".",
"app",
"/",
"Contents",
"/",
"Resources",
".",
"Only",
"valid",
"for",
"bundles",
"."
] | def GetBundleResourceFolder(self):
"""Returns the qualified path to the bundle's resource folder. E.g.
Chromium.app/Contents/Resources. Only valid for bundles."""
assert self._IsBundle()
if self.isIOS:
return self.GetBundleContentsFolderPath()
return os.path.join(self.GetBundleContentsFolderPath(), "Resources") | [
"def",
"GetBundleResourceFolder",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_IsBundle",
"(",
")",
"if",
"self",
".",
"isIOS",
":",
"return",
"self",
".",
"GetBundleContentsFolderPath",
"(",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"GetBundleContentsFolderPath",
"(",
")",
",",
"\"Resources\"",
")"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L317-L323 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/logging/handlers.py | python | HTTPHandler.__init__ | (self, host, url, method="GET") | Initialize the instance with the host, the request URL, and the method
("GET" or "POST") | Initialize the instance with the host, the request URL, and the method
("GET" or "POST") | [
"Initialize",
"the",
"instance",
"with",
"the",
"host",
"the",
"request",
"URL",
"and",
"the",
"method",
"(",
"GET",
"or",
"POST",
")"
] | def __init__(self, host, url, method="GET"):
"""
Initialize the instance with the host, the request URL, and the method
("GET" or "POST")
"""
logging.Handler.__init__(self)
method = method.upper()
if method not in ["GET", "POST"]:
raise ValueError("method must be GET or POST")
self.host = host
self.url = url
self.method = method | [
"def",
"__init__",
"(",
"self",
",",
"host",
",",
"url",
",",
"method",
"=",
"\"GET\"",
")",
":",
"logging",
".",
"Handler",
".",
"__init__",
"(",
"self",
")",
"method",
"=",
"method",
".",
"upper",
"(",
")",
"if",
"method",
"not",
"in",
"[",
"\"GET\"",
",",
"\"POST\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"method must be GET or POST\"",
")",
"self",
".",
"host",
"=",
"host",
"self",
".",
"url",
"=",
"url",
"self",
".",
"method",
"=",
"method"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/logging/handlers.py#L1002-L1013 |
||
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | deps/v8/tools/clusterfuzz/js_fuzzer/tools/run_one.py | python | list_tests | () | Iterates all fuzz tests and corresponding flags in the given base dir. | Iterates all fuzz tests and corresponding flags in the given base dir. | [
"Iterates",
"all",
"fuzz",
"tests",
"and",
"corresponding",
"flags",
"in",
"the",
"given",
"base",
"dir",
"."
] | def list_tests():
"""Iterates all fuzz tests and corresponding flags in the given base dir."""
for f in os.listdir(test_dir):
if f.startswith('fuzz'):
n = int(re.match(r'fuzz-(\d+)\.js', f).group(1))
ff = 'flags-%d.js' % n
yield (os.path.join(test_dir, f), os.path.join(test_dir, ff)) | [
"def",
"list_tests",
"(",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"test_dir",
")",
":",
"if",
"f",
".",
"startswith",
"(",
"'fuzz'",
")",
":",
"n",
"=",
"int",
"(",
"re",
".",
"match",
"(",
"r'fuzz-(\\d+)\\.js'",
",",
"f",
")",
".",
"group",
"(",
"1",
")",
")",
"ff",
"=",
"'flags-%d.js'",
"%",
"n",
"yield",
"(",
"os",
".",
"path",
".",
"join",
"(",
"test_dir",
",",
"f",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"test_dir",
",",
"ff",
")",
")"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/deps/v8/tools/clusterfuzz/js_fuzzer/tools/run_one.py#L63-L69 |
||
quarkslab/irma | 29d8baa4e27bacaf7aa9dd570c16e5268ae6237c | probe/modules/antivirus/drweb/drweb.py | python | DrWeb.get_version | (self) | return self._run_and_parse(
'--version',
regexp='(?P<version>\d+([.-]\d+)+)',
group='version') | return the version of the antivirus | return the version of the antivirus | [
"return",
"the",
"version",
"of",
"the",
"antivirus"
] | def get_version(self):
"""return the version of the antivirus"""
return self._run_and_parse(
'--version',
regexp='(?P<version>\d+([.-]\d+)+)',
group='version') | [
"def",
"get_version",
"(",
"self",
")",
":",
"return",
"self",
".",
"_run_and_parse",
"(",
"'--version'",
",",
"regexp",
"=",
"'(?P<version>\\d+([.-]\\d+)+)'",
",",
"group",
"=",
"'version'",
")"
] | https://github.com/quarkslab/irma/blob/29d8baa4e27bacaf7aa9dd570c16e5268ae6237c/probe/modules/antivirus/drweb/drweb.py#L53-L58 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/product_expiry/models/production_lot.py | python | StockProductionLot._get_date_values | (self, time_delta, new_date=False) | return vals | Return a dict with different date values updated depending of the
time_delta. Used in the onchange of `expiration_date` and when user
defines a date at the receipt. | Return a dict with different date values updated depending of the
time_delta. Used in the onchange of `expiration_date` and when user
defines a date at the receipt. | [
"Return",
"a",
"dict",
"with",
"different",
"date",
"values",
"updated",
"depending",
"of",
"the",
"time_delta",
".",
"Used",
"in",
"the",
"onchange",
"of",
"expiration_date",
"and",
"when",
"user",
"defines",
"a",
"date",
"at",
"the",
"receipt",
"."
] | def _get_date_values(self, time_delta, new_date=False):
''' Return a dict with different date values updated depending of the
time_delta. Used in the onchange of `expiration_date` and when user
defines a date at the receipt. '''
vals = {
'use_date': self.use_date and (self.use_date + time_delta) or new_date,
'removal_date': self.removal_date and (self.removal_date + time_delta) or new_date,
'alert_date': self.alert_date and (self.alert_date + time_delta) or new_date,
}
return vals | [
"def",
"_get_date_values",
"(",
"self",
",",
"time_delta",
",",
"new_date",
"=",
"False",
")",
":",
"vals",
"=",
"{",
"'use_date'",
":",
"self",
".",
"use_date",
"and",
"(",
"self",
".",
"use_date",
"+",
"time_delta",
")",
"or",
"new_date",
",",
"'removal_date'",
":",
"self",
".",
"removal_date",
"and",
"(",
"self",
".",
"removal_date",
"+",
"time_delta",
")",
"or",
"new_date",
",",
"'alert_date'",
":",
"self",
".",
"alert_date",
"and",
"(",
"self",
".",
"alert_date",
"+",
"time_delta",
")",
"or",
"new_date",
",",
"}",
"return",
"vals"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/product_expiry/models/production_lot.py#L112-L121 |
|
klaasnicolaas/Smarthome-homeassistant-config | 610bd35f4e8cdb4a1f41165b0ccb9251c76f5644 | custom_components/hacs/helpers/information.py | python | get_file_name_python_script | (repository) | Get the filename to target. | Get the filename to target. | [
"Get",
"the",
"filename",
"to",
"target",
"."
] | def get_file_name_python_script(repository):
"""Get the filename to target."""
tree = repository.tree
for treefile in tree:
if treefile.full_path.startswith(
repository.content.path.remote
) and treefile.full_path.endswith(".py"):
repository.data.file_name = treefile.filename | [
"def",
"get_file_name_python_script",
"(",
"repository",
")",
":",
"tree",
"=",
"repository",
".",
"tree",
"for",
"treefile",
"in",
"tree",
":",
"if",
"treefile",
".",
"full_path",
".",
"startswith",
"(",
"repository",
".",
"content",
".",
"path",
".",
"remote",
")",
"and",
"treefile",
".",
"full_path",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"repository",
".",
"data",
".",
"file_name",
"=",
"treefile",
".",
"filename"
] | https://github.com/klaasnicolaas/Smarthome-homeassistant-config/blob/610bd35f4e8cdb4a1f41165b0ccb9251c76f5644/custom_components/hacs/helpers/information.py#L215-L223 |
||
TeamvisionCorp/TeamVision | aa2a57469e430ff50cce21174d8f280efa0a83a7 | distribute/0.0.5/build_shell/teamvision/teamvision/home/views/home_autotask_view.py | python | index_list | (request,sub_nav_action) | return page_worker.get_autotask_fullpage(request, sub_nav_action) | index page | index page | [
"index",
"page"
] | def index_list(request,sub_nav_action):
''' index page'''
page_worker=HomeAutoTaskPageWorker(request)
return page_worker.get_autotask_fullpage(request, sub_nav_action) | [
"def",
"index_list",
"(",
"request",
",",
"sub_nav_action",
")",
":",
"page_worker",
"=",
"HomeAutoTaskPageWorker",
"(",
"request",
")",
"return",
"page_worker",
".",
"get_autotask_fullpage",
"(",
"request",
",",
"sub_nav_action",
")"
] | https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.5/build_shell/teamvision/teamvision/home/views/home_autotask_view.py#L16-L19 |
|
googleglass/mirror-quickstart-python | e34077bae91657170c305702471f5c249eb1b686 | lib/oauth2client/client.py | python | credentials_from_code | (client_id, client_secret, scope, code,
redirect_uri='postmessage', http=None,
user_agent=None, token_uri=GOOGLE_TOKEN_URI,
auth_uri=GOOGLE_AUTH_URI,
revoke_uri=GOOGLE_REVOKE_URI) | return credentials | Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or iterable of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token | Exchanges an authorization code for an OAuth2Credentials object. | [
"Exchanges",
"an",
"authorization",
"code",
"for",
"an",
"OAuth2Credentials",
"object",
"."
] | def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri='postmessage', http=None,
user_agent=None, token_uri=GOOGLE_TOKEN_URI,
auth_uri=GOOGLE_AUTH_URI,
revoke_uri=GOOGLE_REVOKE_URI):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or iterable of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
"""
flow = OAuth2WebServerFlow(client_id, client_secret, scope,
redirect_uri=redirect_uri, user_agent=user_agent,
auth_uri=auth_uri, token_uri=token_uri,
revoke_uri=revoke_uri)
credentials = flow.step2_exchange(code, http=http)
return credentials | [
"def",
"credentials_from_code",
"(",
"client_id",
",",
"client_secret",
",",
"scope",
",",
"code",
",",
"redirect_uri",
"=",
"'postmessage'",
",",
"http",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"token_uri",
"=",
"GOOGLE_TOKEN_URI",
",",
"auth_uri",
"=",
"GOOGLE_AUTH_URI",
",",
"revoke_uri",
"=",
"GOOGLE_REVOKE_URI",
")",
":",
"flow",
"=",
"OAuth2WebServerFlow",
"(",
"client_id",
",",
"client_secret",
",",
"scope",
",",
"redirect_uri",
"=",
"redirect_uri",
",",
"user_agent",
"=",
"user_agent",
",",
"auth_uri",
"=",
"auth_uri",
",",
"token_uri",
"=",
"token_uri",
",",
"revoke_uri",
"=",
"revoke_uri",
")",
"credentials",
"=",
"flow",
".",
"step2_exchange",
"(",
"code",
",",
"http",
"=",
"http",
")",
"return",
"credentials"
] | https://github.com/googleglass/mirror-quickstart-python/blob/e34077bae91657170c305702471f5c249eb1b686/lib/oauth2client/client.py#L1073-L1109 |
|
wotermelon/toJump | 3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f | lib/mac/systrace/catapult/third_party/pyserial/serial/serialposix.py | python | PosixSerial.getRI | (self) | return struct.unpack('I',s)[0] & TIOCM_RI != 0 | Read terminal status line: Ring Indicator | Read terminal status line: Ring Indicator | [
"Read",
"terminal",
"status",
"line",
":",
"Ring",
"Indicator"
] | def getRI(self):
"""Read terminal status line: Ring Indicator"""
if not self._isOpen: raise portNotOpenError
s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
return struct.unpack('I',s)[0] & TIOCM_RI != 0 | [
"def",
"getRI",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"s",
"=",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"fd",
",",
"TIOCMGET",
",",
"TIOCM_zero_str",
")",
"return",
"struct",
".",
"unpack",
"(",
"'I'",
",",
"s",
")",
"[",
"0",
"]",
"&",
"TIOCM_RI",
"!=",
"0"
] | https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/third_party/pyserial/serial/serialposix.py#L578-L582 |
|
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetPerTargetSettings | (self) | return result | Gets a list of all the per-target settings. This will only fetch keys
whose values are the same across all configurations. | Gets a list of all the per-target settings. This will only fetch keys
whose values are the same across all configurations. | [
"Gets",
"a",
"list",
"of",
"all",
"the",
"per",
"-",
"target",
"settings",
".",
"This",
"will",
"only",
"fetch",
"keys",
"whose",
"values",
"are",
"the",
"same",
"across",
"all",
"configurations",
"."
] | def GetPerTargetSettings(self):
"""Gets a list of all the per-target settings. This will only fetch keys
whose values are the same across all configurations."""
first_pass = True
result = {}
for configname in sorted(self.xcode_settings.keys()):
if first_pass:
result = dict(self.xcode_settings[configname])
first_pass = False
else:
for key, value in self.xcode_settings[configname].iteritems():
if key not in result:
continue
elif result[key] != value:
del result[key]
return result | [
"def",
"GetPerTargetSettings",
"(",
"self",
")",
":",
"first_pass",
"=",
"True",
"result",
"=",
"{",
"}",
"for",
"configname",
"in",
"sorted",
"(",
"self",
".",
"xcode_settings",
".",
"keys",
"(",
")",
")",
":",
"if",
"first_pass",
":",
"result",
"=",
"dict",
"(",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
")",
"first_pass",
"=",
"False",
"else",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"not",
"in",
"result",
":",
"continue",
"elif",
"result",
"[",
"key",
"]",
"!=",
"value",
":",
"del",
"result",
"[",
"key",
"]",
"return",
"result"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/xcode_emulation.py#L956-L971 |
|
CivilHub/CivilHub | 97c3ebe6031e6a3600c09d0fd99b764448ca592d | gallery/image.py | python | adjust_uploaded_image | (sender, instance, **kwargs) | A unified method that manages images for our model ImagableItemMixin.
Readies images of standarized sizes and the same for retina.
The size of the image is set in settings.DEFAULT_IMG_SIZE. We preserve
the original. | A unified method that manages images for our model ImagableItemMixin.
Readies images of standarized sizes and the same for retina.
The size of the image is set in settings.DEFAULT_IMG_SIZE. We preserve
the original. | [
"A",
"unified",
"method",
"that",
"manages",
"images",
"for",
"our",
"model",
"ImagableItemMixin",
".",
"Readies",
"images",
"of",
"standarized",
"sizes",
"and",
"the",
"same",
"for",
"retina",
".",
"The",
"size",
"of",
"the",
"image",
"is",
"set",
"in",
"settings",
".",
"DEFAULT_IMG_SIZE",
".",
"We",
"preserve",
"the",
"original",
"."
] | def adjust_uploaded_image(sender, instance, **kwargs):
"""
A unified method that manages images for our model ImagableItemMixin.
Readies images of standarized sizes and the same for retina.
The size of the image is set in settings.DEFAULT_IMG_SIZE. We preserve
the original.
"""
# Ignoruj wpisy z domyślnymi obrazami
if instance.image.name == settings.DEFAULT_IMG_PATH:
return True
# Zapisz kopię oryginału jako JPEG
base_image = Image.open(instance.image.path)
filename = os.path.splitext(instance.image.path)[0]
base_image.save("{}.jpg".format(filename), 'JPEG')
# Rozmiar obrazów i miniatur pobieramy z ustawień globalnych
width, height = settings.DEFAULT_IMG_SIZE
t_width, t_height = settings.DEFAULT_THUMB_SIZE
# Normalne obrazki w pełnych wymiarach
image = resize_image(base_image, (width * 2, height * 2))
image.save("{}_fx@2x.jpg".format(filename), 'JPEG')
image = resize_image(base_image, (width, height))
image.save("{}_fx.jpg".format(filename), 'JPEG')
# Miniatury do pokazania w widokach list i aktywności
image = resize_image(base_image, (t_width * 2, t_height * 2))
image.save("{}_thumbnail@2x.jpg".format(filename), 'JPEG')
image = resize_image(base_image, (t_width, t_height))
image.save("{}_thumbnail.jpg".format(filename), 'JPEG') | [
"def",
"adjust_uploaded_image",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"# Ignoruj wpisy z domyślnymi obrazami",
"if",
"instance",
".",
"image",
".",
"name",
"==",
"settings",
".",
"DEFAULT_IMG_PATH",
":",
"return",
"True",
"# Zapisz kopię oryginału jako JPEG",
"base_image",
"=",
"Image",
".",
"open",
"(",
"instance",
".",
"image",
".",
"path",
")",
"filename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"instance",
".",
"image",
".",
"path",
")",
"[",
"0",
"]",
"base_image",
".",
"save",
"(",
"\"{}.jpg\"",
".",
"format",
"(",
"filename",
")",
",",
"'JPEG'",
")",
"# Rozmiar obrazów i miniatur pobieramy z ustawień globalnych",
"width",
",",
"height",
"=",
"settings",
".",
"DEFAULT_IMG_SIZE",
"t_width",
",",
"t_height",
"=",
"settings",
".",
"DEFAULT_THUMB_SIZE",
"# Normalne obrazki w pełnych wymiarach",
"image",
"=",
"resize_image",
"(",
"base_image",
",",
"(",
"width",
"*",
"2",
",",
"height",
"*",
"2",
")",
")",
"image",
".",
"save",
"(",
"\"{}_fx@2x.jpg\"",
".",
"format",
"(",
"filename",
")",
",",
"'JPEG'",
")",
"image",
"=",
"resize_image",
"(",
"base_image",
",",
"(",
"width",
",",
"height",
")",
")",
"image",
".",
"save",
"(",
"\"{}_fx.jpg\"",
".",
"format",
"(",
"filename",
")",
",",
"'JPEG'",
")",
"# Miniatury do pokazania w widokach list i aktywności",
"image",
"=",
"resize_image",
"(",
"base_image",
",",
"(",
"t_width",
"*",
"2",
",",
"t_height",
"*",
"2",
")",
")",
"image",
".",
"save",
"(",
"\"{}_thumbnail@2x.jpg\"",
".",
"format",
"(",
"filename",
")",
",",
"'JPEG'",
")",
"image",
"=",
"resize_image",
"(",
"base_image",
",",
"(",
"t_width",
",",
"t_height",
")",
")",
"image",
".",
"save",
"(",
"\"{}_thumbnail.jpg\"",
".",
"format",
"(",
"filename",
")",
",",
"'JPEG'",
")"
] | https://github.com/CivilHub/CivilHub/blob/97c3ebe6031e6a3600c09d0fd99b764448ca592d/gallery/image.py#L232-L258 |
||
carlosperate/ardublockly | 04fa48273b5651386d0ef1ce6dd446795ffc2594 | ardublocklyserver/local-packages/configparser/__init__.py | python | RawConfigParser.read_dict | (self, dictionary, source='<dict>') | Read configuration from a dictionary.
Keys are section names, values are dictionaries with keys and values
that should be present in the section. If the used dictionary type
preserves order, sections and their keys will be added in order.
All types held in the dictionary are converted to strings during
reading, including section names, option names and keys.
Optional second argument is the `source' specifying the name of the
dictionary being read. | Read configuration from a dictionary. | [
"Read",
"configuration",
"from",
"a",
"dictionary",
"."
] | def read_dict(self, dictionary, source='<dict>'):
"""Read configuration from a dictionary.
Keys are section names, values are dictionaries with keys and values
that should be present in the section. If the used dictionary type
preserves order, sections and their keys will be added in order.
All types held in the dictionary are converted to strings during
reading, including section names, option names and keys.
Optional second argument is the `source' specifying the name of the
dictionary being read.
"""
elements_added = set()
for section, keys in dictionary.items():
section = str(section)
try:
self.add_section(section)
except (DuplicateSectionError, ValueError):
if self._strict and section in elements_added:
raise
elements_added.add(section)
for key, value in keys.items():
key = self.optionxform(str(key))
if value is not None:
value = str(value)
if self._strict and (section, key) in elements_added:
raise DuplicateOptionError(section, key, source)
elements_added.add((section, key))
self.set(section, key, value) | [
"def",
"read_dict",
"(",
"self",
",",
"dictionary",
",",
"source",
"=",
"'<dict>'",
")",
":",
"elements_added",
"=",
"set",
"(",
")",
"for",
"section",
",",
"keys",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"section",
"=",
"str",
"(",
"section",
")",
"try",
":",
"self",
".",
"add_section",
"(",
"section",
")",
"except",
"(",
"DuplicateSectionError",
",",
"ValueError",
")",
":",
"if",
"self",
".",
"_strict",
"and",
"section",
"in",
"elements_added",
":",
"raise",
"elements_added",
".",
"add",
"(",
"section",
")",
"for",
"key",
",",
"value",
"in",
"keys",
".",
"items",
"(",
")",
":",
"key",
"=",
"self",
".",
"optionxform",
"(",
"str",
"(",
"key",
")",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"self",
".",
"_strict",
"and",
"(",
"section",
",",
"key",
")",
"in",
"elements_added",
":",
"raise",
"DuplicateOptionError",
"(",
"section",
",",
"key",
",",
"source",
")",
"elements_added",
".",
"add",
"(",
"(",
"section",
",",
"key",
")",
")",
"self",
".",
"set",
"(",
"section",
",",
"key",
",",
"value",
")"
] | https://github.com/carlosperate/ardublockly/blob/04fa48273b5651386d0ef1ce6dd446795ffc2594/ardublocklyserver/local-packages/configparser/__init__.py#L725-L754 |
||
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/mdx/highlight.py | python | Highlight.get_extended_language | (self, language) | return self.extend_pygments_lang.get(language, (language, {})) | Get extended language. | Get extended language. | [
"Get",
"extended",
"language",
"."
] | def get_extended_language(self, language):
"""Get extended language."""
return self.extend_pygments_lang.get(language, (language, {})) | [
"def",
"get_extended_language",
"(",
"self",
",",
"language",
")",
":",
"return",
"self",
".",
"extend_pygments_lang",
".",
"get",
"(",
"language",
",",
"(",
"language",
",",
"{",
"}",
")",
")"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/mdx/highlight.py#L272-L275 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/bdb.py | python | effective | (file, line, frame) | return (None, None) | Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary bp. | Determine which breakpoint for this file:line is to be acted upon. | [
"Determine",
"which",
"breakpoint",
"for",
"this",
"file",
":",
"line",
"is",
"to",
"be",
"acted",
"upon",
"."
] | def effective(file, line, frame):
"""Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary bp.
"""
possibles = Breakpoint.bplist[file,line]
for i in range(0, len(possibles)):
b = possibles[i]
if b.enabled == 0:
continue
if not checkfuncname(b, frame):
continue
# Count every hit when bp is enabled
b.hits = b.hits + 1
if not b.cond:
# If unconditional, and ignoring,
# go on to next, else break
if b.ignore > 0:
b.ignore = b.ignore -1
continue
else:
# breakpoint and marker that's ok
# to delete if temporary
return (b,1)
else:
# Conditional bp.
# Ignore count applies only to those bpt hits where the
# condition evaluates to true.
try:
val = eval(b.cond, frame.f_globals,
frame.f_locals)
if val:
if b.ignore > 0:
b.ignore = b.ignore -1
# continue
else:
return (b,1)
# else:
# continue
except:
# if eval fails, most conservative
# thing is to stop on breakpoint
# regardless of ignore count.
# Don't delete temporary,
# as another hint to user.
return (b,0)
return (None, None) | [
"def",
"effective",
"(",
"file",
",",
"line",
",",
"frame",
")",
":",
"possibles",
"=",
"Breakpoint",
".",
"bplist",
"[",
"file",
",",
"line",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"possibles",
")",
")",
":",
"b",
"=",
"possibles",
"[",
"i",
"]",
"if",
"b",
".",
"enabled",
"==",
"0",
":",
"continue",
"if",
"not",
"checkfuncname",
"(",
"b",
",",
"frame",
")",
":",
"continue",
"# Count every hit when bp is enabled",
"b",
".",
"hits",
"=",
"b",
".",
"hits",
"+",
"1",
"if",
"not",
"b",
".",
"cond",
":",
"# If unconditional, and ignoring,",
"# go on to next, else break",
"if",
"b",
".",
"ignore",
">",
"0",
":",
"b",
".",
"ignore",
"=",
"b",
".",
"ignore",
"-",
"1",
"continue",
"else",
":",
"# breakpoint and marker that's ok",
"# to delete if temporary",
"return",
"(",
"b",
",",
"1",
")",
"else",
":",
"# Conditional bp.",
"# Ignore count applies only to those bpt hits where the",
"# condition evaluates to true.",
"try",
":",
"val",
"=",
"eval",
"(",
"b",
".",
"cond",
",",
"frame",
".",
"f_globals",
",",
"frame",
".",
"f_locals",
")",
"if",
"val",
":",
"if",
"b",
".",
"ignore",
">",
"0",
":",
"b",
".",
"ignore",
"=",
"b",
".",
"ignore",
"-",
"1",
"# continue",
"else",
":",
"return",
"(",
"b",
",",
"1",
")",
"# else:",
"# continue",
"except",
":",
"# if eval fails, most conservative",
"# thing is to stop on breakpoint",
"# regardless of ignore count.",
"# Don't delete temporary,",
"# as another hint to user.",
"return",
"(",
"b",
",",
"0",
")",
"return",
"(",
"None",
",",
"None",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/bdb.py#L548-L597 |
|
crits/crits | 6b357daa5c3060cf622d3a3b0c7b41a9ca69c049 | crits/campaigns/campaign.py | python | Campaign.add_ttp | (self, ttp_item) | Add a TTP to this Campaign.
:param ttp_item: The TTP to add.
:type ttp_item: EmbeddedTTP | Add a TTP to this Campaign. | [
"Add",
"a",
"TTP",
"to",
"this",
"Campaign",
"."
] | def add_ttp(self, ttp_item):
"""
Add a TTP to this Campaign.
:param ttp_item: The TTP to add.
:type ttp_item: EmbeddedTTP
"""
if isinstance(ttp_item, EmbeddedTTP):
found = False
for ttp in self.ttps:
if ttp.ttp == ttp_item.ttp:
found = True
if not found:
self.ttps.append(ttp_item) | [
"def",
"add_ttp",
"(",
"self",
",",
"ttp_item",
")",
":",
"if",
"isinstance",
"(",
"ttp_item",
",",
"EmbeddedTTP",
")",
":",
"found",
"=",
"False",
"for",
"ttp",
"in",
"self",
".",
"ttps",
":",
"if",
"ttp",
".",
"ttp",
"==",
"ttp_item",
".",
"ttp",
":",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"self",
".",
"ttps",
".",
"append",
"(",
"ttp_item",
")"
] | https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/campaigns/campaign.py#L179-L194 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py | python | _fix_file | (parameters) | Helper function for optionally running fix_file() in parallel. | Helper function for optionally running fix_file() in parallel. | [
"Helper",
"function",
"for",
"optionally",
"running",
"fix_file",
"()",
"in",
"parallel",
"."
] | def _fix_file(parameters):
"""Helper function for optionally running fix_file() in parallel."""
if parameters[1].verbose:
print('[file:{0}]'.format(parameters[0]), file=sys.stderr)
try:
fix_file(*parameters)
except IOError as error:
print(unicode(error), file=sys.stderr) | [
"def",
"_fix_file",
"(",
"parameters",
")",
":",
"if",
"parameters",
"[",
"1",
"]",
".",
"verbose",
":",
"print",
"(",
"'[file:{0}]'",
".",
"format",
"(",
"parameters",
"[",
"0",
"]",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"try",
":",
"fix_file",
"(",
"*",
"parameters",
")",
"except",
"IOError",
"as",
"error",
":",
"print",
"(",
"unicode",
"(",
"error",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py#L3682-L3689 |
||
nodejs/node-convergence-archive | e11fe0c2777561827cdb7207d46b0917ef3c42a7 | tools/cpplint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"Resets the set of NOLINT suppressions to empty."
_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/tools/cpplint.py#L328-L330 |
||
TeamvisionCorp/TeamVision | aa2a57469e430ff50cce21174d8f280efa0a83a7 | distribute/0.0.4/build_shell/teamvision/teamvision/ci/views/ci_task_parameter_view.py | python | create | (request,task_id) | return HttpResponse(result) | create a new parameter group after press enter | create a new parameter group after press enter | [
"create",
"a",
"new",
"parameter",
"group",
"after",
"press",
"enter"
] | def create(request,task_id):
'''create a new parameter group after press enter'''
result=True
try:
CITaskParameterService.create_task_parameter(request,task_id)
except Exception as ex:
result=str(ex)
SimpleLogger.exception(ex)
return HttpResponse(result) | [
"def",
"create",
"(",
"request",
",",
"task_id",
")",
":",
"result",
"=",
"True",
"try",
":",
"CITaskParameterService",
".",
"create_task_parameter",
"(",
"request",
",",
"task_id",
")",
"except",
"Exception",
"as",
"ex",
":",
"result",
"=",
"str",
"(",
"ex",
")",
"SimpleLogger",
".",
"exception",
"(",
"ex",
")",
"return",
"HttpResponse",
"(",
"result",
")"
] | https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.4/build_shell/teamvision/teamvision/ci/views/ci_task_parameter_view.py#L34-L42 |
|
crits/crits | 6b357daa5c3060cf622d3a3b0c7b41a9ca69c049 | crits/core/crits_mongoengine.py | python | CritsBaseAttributes.delete_all_objects | (self) | Delete all objects for this top-level object. | Delete all objects for this top-level object. | [
"Delete",
"all",
"objects",
"for",
"this",
"top",
"-",
"level",
"object",
"."
] | def delete_all_objects(self):
"""
Delete all objects for this top-level object.
"""
from crits.objects.handlers import delete_object_file
for o in self.obj:
if o.object_type == ObjectTypes.FILE_UPLOAD:
delete_object_file(o.value)
self.obj = [] | [
"def",
"delete_all_objects",
"(",
"self",
")",
":",
"from",
"crits",
".",
"objects",
".",
"handlers",
"import",
"delete_object_file",
"for",
"o",
"in",
"self",
".",
"obj",
":",
"if",
"o",
".",
"object_type",
"==",
"ObjectTypes",
".",
"FILE_UPLOAD",
":",
"delete_object_file",
"(",
"o",
".",
"value",
")",
"self",
".",
"obj",
"=",
"[",
"]"
] | https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/core/crits_mongoengine.py#L1716-L1725 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/site.py | python | setencoding | () | Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this. | Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this. | [
"Set",
"the",
"string",
"encoding",
"used",
"by",
"the",
"Unicode",
"implementation",
".",
"The",
"default",
"is",
"ascii",
"but",
"if",
"you",
"re",
"willing",
"to",
"experiment",
"you",
"can",
"change",
"this",
"."
] | def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) | [
"def",
"setencoding",
"(",
")",
":",
"encoding",
"=",
"\"ascii\"",
"# Default value set by _PyUnicode_Init()",
"if",
"0",
":",
"# Enable to support locale aware default string encodings.",
"import",
"locale",
"loc",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"if",
"loc",
"[",
"1",
"]",
":",
"encoding",
"=",
"loc",
"[",
"1",
"]",
"if",
"0",
":",
"# Enable to switch off string to Unicode coercion and implicit",
"# Unicode to string conversion.",
"encoding",
"=",
"\"undefined\"",
"if",
"encoding",
"!=",
"\"ascii\"",
":",
"# On Non-Unicode builds this will raise an AttributeError...",
"sys",
".",
"setdefaultencoding",
"(",
"encoding",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/site.py#L487-L504 |
||
uccser/cs-field-guide | ea6e08e3cf170209d5bacdcef4ce6934fe1ecdb4 | csfieldguide/static/files/linear-binary-search-python3.py | python | binary_search_count | (list_of_keys, search_key) | return 0 | Perform a Binary search.
Returns the number of comparisons required.
Based on code from:
http://rosettacode.org/wiki/Binary_search#Python:_Iterative | Perform a Binary search. | [
"Perform",
"a",
"Binary",
"search",
"."
] | def binary_search_count(list_of_keys, search_key):
"""
Perform a Binary search.
Returns the number of comparisons required.
Based on code from:
http://rosettacode.org/wiki/Binary_search#Python:_Iterative
"""
length = len(list_of_keys)
if length == 0:
print("List of keys not found.")
return 0
if length == 1:
return 1
key_comparisons_made = 0
low = 0
high = len(list_of_keys) - 1
while low <= high:
middle = (low + high) // 2
key_comparisons_made += 1
if list_of_keys[middle] > search_key:
high = middle - 1
elif list_of_keys[middle] < search_key:
low = middle + 1
key_comparisons_made += 1
else:
# increment here because the previous comparison was unsuccessful
key_comparisons_made += 1
return key_comparisons_made
return 0 | [
"def",
"binary_search_count",
"(",
"list_of_keys",
",",
"search_key",
")",
":",
"length",
"=",
"len",
"(",
"list_of_keys",
")",
"if",
"length",
"==",
"0",
":",
"print",
"(",
"\"List of keys not found.\"",
")",
"return",
"0",
"if",
"length",
"==",
"1",
":",
"return",
"1",
"key_comparisons_made",
"=",
"0",
"low",
"=",
"0",
"high",
"=",
"len",
"(",
"list_of_keys",
")",
"-",
"1",
"while",
"low",
"<=",
"high",
":",
"middle",
"=",
"(",
"low",
"+",
"high",
")",
"//",
"2",
"key_comparisons_made",
"+=",
"1",
"if",
"list_of_keys",
"[",
"middle",
"]",
">",
"search_key",
":",
"high",
"=",
"middle",
"-",
"1",
"elif",
"list_of_keys",
"[",
"middle",
"]",
"<",
"search_key",
":",
"low",
"=",
"middle",
"+",
"1",
"key_comparisons_made",
"+=",
"1",
"else",
":",
"# increment here because the previous comparison was unsuccessful",
"key_comparisons_made",
"+=",
"1",
"return",
"key_comparisons_made",
"return",
"0"
] | https://github.com/uccser/cs-field-guide/blob/ea6e08e3cf170209d5bacdcef4ce6934fe1ecdb4/csfieldguide/static/files/linear-binary-search-python3.py#L29-L59 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/Zelenium/generator.py | python | ScenarioGenerator._log | ( self, msg, level ) | Write a note to stderr (if verbosity enabled). | Write a note to stderr (if verbosity enabled). | [
"Write",
"a",
"note",
"to",
"stderr",
"(",
"if",
"verbosity",
"enabled",
")",
"."
] | def _log( self, msg, level ):
"""
Write a note to stderr (if verbosity enabled).
"""
if level <= self._verbosity:
sys.stderr.write( "%s\n" % msg ) | [
"def",
"_log",
"(",
"self",
",",
"msg",
",",
"level",
")",
":",
"if",
"level",
"<=",
"self",
".",
"_verbosity",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"msg",
")"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Zelenium/generator.py#L261-L266 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py | python | Thread.get_register | (self, register) | return context[register] | @type register: str
@param register: Register name.
@rtype: int
@return: Value of the requested register. | @type register: str
@param register: Register name. | [
"@type",
"register",
":",
"str",
"@param",
"register",
":",
"Register",
"name",
"."
] | def get_register(self, register):
"""
@type register: str
@param register: Register name.
@rtype: int
@return: Value of the requested register.
"""
'Returns the value of a specific register.'
context = self.get_context()
return context[register] | [
"def",
"get_register",
"(",
"self",
",",
"register",
")",
":",
"'Returns the value of a specific register.'",
"context",
"=",
"self",
".",
"get_context",
"(",
")",
"return",
"context",
"[",
"register",
"]"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py#L609-L619 |
|
google/blockly-games | 79fa4307a23ce9e4f46dd6a737cfb2ce6428a892 | third-party/closurebuilder/source.py | python | Source.GetSource | (self) | return self._source | Get the source as a string. | Get the source as a string. | [
"Get",
"the",
"source",
"as",
"a",
"string",
"."
] | def GetSource(self):
"""Get the source as a string."""
return self._source | [
"def",
"GetSource",
"(",
"self",
")",
":",
"return",
"self",
".",
"_source"
] | https://github.com/google/blockly-games/blob/79fa4307a23ce9e4f46dd6a737cfb2ce6428a892/third-party/closurebuilder/source.py#L64-L66 |
|
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/Sqlmap/thirdparty/bottle/bottle.py | python | MultiDict.getall | (self, key) | return self.dict.get(key) or [] | Return a (possibly empty) list of values for a key. | Return a (possibly empty) list of values for a key. | [
"Return",
"a",
"(",
"possibly",
"empty",
")",
"list",
"of",
"values",
"for",
"a",
"key",
"."
] | def getall(self, key):
''' Return a (possibly empty) list of values for a key. '''
return self.dict.get(key) or [] | [
"def",
"getall",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"dict",
".",
"get",
"(",
"key",
")",
"or",
"[",
"]"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/bottle/bottle.py#L1755-L1757 |
|
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter._WinIdlRule | (self, source, prebuild, outputs) | Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated. | Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated. | [
"Handle",
"the",
"implicit",
"VS",
".",
"idl",
"rule",
"for",
"one",
"source",
"file",
".",
"Fills",
"|outputs|",
"with",
"files",
"that",
"are",
"generated",
"."
] | def _WinIdlRule(self, source, prebuild, outputs):
"""Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated."""
outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData(
source, self.config_name)
outdir = self.GypPathToNinja(outdir)
def fix_path(path, rel=None):
path = os.path.join(outdir, path)
dirname, basename = os.path.split(source)
root, ext = os.path.splitext(basename)
path = self.ExpandRuleVariables(
path, root, dirname, source, ext, basename)
if rel:
path = os.path.relpath(path, rel)
return path
vars = [(name, fix_path(value, outdir)) for name, value in vars]
output = [fix_path(p) for p in output]
vars.append(('outdir', outdir))
vars.append(('idlflags', flags))
input = self.GypPathToNinja(source)
self.ninja.build(output, 'idl', input,
variables=vars, order_only=prebuild)
outputs.extend(output) | [
"def",
"_WinIdlRule",
"(",
"self",
",",
"source",
",",
"prebuild",
",",
"outputs",
")",
":",
"outdir",
",",
"output",
",",
"vars",
",",
"flags",
"=",
"self",
".",
"msvs_settings",
".",
"GetIdlBuildData",
"(",
"source",
",",
"self",
".",
"config_name",
")",
"outdir",
"=",
"self",
".",
"GypPathToNinja",
"(",
"outdir",
")",
"def",
"fix_path",
"(",
"path",
",",
"rel",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outdir",
",",
"path",
")",
"dirname",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"source",
")",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"path",
"=",
"self",
".",
"ExpandRuleVariables",
"(",
"path",
",",
"root",
",",
"dirname",
",",
"source",
",",
"ext",
",",
"basename",
")",
"if",
"rel",
":",
"path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"rel",
")",
"return",
"path",
"vars",
"=",
"[",
"(",
"name",
",",
"fix_path",
"(",
"value",
",",
"outdir",
")",
")",
"for",
"name",
",",
"value",
"in",
"vars",
"]",
"output",
"=",
"[",
"fix_path",
"(",
"p",
")",
"for",
"p",
"in",
"output",
"]",
"vars",
".",
"append",
"(",
"(",
"'outdir'",
",",
"outdir",
")",
")",
"vars",
".",
"append",
"(",
"(",
"'idlflags'",
",",
"flags",
")",
")",
"input",
"=",
"self",
".",
"GypPathToNinja",
"(",
"source",
")",
"self",
".",
"ninja",
".",
"build",
"(",
"output",
",",
"'idl'",
",",
"input",
",",
"variables",
"=",
"vars",
",",
"order_only",
"=",
"prebuild",
")",
"outputs",
".",
"extend",
"(",
"output",
")"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L504-L526 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/xml/sax/handler.py | python | DTDHandler.notationDecl | (self, name, publicId, systemId) | Handle a notation declaration event. | Handle a notation declaration event. | [
"Handle",
"a",
"notation",
"declaration",
"event",
"."
] | def notationDecl(self, name, publicId, systemId):
"Handle a notation declaration event." | [
"def",
"notationDecl",
"(",
"self",
",",
"name",
",",
"publicId",
",",
"systemId",
")",
":"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/xml/sax/handler.py#L214-L215 |
||
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | api/src/opentrons/protocol_engine/execution/movement.py | python | MovementHandler.home | (self, axes: Optional[Sequence[MotorAxis]]) | Send the requested axes to their "home" positions.
If axes is `None`, will home all motors. | Send the requested axes to their "home" positions. | [
"Send",
"the",
"requested",
"axes",
"to",
"their",
"home",
"positions",
"."
] | async def home(self, axes: Optional[Sequence[MotorAxis]]) -> None:
"""Send the requested axes to their "home" positions.
If axes is `None`, will home all motors.
"""
hardware_axes = None
if axes is not None:
hardware_axes = [MOTOR_AXIS_TO_HARDWARE_AXIS[a] for a in axes]
await self._hardware_api.home(axes=hardware_axes) | [
"async",
"def",
"home",
"(",
"self",
",",
"axes",
":",
"Optional",
"[",
"Sequence",
"[",
"MotorAxis",
"]",
"]",
")",
"->",
"None",
":",
"hardware_axes",
"=",
"None",
"if",
"axes",
"is",
"not",
"None",
":",
"hardware_axes",
"=",
"[",
"MOTOR_AXIS_TO_HARDWARE_AXIS",
"[",
"a",
"]",
"for",
"a",
"in",
"axes",
"]",
"await",
"self",
".",
"_hardware_api",
".",
"home",
"(",
"axes",
"=",
"hardware_axes",
")"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/protocol_engine/execution/movement.py#L177-L186 |
||
jcubic/leash | e0a7a9fbd5e30daa97711b5b5c1ff33c6f485fbb | cgi-bin/json_rpc.py | python | dump_exception | () | return message | create execption info for json response. | create execption info for json response. | [
"create",
"execption",
"info",
"for",
"json",
"response",
"."
] | def dump_exception():
"""create execption info for json response."""
info = sys.exc_info()
message = {"name": str(info[0]), "message": str(info[1])}
if __debug__:
buff = StringIO()
traceback.print_exc(file=buff)
message["traceback"] = buff.getvalue()
return message | [
"def",
"dump_exception",
"(",
")",
":",
"info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"message",
"=",
"{",
"\"name\"",
":",
"str",
"(",
"info",
"[",
"0",
"]",
")",
",",
"\"message\"",
":",
"str",
"(",
"info",
"[",
"1",
"]",
")",
"}",
"if",
"__debug__",
":",
"buff",
"=",
"StringIO",
"(",
")",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"buff",
")",
"message",
"[",
"\"traceback\"",
"]",
"=",
"buff",
".",
"getvalue",
"(",
")",
"return",
"message"
] | https://github.com/jcubic/leash/blob/e0a7a9fbd5e30daa97711b5b5c1ff33c6f485fbb/cgi-bin/json_rpc.py#L93-L101 |
|
wotermelon/toJump | 3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f | lib/mac/systrace/catapult/devil/devil/utils/usb_hubs.py | python | HubType.GetPhysicalPortToNodeTuples | (self, node) | Gets devices connected to the physical ports on a hub of this type.
Args:
node: [USBNode] Node representing a hub of this type.
Yields:
A series of (int, USBNode) tuples giving a physical port
and the USBNode connected to it.
Raises:
ValueError: If the given node isn't a hub of this type. | Gets devices connected to the physical ports on a hub of this type. | [
"Gets",
"devices",
"connected",
"to",
"the",
"physical",
"ports",
"on",
"a",
"hub",
"of",
"this",
"type",
"."
] | def GetPhysicalPortToNodeTuples(self, node):
"""Gets devices connected to the physical ports on a hub of this type.
Args:
node: [USBNode] Node representing a hub of this type.
Yields:
A series of (int, USBNode) tuples giving a physical port
and the USBNode connected to it.
Raises:
ValueError: If the given node isn't a hub of this type.
"""
if self.IsType(node):
for res in self._GppHelper(node, self._v2p_port):
yield res
else:
raise ValueError('Node must be a hub of this type') | [
"def",
"GetPhysicalPortToNodeTuples",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"IsType",
"(",
"node",
")",
":",
"for",
"res",
"in",
"self",
".",
"_GppHelper",
"(",
"node",
",",
"self",
".",
"_v2p_port",
")",
":",
"yield",
"res",
"else",
":",
"raise",
"ValueError",
"(",
"'Node must be a hub of this type'",
")"
] | https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/devil/devil/utils/usb_hubs.py#L53-L70 |
||
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | tools/gyp/pylib/gyp/generator/ninja.py | python | ComputeOutputDir | (params) | return os.path.normpath(os.path.join(generator_dir, output_dir)) | Returns the path from the toplevel_dir to the build output directory. | Returns the path from the toplevel_dir to the build output directory. | [
"Returns",
"the",
"path",
"from",
"the",
"toplevel_dir",
"to",
"the",
"build",
"output",
"directory",
"."
] | def ComputeOutputDir(params):
"""Returns the path from the toplevel_dir to the build output directory."""
# generator_dir: relative path from pwd to where make puts build files.
# Makes migrating from make to ninja easier, ninja doesn't put anything here.
generator_dir = os.path.relpath(params["options"].generator_output or ".")
# output_dir: relative path from generator_dir to the build directory.
output_dir = params.get("generator_flags", {}).get("output_dir", "out")
# Relative path from source root to our output files. e.g. "out"
return os.path.normpath(os.path.join(generator_dir, output_dir)) | [
"def",
"ComputeOutputDir",
"(",
"params",
")",
":",
"# generator_dir: relative path from pwd to where make puts build files.",
"# Makes migrating from make to ninja easier, ninja doesn't put anything here.",
"generator_dir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"params",
"[",
"\"options\"",
"]",
".",
"generator_output",
"or",
"\".\"",
")",
"# output_dir: relative path from generator_dir to the build directory.",
"output_dir",
"=",
"params",
".",
"get",
"(",
"\"generator_flags\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"output_dir\"",
",",
"\"out\"",
")",
"# Relative path from source root to our output files. e.g. \"out\"",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"generator_dir",
",",
"output_dir",
")",
")"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/gyp/pylib/gyp/generator/ninja.py#L2047-L2057 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py | python | ConsoleDebugger.do_ba | (self, arg) | [~thread] ba <a|w|e> <1|2|4|8> <address> - set hardware breakpoint | [~thread] ba <a|w|e> <1|2|4|8> <address> - set hardware breakpoint | [
"[",
"~thread",
"]",
"ba",
"<a|w|e",
">",
"<1|2|4|8",
">",
"<address",
">",
"-",
"set",
"hardware",
"breakpoint"
] | def do_ba(self, arg):
"""
[~thread] ba <a|w|e> <1|2|4|8> <address> - set hardware breakpoint
"""
debug = self.debug
thread = self.get_thread_from_prefix()
pid = thread.get_pid()
tid = thread.get_tid()
if not debug.is_debugee(pid):
raise CmdError("target thread is not being debugged")
token_list = self.split_tokens(arg, 3, 3)
access = token_list[0].lower()
size = token_list[1]
address = token_list[2]
if access == 'a':
access = debug.BP_BREAK_ON_ACCESS
elif access == 'w':
access = debug.BP_BREAK_ON_WRITE
elif access == 'e':
access = debug.BP_BREAK_ON_EXECUTION
else:
raise CmdError("bad access type: %s" % token_list[0])
if size == '1':
size = debug.BP_WATCH_BYTE
elif size == '2':
size = debug.BP_WATCH_WORD
elif size == '4':
size = debug.BP_WATCH_DWORD
elif size == '8':
size = debug.BP_WATCH_QWORD
else:
raise CmdError("bad breakpoint size: %s" % size)
thread = self.get_thread_from_prefix()
tid = thread.get_tid()
pid = thread.get_pid()
if not debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
address = self.input_address(address, pid)
if debug.has_hardware_breakpoint(tid, address):
debug.erase_hardware_breakpoint(tid, address)
debug.define_hardware_breakpoint(tid, address, access, size)
debug.enable_hardware_breakpoint(tid, address) | [
"def",
"do_ba",
"(",
"self",
",",
"arg",
")",
":",
"debug",
"=",
"self",
".",
"debug",
"thread",
"=",
"self",
".",
"get_thread_from_prefix",
"(",
")",
"pid",
"=",
"thread",
".",
"get_pid",
"(",
")",
"tid",
"=",
"thread",
".",
"get_tid",
"(",
")",
"if",
"not",
"debug",
".",
"is_debugee",
"(",
"pid",
")",
":",
"raise",
"CmdError",
"(",
"\"target thread is not being debugged\"",
")",
"token_list",
"=",
"self",
".",
"split_tokens",
"(",
"arg",
",",
"3",
",",
"3",
")",
"access",
"=",
"token_list",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"size",
"=",
"token_list",
"[",
"1",
"]",
"address",
"=",
"token_list",
"[",
"2",
"]",
"if",
"access",
"==",
"'a'",
":",
"access",
"=",
"debug",
".",
"BP_BREAK_ON_ACCESS",
"elif",
"access",
"==",
"'w'",
":",
"access",
"=",
"debug",
".",
"BP_BREAK_ON_WRITE",
"elif",
"access",
"==",
"'e'",
":",
"access",
"=",
"debug",
".",
"BP_BREAK_ON_EXECUTION",
"else",
":",
"raise",
"CmdError",
"(",
"\"bad access type: %s\"",
"%",
"token_list",
"[",
"0",
"]",
")",
"if",
"size",
"==",
"'1'",
":",
"size",
"=",
"debug",
".",
"BP_WATCH_BYTE",
"elif",
"size",
"==",
"'2'",
":",
"size",
"=",
"debug",
".",
"BP_WATCH_WORD",
"elif",
"size",
"==",
"'4'",
":",
"size",
"=",
"debug",
".",
"BP_WATCH_DWORD",
"elif",
"size",
"==",
"'8'",
":",
"size",
"=",
"debug",
".",
"BP_WATCH_QWORD",
"else",
":",
"raise",
"CmdError",
"(",
"\"bad breakpoint size: %s\"",
"%",
"size",
")",
"thread",
"=",
"self",
".",
"get_thread_from_prefix",
"(",
")",
"tid",
"=",
"thread",
".",
"get_tid",
"(",
")",
"pid",
"=",
"thread",
".",
"get_pid",
"(",
")",
"if",
"not",
"debug",
".",
"is_debugee",
"(",
"pid",
")",
":",
"raise",
"CmdError",
"(",
"\"target process is not being debugged\"",
")",
"address",
"=",
"self",
".",
"input_address",
"(",
"address",
",",
"pid",
")",
"if",
"debug",
".",
"has_hardware_breakpoint",
"(",
"tid",
",",
"address",
")",
":",
"debug",
".",
"erase_hardware_breakpoint",
"(",
"tid",
",",
"address",
")",
"debug",
".",
"define_hardware_breakpoint",
"(",
"tid",
",",
"address",
",",
"access",
",",
"size",
")",
"debug",
".",
"enable_hardware_breakpoint",
"(",
"tid",
",",
"address",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py#L1599-L1640 |
||
wotermelon/toJump | 3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f | lib/win/systrace/catapult/third_party/pyserial/serial/serialutil.py | python | SerialBase.getPort | (self) | return self._port | Get the current port setting. The value that was passed on init or using
setPort() is passed back. See also the attribute portstr which contains
the name of the port as a string. | Get the current port setting. The value that was passed on init or using
setPort() is passed back. See also the attribute portstr which contains
the name of the port as a string. | [
"Get",
"the",
"current",
"port",
"setting",
".",
"The",
"value",
"that",
"was",
"passed",
"on",
"init",
"or",
"using",
"setPort",
"()",
"is",
"passed",
"back",
".",
"See",
"also",
"the",
"attribute",
"portstr",
"which",
"contains",
"the",
"name",
"of",
"the",
"port",
"as",
"a",
"string",
"."
] | def getPort(self):
"""Get the current port setting. The value that was passed on init or using
setPort() is passed back. See also the attribute portstr which contains
the name of the port as a string."""
return self._port | [
"def",
"getPort",
"(",
"self",
")",
":",
"return",
"self",
".",
"_port"
] | https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/win/systrace/catapult/third_party/pyserial/serial/serialutil.py#L324-L328 |
|
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | api/src/opentrons/config/advanced_settings.py | python | _migrate13to14 | (previous: SettingsMap) | return newmap | Migrate to version 14 of the feature flags file.
- Removes deprecated enableHttpProtocolSessions option | Migrate to version 14 of the feature flags file. | [
"Migrate",
"to",
"version",
"14",
"of",
"the",
"feature",
"flags",
"file",
"."
] | def _migrate13to14(previous: SettingsMap) -> SettingsMap:
"""Migrate to version 14 of the feature flags file.
- Removes deprecated enableHttpProtocolSessions option
"""
removals = ["enableHttpProtocolSessions"]
newmap = {k: v for k, v in previous.items() if k not in removals}
return newmap | [
"def",
"_migrate13to14",
"(",
"previous",
":",
"SettingsMap",
")",
"->",
"SettingsMap",
":",
"removals",
"=",
"[",
"\"enableHttpProtocolSessions\"",
"]",
"newmap",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"previous",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"removals",
"}",
"return",
"newmap"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/config/advanced_settings.py#L421-L428 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | bt5/erp5_payroll/DocumentTemplateItem/portal_components/document.erp5.PaySheetModel.py | python | PaySheetModel.getInheritanceReferenceDict | (self, context, portal_type_list,
property_list=None) | return model_reference_dict | Returns a dict with the model url as key and a list of reference as
value. A Reference can appear only one time in the final output.
If property_list is not empty, documents which don't have any of theses
properties will be skipped. | Returns a dict with the model url as key and a list of reference as
value. A Reference can appear only one time in the final output.
If property_list is not empty, documents which don't have any of theses
properties will be skipped. | [
"Returns",
"a",
"dict",
"with",
"the",
"model",
"url",
"as",
"key",
"and",
"a",
"list",
"of",
"reference",
"as",
"value",
".",
"A",
"Reference",
"can",
"appear",
"only",
"one",
"time",
"in",
"the",
"final",
"output",
".",
"If",
"property_list",
"is",
"not",
"empty",
"documents",
"which",
"don",
"t",
"have",
"any",
"of",
"theses",
"properties",
"will",
"be",
"skipped",
"."
] | def getInheritanceReferenceDict(self, context, portal_type_list,
property_list=None):
'''Returns a dict with the model url as key and a list of reference as
value. A Reference can appear only one time in the final output.
If property_list is not empty, documents which don't have any of theses
properties will be skipped.
'''
reference_list = []
model_reference_dict = {}
for model in self.findEffectiveSpecialiseValueList(context):
id_list = []
model_reference_list = model.getReferenceDict(
portal_type_list, property_list=property_list)
for reference in model_reference_list.keys():
if reference not in reference_list:
reference_list.append(reference)
id_list.append(model_reference_list[reference])
if len(id_list) != 0:
model_reference_dict[model.getRelativeUrl()]=id_list
return model_reference_dict | [
"def",
"getInheritanceReferenceDict",
"(",
"self",
",",
"context",
",",
"portal_type_list",
",",
"property_list",
"=",
"None",
")",
":",
"reference_list",
"=",
"[",
"]",
"model_reference_dict",
"=",
"{",
"}",
"for",
"model",
"in",
"self",
".",
"findEffectiveSpecialiseValueList",
"(",
"context",
")",
":",
"id_list",
"=",
"[",
"]",
"model_reference_list",
"=",
"model",
".",
"getReferenceDict",
"(",
"portal_type_list",
",",
"property_list",
"=",
"property_list",
")",
"for",
"reference",
"in",
"model_reference_list",
".",
"keys",
"(",
")",
":",
"if",
"reference",
"not",
"in",
"reference_list",
":",
"reference_list",
".",
"append",
"(",
"reference",
")",
"id_list",
".",
"append",
"(",
"model_reference_list",
"[",
"reference",
"]",
")",
"if",
"len",
"(",
"id_list",
")",
"!=",
"0",
":",
"model_reference_dict",
"[",
"model",
".",
"getRelativeUrl",
"(",
")",
"]",
"=",
"id_list",
"return",
"model_reference_dict"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_payroll/DocumentTemplateItem/portal_components/document.erp5.PaySheetModel.py#L112-L131 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/lib2to3/pytree.py | python | Base.pre_order | (self) | Return a pre-order iterator for the tree.
This must be implemented by the concrete subclass. | Return a pre-order iterator for the tree. | [
"Return",
"a",
"pre",
"-",
"order",
"iterator",
"for",
"the",
"tree",
"."
] | def pre_order(self):
"""
Return a pre-order iterator for the tree.
This must be implemented by the concrete subclass.
"""
raise NotImplementedError | [
"def",
"pre_order",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/lib2to3/pytree.py#L104-L110 |
||
Wscats/python-tutorial | 02ad3b7cd4ac179759e1b956cc707989575ca43b | tutorial/swiper/backend/lib/sms.py | python | gen_verify_code | (length=4) | return str(code) | 生成验证码 | 生成验证码 | [
"生成验证码"
] | def gen_verify_code(length=4):
'''生成验证码'''
if length <= 0:
length = 1
code = random.randrange(10 ** (length - 1), 10 ** (length))
return str(code) | [
"def",
"gen_verify_code",
"(",
"length",
"=",
"4",
")",
":",
"if",
"length",
"<=",
"0",
":",
"length",
"=",
"1",
"code",
"=",
"random",
".",
"randrange",
"(",
"10",
"**",
"(",
"length",
"-",
"1",
")",
",",
"10",
"**",
"(",
"length",
")",
")",
"return",
"str",
"(",
"code",
")"
] | https://github.com/Wscats/python-tutorial/blob/02ad3b7cd4ac179759e1b956cc707989575ca43b/tutorial/swiper/backend/lib/sms.py#L9-L14 |
|
jupyter/notebook | 26626343384195a1f4f5461ba42eb3e133655976 | notebook/services/kernels/handlers.py | python | ZMQChannelsHandler._handle_kernel_info_reply | (self, msg) | process the kernel_info_reply
enabling msg spec adaptation, if necessary | process the kernel_info_reply | [
"process",
"the",
"kernel_info_reply"
] | def _handle_kernel_info_reply(self, msg):
"""process the kernel_info_reply
enabling msg spec adaptation, if necessary
"""
idents,msg = self.session.feed_identities(msg)
try:
msg = self.session.deserialize(msg)
except:
self.log.error("Bad kernel_info reply", exc_info=True)
self._kernel_info_future.set_result({})
return
else:
info = msg['content']
self.log.debug("Received kernel info: %s", info)
if msg['msg_type'] != 'kernel_info_reply' or 'protocol_version' not in info:
self.log.error("Kernel info request failed, assuming current %s", info)
info = {}
self._finish_kernel_info(info)
# close the kernel_info channel, we don't need it anymore
if self.kernel_info_channel:
self.kernel_info_channel.close()
self.kernel_info_channel = None | [
"def",
"_handle_kernel_info_reply",
"(",
"self",
",",
"msg",
")",
":",
"idents",
",",
"msg",
"=",
"self",
".",
"session",
".",
"feed_identities",
"(",
"msg",
")",
"try",
":",
"msg",
"=",
"self",
".",
"session",
".",
"deserialize",
"(",
"msg",
")",
"except",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Bad kernel_info reply\"",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"_kernel_info_future",
".",
"set_result",
"(",
"{",
"}",
")",
"return",
"else",
":",
"info",
"=",
"msg",
"[",
"'content'",
"]",
"self",
".",
"log",
".",
"debug",
"(",
"\"Received kernel info: %s\"",
",",
"info",
")",
"if",
"msg",
"[",
"'msg_type'",
"]",
"!=",
"'kernel_info_reply'",
"or",
"'protocol_version'",
"not",
"in",
"info",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Kernel info request failed, assuming current %s\"",
",",
"info",
")",
"info",
"=",
"{",
"}",
"self",
".",
"_finish_kernel_info",
"(",
"info",
")",
"# close the kernel_info channel, we don't need it anymore",
"if",
"self",
".",
"kernel_info_channel",
":",
"self",
".",
"kernel_info_channel",
".",
"close",
"(",
")",
"self",
".",
"kernel_info_channel",
"=",
"None"
] | https://github.com/jupyter/notebook/blob/26626343384195a1f4f5461ba42eb3e133655976/notebook/services/kernels/handlers.py#L274-L297 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/spidershim/spidermonkey/python/mozbuild/mozpack/mozjar.py | python | JarFileReader.compressed_data | (self) | return self._data[:self.compressed_size] | Return the raw compressed data. | Return the raw compressed data. | [
"Return",
"the",
"raw",
"compressed",
"data",
"."
] | def compressed_data(self):
'''
Return the raw compressed data.
'''
return self._data[:self.compressed_size] | [
"def",
"compressed_data",
"(",
"self",
")",
":",
"return",
"self",
".",
"_data",
"[",
":",
"self",
".",
"compressed_size",
"]"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/spidershim/spidermonkey/python/mozbuild/mozpack/mozjar.py#L306-L310 |
|
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Backup/20181226200439/python-markdown/st3/markdown/blockprocessors.py | python | BlockProcessor.lastChild | (self, parent) | Return the last child of an etree element. | Return the last child of an etree element. | [
"Return",
"the",
"last",
"child",
"of",
"an",
"etree",
"element",
"."
] | def lastChild(self, parent):
""" Return the last child of an etree element. """
if len(parent):
return parent[-1]
else:
return None | [
"def",
"lastChild",
"(",
"self",
",",
"parent",
")",
":",
"if",
"len",
"(",
"parent",
")",
":",
"return",
"parent",
"[",
"-",
"1",
"]",
"else",
":",
"return",
"None"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20181226200439/python-markdown/st3/markdown/blockprocessors.py#L56-L61 |
||
prometheus-ar/vot.ar | 72d8fa1ea08fe417b64340b98dff68df8364afdf | msa/core/armve/protocol.py | python | RFID.__init__ | (self, buffer=None) | Constructor del dispositivo RFID. | Constructor del dispositivo RFID. | [
"Constructor",
"del",
"dispositivo",
"RFID",
"."
] | def __init__(self, buffer=None):
"""Constructor del dispositivo RFID."""
Device.__init__(self, buffer)
self._device_type = DEV_RFID | [
"def",
"__init__",
"(",
"self",
",",
"buffer",
"=",
"None",
")",
":",
"Device",
".",
"__init__",
"(",
"self",
",",
"buffer",
")",
"self",
".",
"_device_type",
"=",
"DEV_RFID"
] | https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/core/armve/protocol.py#L1705-L1708 |
||
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | 3rd_party/python3/site-packages/cherrypy/_cpdispatch.py | python | Dispatcher.find_handler | (self, path) | return None, [] | Return the appropriate page handler, plus any virtual path.
This will return two objects. The first will be a callable,
which can be used to generate page output. Any parameters from
the query string or request body will be sent to that callable
as keyword arguments.
The callable is found by traversing the application's tree,
starting from cherrypy.request.app.root, and matching path
components to successive objects in the tree. For example, the
URL "/path/to/handler" might return root.path.to.handler.
The second object returned will be a list of names which are
'virtual path' components: parts of the URL which are dynamic,
and were not used when looking up the handler.
These virtual path components are passed to the handler as
positional arguments. | Return the appropriate page handler, plus any virtual path. | [
"Return",
"the",
"appropriate",
"page",
"handler",
"plus",
"any",
"virtual",
"path",
"."
] | def find_handler(self, path):
"""Return the appropriate page handler, plus any virtual path.
This will return two objects. The first will be a callable,
which can be used to generate page output. Any parameters from
the query string or request body will be sent to that callable
as keyword arguments.
The callable is found by traversing the application's tree,
starting from cherrypy.request.app.root, and matching path
components to successive objects in the tree. For example, the
URL "/path/to/handler" might return root.path.to.handler.
The second object returned will be a list of names which are
'virtual path' components: parts of the URL which are dynamic,
and were not used when looking up the handler.
These virtual path components are passed to the handler as
positional arguments.
"""
request = cherrypy.serving.request
app = request.app
root = app.root
dispatch_name = self.dispatch_method_name
# Get config for the root object/path.
fullpath = [x for x in path.strip('/').split('/') if x] + ['index']
fullpath_len = len(fullpath)
segleft = fullpath_len
nodeconf = {}
if hasattr(root, '_cp_config'):
nodeconf.update(root._cp_config)
if '/' in app.config:
nodeconf.update(app.config['/'])
object_trail = [['root', root, nodeconf, segleft]]
node = root
iternames = fullpath[:]
while iternames:
name = iternames[0]
# map to legal Python identifiers (e.g. replace '.' with '_')
objname = name.translate(self.translate)
nodeconf = {}
subnode = getattr(node, objname, None)
pre_len = len(iternames)
if subnode is None:
dispatch = getattr(node, dispatch_name, None)
if dispatch and hasattr(dispatch, '__call__') and not \
getattr(dispatch, 'exposed', False) and \
pre_len > 1:
# Don't expose the hidden 'index' token to _cp_dispatch
# We skip this if pre_len == 1 since it makes no sense
# to call a dispatcher when we have no tokens left.
index_name = iternames.pop()
subnode = dispatch(vpath=iternames)
iternames.append(index_name)
else:
# We didn't find a path, but keep processing in case there
# is a default() handler.
iternames.pop(0)
else:
# We found the path, remove the vpath entry
iternames.pop(0)
segleft = len(iternames)
if segleft > pre_len:
# No path segment was removed. Raise an error.
raise cherrypy.CherryPyException(
'A vpath segment was added. Custom dispatchers may only '
'remove elements. While trying to process '
'{0} in {1}'.format(name, fullpath)
)
elif segleft == pre_len:
# Assume that the handler used the current path segment, but
# did not pop it. This allows things like
# return getattr(self, vpath[0], None)
iternames.pop(0)
segleft -= 1
node = subnode
if node is not None:
# Get _cp_config attached to this node.
if hasattr(node, '_cp_config'):
nodeconf.update(node._cp_config)
# Mix in values from app.config for this path.
existing_len = fullpath_len - pre_len
if existing_len != 0:
curpath = '/' + '/'.join(fullpath[0:existing_len])
else:
curpath = ''
new_segs = fullpath[fullpath_len - pre_len:fullpath_len - segleft]
for seg in new_segs:
curpath += '/' + seg
if curpath in app.config:
nodeconf.update(app.config[curpath])
object_trail.append([name, node, nodeconf, segleft])
def set_conf():
"""Collapse all object_trail config into cherrypy.request.config.
"""
base = cherrypy.config.copy()
# Note that we merge the config from each node
# even if that node was None.
for name, obj, conf, segleft in object_trail:
base.update(conf)
if 'tools.staticdir.dir' in conf:
base['tools.staticdir.section'] = '/' + \
'/'.join(fullpath[0:fullpath_len - segleft])
return base
# Try successive objects (reverse order)
num_candidates = len(object_trail) - 1
for i in range(num_candidates, -1, -1):
name, candidate, nodeconf, segleft = object_trail[i]
if candidate is None:
continue
# Try a "default" method on the current leaf.
if hasattr(candidate, 'default'):
defhandler = candidate.default
if getattr(defhandler, 'exposed', False):
# Insert any extra _cp_config from the default handler.
conf = getattr(defhandler, '_cp_config', {})
object_trail.insert(
i + 1, ['default', defhandler, conf, segleft])
request.config = set_conf()
# See https://github.com/cherrypy/cherrypy/issues/613
request.is_index = path.endswith('/')
return defhandler, fullpath[fullpath_len - segleft:-1]
# Uncomment the next line to restrict positional params to
# "default".
# if i < num_candidates - 2: continue
# Try the current leaf.
if getattr(candidate, 'exposed', False):
request.config = set_conf()
if i == num_candidates:
# We found the extra ".index". Mark request so tools
# can redirect if path_info has no trailing slash.
request.is_index = True
else:
# We're not at an 'index' handler. Mark request so tools
# can redirect if path_info has NO trailing slash.
# Note that this also includes handlers which take
# positional parameters (virtual paths).
request.is_index = False
return candidate, fullpath[fullpath_len - segleft:-1]
# We didn't find anything
request.config = set_conf()
return None, [] | [
"def",
"find_handler",
"(",
"self",
",",
"path",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"app",
"=",
"request",
".",
"app",
"root",
"=",
"app",
".",
"root",
"dispatch_name",
"=",
"self",
".",
"dispatch_method_name",
"# Get config for the root object/path.",
"fullpath",
"=",
"[",
"x",
"for",
"x",
"in",
"path",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"x",
"]",
"+",
"[",
"'index'",
"]",
"fullpath_len",
"=",
"len",
"(",
"fullpath",
")",
"segleft",
"=",
"fullpath_len",
"nodeconf",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"root",
",",
"'_cp_config'",
")",
":",
"nodeconf",
".",
"update",
"(",
"root",
".",
"_cp_config",
")",
"if",
"'/'",
"in",
"app",
".",
"config",
":",
"nodeconf",
".",
"update",
"(",
"app",
".",
"config",
"[",
"'/'",
"]",
")",
"object_trail",
"=",
"[",
"[",
"'root'",
",",
"root",
",",
"nodeconf",
",",
"segleft",
"]",
"]",
"node",
"=",
"root",
"iternames",
"=",
"fullpath",
"[",
":",
"]",
"while",
"iternames",
":",
"name",
"=",
"iternames",
"[",
"0",
"]",
"# map to legal Python identifiers (e.g. replace '.' with '_')",
"objname",
"=",
"name",
".",
"translate",
"(",
"self",
".",
"translate",
")",
"nodeconf",
"=",
"{",
"}",
"subnode",
"=",
"getattr",
"(",
"node",
",",
"objname",
",",
"None",
")",
"pre_len",
"=",
"len",
"(",
"iternames",
")",
"if",
"subnode",
"is",
"None",
":",
"dispatch",
"=",
"getattr",
"(",
"node",
",",
"dispatch_name",
",",
"None",
")",
"if",
"dispatch",
"and",
"hasattr",
"(",
"dispatch",
",",
"'__call__'",
")",
"and",
"not",
"getattr",
"(",
"dispatch",
",",
"'exposed'",
",",
"False",
")",
"and",
"pre_len",
">",
"1",
":",
"# Don't expose the hidden 'index' token to _cp_dispatch",
"# We skip this if pre_len == 1 since it makes no sense",
"# to call a dispatcher when we have no tokens left.",
"index_name",
"=",
"iternames",
".",
"pop",
"(",
")",
"subnode",
"=",
"dispatch",
"(",
"vpath",
"=",
"iternames",
")",
"iternames",
".",
"append",
"(",
"index_name",
")",
"else",
":",
"# We didn't find a path, but keep processing in case there",
"# is a default() handler.",
"iternames",
".",
"pop",
"(",
"0",
")",
"else",
":",
"# We found the path, remove the vpath entry",
"iternames",
".",
"pop",
"(",
"0",
")",
"segleft",
"=",
"len",
"(",
"iternames",
")",
"if",
"segleft",
">",
"pre_len",
":",
"# No path segment was removed. Raise an error.",
"raise",
"cherrypy",
".",
"CherryPyException",
"(",
"'A vpath segment was added. Custom dispatchers may only '",
"'remove elements. While trying to process '",
"'{0} in {1}'",
".",
"format",
"(",
"name",
",",
"fullpath",
")",
")",
"elif",
"segleft",
"==",
"pre_len",
":",
"# Assume that the handler used the current path segment, but",
"# did not pop it. This allows things like",
"# return getattr(self, vpath[0], None)",
"iternames",
".",
"pop",
"(",
"0",
")",
"segleft",
"-=",
"1",
"node",
"=",
"subnode",
"if",
"node",
"is",
"not",
"None",
":",
"# Get _cp_config attached to this node.",
"if",
"hasattr",
"(",
"node",
",",
"'_cp_config'",
")",
":",
"nodeconf",
".",
"update",
"(",
"node",
".",
"_cp_config",
")",
"# Mix in values from app.config for this path.",
"existing_len",
"=",
"fullpath_len",
"-",
"pre_len",
"if",
"existing_len",
"!=",
"0",
":",
"curpath",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"fullpath",
"[",
"0",
":",
"existing_len",
"]",
")",
"else",
":",
"curpath",
"=",
"''",
"new_segs",
"=",
"fullpath",
"[",
"fullpath_len",
"-",
"pre_len",
":",
"fullpath_len",
"-",
"segleft",
"]",
"for",
"seg",
"in",
"new_segs",
":",
"curpath",
"+=",
"'/'",
"+",
"seg",
"if",
"curpath",
"in",
"app",
".",
"config",
":",
"nodeconf",
".",
"update",
"(",
"app",
".",
"config",
"[",
"curpath",
"]",
")",
"object_trail",
".",
"append",
"(",
"[",
"name",
",",
"node",
",",
"nodeconf",
",",
"segleft",
"]",
")",
"def",
"set_conf",
"(",
")",
":",
"\"\"\"Collapse all object_trail config into cherrypy.request.config.\n \"\"\"",
"base",
"=",
"cherrypy",
".",
"config",
".",
"copy",
"(",
")",
"# Note that we merge the config from each node",
"# even if that node was None.",
"for",
"name",
",",
"obj",
",",
"conf",
",",
"segleft",
"in",
"object_trail",
":",
"base",
".",
"update",
"(",
"conf",
")",
"if",
"'tools.staticdir.dir'",
"in",
"conf",
":",
"base",
"[",
"'tools.staticdir.section'",
"]",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"fullpath",
"[",
"0",
":",
"fullpath_len",
"-",
"segleft",
"]",
")",
"return",
"base",
"# Try successive objects (reverse order)",
"num_candidates",
"=",
"len",
"(",
"object_trail",
")",
"-",
"1",
"for",
"i",
"in",
"range",
"(",
"num_candidates",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"name",
",",
"candidate",
",",
"nodeconf",
",",
"segleft",
"=",
"object_trail",
"[",
"i",
"]",
"if",
"candidate",
"is",
"None",
":",
"continue",
"# Try a \"default\" method on the current leaf.",
"if",
"hasattr",
"(",
"candidate",
",",
"'default'",
")",
":",
"defhandler",
"=",
"candidate",
".",
"default",
"if",
"getattr",
"(",
"defhandler",
",",
"'exposed'",
",",
"False",
")",
":",
"# Insert any extra _cp_config from the default handler.",
"conf",
"=",
"getattr",
"(",
"defhandler",
",",
"'_cp_config'",
",",
"{",
"}",
")",
"object_trail",
".",
"insert",
"(",
"i",
"+",
"1",
",",
"[",
"'default'",
",",
"defhandler",
",",
"conf",
",",
"segleft",
"]",
")",
"request",
".",
"config",
"=",
"set_conf",
"(",
")",
"# See https://github.com/cherrypy/cherrypy/issues/613",
"request",
".",
"is_index",
"=",
"path",
".",
"endswith",
"(",
"'/'",
")",
"return",
"defhandler",
",",
"fullpath",
"[",
"fullpath_len",
"-",
"segleft",
":",
"-",
"1",
"]",
"# Uncomment the next line to restrict positional params to",
"# \"default\".",
"# if i < num_candidates - 2: continue",
"# Try the current leaf.",
"if",
"getattr",
"(",
"candidate",
",",
"'exposed'",
",",
"False",
")",
":",
"request",
".",
"config",
"=",
"set_conf",
"(",
")",
"if",
"i",
"==",
"num_candidates",
":",
"# We found the extra \".index\". Mark request so tools",
"# can redirect if path_info has no trailing slash.",
"request",
".",
"is_index",
"=",
"True",
"else",
":",
"# We're not at an 'index' handler. Mark request so tools",
"# can redirect if path_info has NO trailing slash.",
"# Note that this also includes handlers which take",
"# positional parameters (virtual paths).",
"request",
".",
"is_index",
"=",
"False",
"return",
"candidate",
",",
"fullpath",
"[",
"fullpath_len",
"-",
"segleft",
":",
"-",
"1",
"]",
"# We didn't find anything",
"request",
".",
"config",
"=",
"set_conf",
"(",
")",
"return",
"None",
",",
"[",
"]"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cherrypy/_cpdispatch.py#L299-L452 |
|
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/chakrashim/third_party/jinja2/jinja2/environment.py | python | Environment.getattr | (self, obj, attribute) | Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a bytestring. | Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a bytestring. | [
"Get",
"an",
"item",
"or",
"attribute",
"of",
"an",
"object",
"but",
"prefer",
"the",
"attribute",
".",
"Unlike",
":",
"meth",
":",
"getitem",
"the",
"attribute",
"*",
"must",
"*",
"be",
"a",
"bytestring",
"."
] | def getattr(self, obj, attribute):
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a bytestring.
"""
try:
return getattr(obj, attribute)
except AttributeError:
pass
try:
return obj[attribute]
except (TypeError, LookupError, AttributeError):
return self.undefined(obj=obj, name=attribute) | [
"def",
"getattr",
"(",
"self",
",",
"obj",
",",
"attribute",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"obj",
",",
"attribute",
")",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"return",
"obj",
"[",
"attribute",
"]",
"except",
"(",
"TypeError",
",",
"LookupError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"undefined",
"(",
"obj",
"=",
"obj",
",",
"name",
"=",
"attribute",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/chakrashim/third_party/jinja2/jinja2/environment.py#L403-L414 |
||
robplatek/Massive-Coupon---Open-source-groupon-clone | 1d725356eeb41c6328605cef6e8779ab472db2b4 | tagging/fields.py | python | TagField._save | (self, **kwargs) | Save tags back to the database | Save tags back to the database | [
"Save",
"tags",
"back",
"to",
"the",
"database"
] | def _save(self, **kwargs): #signal, sender, instance):
"""
Save tags back to the database
"""
tags = self._get_instance_tag_cache(kwargs['instance'])
Tag.objects.update_tags(kwargs['instance'], tags) | [
"def",
"_save",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"#signal, sender, instance):",
"tags",
"=",
"self",
".",
"_get_instance_tag_cache",
"(",
"kwargs",
"[",
"'instance'",
"]",
")",
"Tag",
".",
"objects",
".",
"update_tags",
"(",
"kwargs",
"[",
"'instance'",
"]",
",",
"tags",
")"
] | https://github.com/robplatek/Massive-Coupon---Open-source-groupon-clone/blob/1d725356eeb41c6328605cef6e8779ab472db2b4/tagging/fields.py#L71-L76 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/Bastion.py | python | Bastion | (object, filter = lambda name: name[:1] != '_',
name=None, bastionclass=BastionClass) | return bastionclass(get2, name) | Create a bastion for an object, using an optional filter.
See the Bastion module's documentation for background.
Arguments:
object - the original object
filter - a predicate that decides whether a function name is OK;
by default all names are OK that don't start with '_'
name - the name of the object; default repr(object)
bastionclass - class used to create the bastion; default BastionClass | Create a bastion for an object, using an optional filter. | [
"Create",
"a",
"bastion",
"for",
"an",
"object",
"using",
"an",
"optional",
"filter",
"."
] | def Bastion(object, filter = lambda name: name[:1] != '_',
name=None, bastionclass=BastionClass):
"""Create a bastion for an object, using an optional filter.
See the Bastion module's documentation for background.
Arguments:
object - the original object
filter - a predicate that decides whether a function name is OK;
by default all names are OK that don't start with '_'
name - the name of the object; default repr(object)
bastionclass - class used to create the bastion; default BastionClass
"""
raise RuntimeError, "This code is not secure in Python 2.2 and later"
# Note: we define *two* ad-hoc functions here, get1 and get2.
# Both are intended to be called in the same way: get(name).
# It is clear that the real work (getting the attribute
# from the object and calling the filter) is done in get1.
# Why can't we pass get1 to the bastion? Because the user
# would be able to override the filter argument! With get2,
# overriding the default argument is no security loophole:
# all it does is call it.
# Also notice that we can't place the object and filter as
# instance variables on the bastion object itself, since
# the user has full access to all instance variables!
def get1(name, object=object, filter=filter):
"""Internal function for Bastion(). See source comments."""
if filter(name):
attribute = getattr(object, name)
if type(attribute) == MethodType:
return attribute
raise AttributeError, name
def get2(name, get1=get1):
"""Internal function for Bastion(). See source comments."""
return get1(name)
if name is None:
name = repr(object)
return bastionclass(get2, name) | [
"def",
"Bastion",
"(",
"object",
",",
"filter",
"=",
"lambda",
"name",
":",
"name",
"[",
":",
"1",
"]",
"!=",
"'_'",
",",
"name",
"=",
"None",
",",
"bastionclass",
"=",
"BastionClass",
")",
":",
"raise",
"RuntimeError",
",",
"\"This code is not secure in Python 2.2 and later\"",
"# Note: we define *two* ad-hoc functions here, get1 and get2.",
"# Both are intended to be called in the same way: get(name).",
"# It is clear that the real work (getting the attribute",
"# from the object and calling the filter) is done in get1.",
"# Why can't we pass get1 to the bastion? Because the user",
"# would be able to override the filter argument! With get2,",
"# overriding the default argument is no security loophole:",
"# all it does is call it.",
"# Also notice that we can't place the object and filter as",
"# instance variables on the bastion object itself, since",
"# the user has full access to all instance variables!",
"def",
"get1",
"(",
"name",
",",
"object",
"=",
"object",
",",
"filter",
"=",
"filter",
")",
":",
"\"\"\"Internal function for Bastion(). See source comments.\"\"\"",
"if",
"filter",
"(",
"name",
")",
":",
"attribute",
"=",
"getattr",
"(",
"object",
",",
"name",
")",
"if",
"type",
"(",
"attribute",
")",
"==",
"MethodType",
":",
"return",
"attribute",
"raise",
"AttributeError",
",",
"name",
"def",
"get2",
"(",
"name",
",",
"get1",
"=",
"get1",
")",
":",
"\"\"\"Internal function for Bastion(). See source comments.\"\"\"",
"return",
"get1",
"(",
"name",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"repr",
"(",
"object",
")",
"return",
"bastionclass",
"(",
"get2",
",",
"name",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/Bastion.py#L87-L131 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/mhlib.py | python | MH.listfolders | (self) | return folders | Return the names of the top-level folders. | Return the names of the top-level folders. | [
"Return",
"the",
"names",
"of",
"the",
"top",
"-",
"level",
"folders",
"."
] | def listfolders(self):
"""Return the names of the top-level folders."""
folders = []
path = self.getpath()
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isdir(fullname):
folders.append(name)
folders.sort()
return folders | [
"def",
"listfolders",
"(",
"self",
")",
":",
"folders",
"=",
"[",
"]",
"path",
"=",
"self",
".",
"getpath",
"(",
")",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullname",
")",
":",
"folders",
".",
"append",
"(",
"name",
")",
"folders",
".",
"sort",
"(",
")",
"return",
"folders"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/mhlib.py#L144-L153 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/sale_product_matrix/models/sale_order.py | python | SaleOrder.get_report_matrixes | (self) | return matrixes | Reporting method.
:return: array of matrices to display in the report
:rtype: list | Reporting method. | [
"Reporting",
"method",
"."
] | def get_report_matrixes(self):
"""Reporting method.
:return: array of matrices to display in the report
:rtype: list
"""
matrixes = []
if self.report_grids:
grid_configured_templates = self.order_line.filtered('is_configurable_product').product_template_id.filtered(lambda ptmpl: ptmpl.product_add_mode == 'matrix')
for template in grid_configured_templates:
if len(self.order_line.filtered(lambda line: line.product_template_id == template)) > 1:
# TODO do we really want the whole matrix even if there isn't a lot of lines ??
matrixes.append(self._get_matrix(template))
return matrixes | [
"def",
"get_report_matrixes",
"(",
"self",
")",
":",
"matrixes",
"=",
"[",
"]",
"if",
"self",
".",
"report_grids",
":",
"grid_configured_templates",
"=",
"self",
".",
"order_line",
".",
"filtered",
"(",
"'is_configurable_product'",
")",
".",
"product_template_id",
".",
"filtered",
"(",
"lambda",
"ptmpl",
":",
"ptmpl",
".",
"product_add_mode",
"==",
"'matrix'",
")",
"for",
"template",
"in",
"grid_configured_templates",
":",
"if",
"len",
"(",
"self",
".",
"order_line",
".",
"filtered",
"(",
"lambda",
"line",
":",
"line",
".",
"product_template_id",
"==",
"template",
")",
")",
">",
"1",
":",
"# TODO do we really want the whole matrix even if there isn't a lot of lines ??",
"matrixes",
".",
"append",
"(",
"self",
".",
"_get_matrix",
"(",
"template",
")",
")",
"return",
"matrixes"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/sale_product_matrix/models/sale_order.py#L162-L175 |
|
PaulGuo/F2E.im | 6d21eaa4b6372d3846a079a36f4d35121695dd91 | lib/gravatar.py | python | sanitize_email | (email) | return email.lower().strip() | Returns an e-mail address in lower-case and strip leading and trailing
whitespaces.
>>> sanitize_email(' MyEmailAddress@example.com ')
'myemailaddress@example.com' | Returns an e-mail address in lower-case and strip leading and trailing
whitespaces. | [
"Returns",
"an",
"e",
"-",
"mail",
"address",
"in",
"lower",
"-",
"case",
"and",
"strip",
"leading",
"and",
"trailing",
"whitespaces",
"."
] | def sanitize_email(email):
"""
Returns an e-mail address in lower-case and strip leading and trailing
whitespaces.
>>> sanitize_email(' MyEmailAddress@example.com ')
'myemailaddress@example.com'
"""
return email.lower().strip() | [
"def",
"sanitize_email",
"(",
"email",
")",
":",
"return",
"email",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")"
] | https://github.com/PaulGuo/F2E.im/blob/6d21eaa4b6372d3846a079a36f4d35121695dd91/lib/gravatar.py#L129-L138 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | deps/v8/tools/clusterfuzz/v8_commands.py | python | Command.run | (self, testcase, verbose=False) | return Execute(
args,
cwd=os.path.dirname(os.path.abspath(testcase)),
timeout=TIMEOUT,
) | Run the executable with a specific testcase. | Run the executable with a specific testcase. | [
"Run",
"the",
"executable",
"with",
"a",
"specific",
"testcase",
"."
] | def run(self, testcase, verbose=False):
"""Run the executable with a specific testcase."""
args = [self.executable] + self.flags + self.files + [testcase]
if verbose:
print('# Command line for %s comparison:' % self.label)
print(' '.join(args))
if self.executable.endswith('.py'):
# Wrap with python in tests.
args = [sys.executable] + args
return Execute(
args,
cwd=os.path.dirname(os.path.abspath(testcase)),
timeout=TIMEOUT,
) | [
"def",
"run",
"(",
"self",
",",
"testcase",
",",
"verbose",
"=",
"False",
")",
":",
"args",
"=",
"[",
"self",
".",
"executable",
"]",
"+",
"self",
".",
"flags",
"+",
"self",
".",
"files",
"+",
"[",
"testcase",
"]",
"if",
"verbose",
":",
"print",
"(",
"'# Command line for %s comparison:'",
"%",
"self",
".",
"label",
")",
"print",
"(",
"' '",
".",
"join",
"(",
"args",
")",
")",
"if",
"self",
".",
"executable",
".",
"endswith",
"(",
"'.py'",
")",
":",
"# Wrap with python in tests.",
"args",
"=",
"[",
"sys",
".",
"executable",
"]",
"+",
"args",
"return",
"Execute",
"(",
"args",
",",
"cwd",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"testcase",
")",
")",
",",
"timeout",
"=",
"TIMEOUT",
",",
")"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/v8/tools/clusterfuzz/v8_commands.py#L64-L77 |
|
aws/aws-ops-wheel | c36cdbc43a19fd4183cc932ce4f0b503ef492a7f | api/wheel.py | python | create_wheel | (event) | return wheel | Create a wheel. Requires a name
:param event: Lambda event containing the API Gateway request body including a name
{
"body":
{
"name": string wheel name,
}
}
:return: response dictionary containing new wheel object if successful
{
"body":
{
"id": string ID of the wheel (DDB Hash Key),
"name": string name of the wheel,
"participant_count": number of participants in the wheel,
"created_at": creation timestamp,
"updated_at": updated timestamp,
}
} | Create a wheel. Requires a name | [
"Create",
"a",
"wheel",
".",
"Requires",
"a",
"name"
] | def create_wheel(event):
"""
Create a wheel. Requires a name
:param event: Lambda event containing the API Gateway request body including a name
{
"body":
{
"name": string wheel name,
}
}
:return: response dictionary containing new wheel object if successful
{
"body":
{
"id": string ID of the wheel (DDB Hash Key),
"name": string name of the wheel,
"participant_count": number of participants in the wheel,
"created_at": creation timestamp,
"updated_at": updated timestamp,
}
}
"""
create_timestamp = get_utc_timestamp()
body = event['body']
if body is None or not check_string(body.get('name', None)):
raise base.BadRequestError(
f"New wheels require a name that must be a string with a length of at least 1. Got: {body}"
)
wheel = {
'id': get_uuid(),
'name': body['name'],
'created_at': create_timestamp,
'updated_at': create_timestamp,
}
with choice_algorithm.wrap_wheel_creation(wheel):
Wheel.put_item(Item=wheel)
return wheel | [
"def",
"create_wheel",
"(",
"event",
")",
":",
"create_timestamp",
"=",
"get_utc_timestamp",
"(",
")",
"body",
"=",
"event",
"[",
"'body'",
"]",
"if",
"body",
"is",
"None",
"or",
"not",
"check_string",
"(",
"body",
".",
"get",
"(",
"'name'",
",",
"None",
")",
")",
":",
"raise",
"base",
".",
"BadRequestError",
"(",
"f\"New wheels require a name that must be a string with a length of at least 1. Got: {body}\"",
")",
"wheel",
"=",
"{",
"'id'",
":",
"get_uuid",
"(",
")",
",",
"'name'",
":",
"body",
"[",
"'name'",
"]",
",",
"'created_at'",
":",
"create_timestamp",
",",
"'updated_at'",
":",
"create_timestamp",
",",
"}",
"with",
"choice_algorithm",
".",
"wrap_wheel_creation",
"(",
"wheel",
")",
":",
"Wheel",
".",
"put_item",
"(",
"Item",
"=",
"wheel",
")",
"return",
"wheel"
] | https://github.com/aws/aws-ops-wheel/blob/c36cdbc43a19fd4183cc932ce4f0b503ef492a7f/api/wheel.py#L21-L59 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/mailbox.py | python | Mailbox.get_file | (self, key) | Return a file-like representation or raise a KeyError. | Return a file-like representation or raise a KeyError. | [
"Return",
"a",
"file",
"-",
"like",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_file(self, key):
"""Return a file-like representation or raise a KeyError."""
raise NotImplementedError('Method must be implemented by subclass') | [
"def",
"get_file",
"(",
"self",
",",
"key",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Method must be implemented by subclass'",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/mailbox.py#L94-L96 |
||
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.WriteList | (self, value_list, variable=None, prefix='',
quoter=QuoteIfNecessary) | Write a variable definition that is a list of values.
E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
foo = blaha blahb
but in a pretty-printed style. | Write a variable definition that is a list of values. | [
"Write",
"a",
"variable",
"definition",
"that",
"is",
"a",
"list",
"of",
"values",
"."
] | def WriteList(self, value_list, variable=None, prefix='',
quoter=QuoteIfNecessary):
"""Write a variable definition that is a list of values.
E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
foo = blaha blahb
but in a pretty-printed style.
"""
values = ''
if value_list:
value_list = [quoter(prefix + l) for l in value_list]
values = ' \\\n\t' + ' \\\n\t'.join(value_list)
self.fp.write('%s :=%s\n\n' % (variable, values)) | [
"def",
"WriteList",
"(",
"self",
",",
"value_list",
",",
"variable",
"=",
"None",
",",
"prefix",
"=",
"''",
",",
"quoter",
"=",
"QuoteIfNecessary",
")",
":",
"values",
"=",
"''",
"if",
"value_list",
":",
"value_list",
"=",
"[",
"quoter",
"(",
"prefix",
"+",
"l",
")",
"for",
"l",
"in",
"value_list",
"]",
"values",
"=",
"' \\\\\\n\\t'",
"+",
"' \\\\\\n\\t'",
".",
"join",
"(",
"value_list",
")",
"self",
".",
"fp",
".",
"write",
"(",
"'%s :=%s\\n\\n'",
"%",
"(",
"variable",
",",
"values",
")",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L1693-L1705 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/collections.py | python | OrderedDict.copy | (self) | return self.__class__(self) | od.copy() -> a shallow copy of od | od.copy() -> a shallow copy of od | [
"od",
".",
"copy",
"()",
"-",
">",
"a",
"shallow",
"copy",
"of",
"od"
] | def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/collections.py#L190-L192 |
|
metacademy/metacademy-application | c05ee087a04d9c542caa60becb853467c6ea2bd9 | server/apps/graph/management/commands/content_server/graphs.py | python | Graph.gather_dependencies | (self) | return dependencies | Construct a dict mapping a tag to the set of all tags which it depends on. | Construct a dict mapping a tag to the set of all tags which it depends on. | [
"Construct",
"a",
"dict",
"mapping",
"a",
"tag",
"to",
"the",
"set",
"of",
"all",
"tags",
"which",
"it",
"depends",
"on",
"."
] | def gather_dependencies(self):
"""Construct a dict mapping a tag to the set of all tags which it depends on."""
vertices = self.topo_sort()
dependencies = {}
for v in vertices:
curr_deps = set(self.incoming[v])
for parent in self.incoming[v]:
curr_deps.update(dependencies[parent])
dependencies[v] = curr_deps
return dependencies | [
"def",
"gather_dependencies",
"(",
"self",
")",
":",
"vertices",
"=",
"self",
".",
"topo_sort",
"(",
")",
"dependencies",
"=",
"{",
"}",
"for",
"v",
"in",
"vertices",
":",
"curr_deps",
"=",
"set",
"(",
"self",
".",
"incoming",
"[",
"v",
"]",
")",
"for",
"parent",
"in",
"self",
".",
"incoming",
"[",
"v",
"]",
":",
"curr_deps",
".",
"update",
"(",
"dependencies",
"[",
"parent",
"]",
")",
"dependencies",
"[",
"v",
"]",
"=",
"curr_deps",
"return",
"dependencies"
] | https://github.com/metacademy/metacademy-application/blob/c05ee087a04d9c542caa60becb853467c6ea2bd9/server/apps/graph/management/commands/content_server/graphs.py#L138-L149 |
|
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | deps/v8/tools/grokdump.py | python | InspectionShell.do_do | (self, address) | return self.do_display_object(address) | see display_object | see display_object | [
"see",
"display_object"
] | def do_do(self, address):
""" see display_object """
return self.do_display_object(address) | [
"def",
"do_do",
"(",
"self",
",",
"address",
")",
":",
"return",
"self",
".",
"do_display_object",
"(",
"address",
")"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/v8/tools/grokdump.py#L3387-L3389 |
|
graphite-project/graphite-web | 2105089c20786186364733941a3d2863f78b1765 | webapp/graphite/render/functions.py | python | diffSeriesLists | (requestContext, seriesListFirstPos, seriesListSecondPos) | return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'diff') | Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=diffSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`diffSeries <diffSeries>` for each member of the list:
.. code-block:: none
?target=diffSeries(mining.carbon.extracted,mining.carbon.shipped)
&target=diffSeries(mining.graphite.extracted,mining.graphite.shipped)
&target=diffSeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``diff``. | Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length | [
"Iterates",
"over",
"a",
"two",
"lists",
"and",
"subtracts",
"series",
"lists",
"2",
"through",
"n",
"from",
"series",
"1",
"list1",
"[",
"0",
"]",
"to",
"list2",
"[",
"0",
"]",
"list1",
"[",
"1",
"]",
"to",
"list2",
"[",
"1",
"]",
"and",
"so",
"on",
".",
"The",
"lists",
"will",
"need",
"to",
"be",
"the",
"same",
"length"
] | def diffSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos):
"""
Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=diffSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`diffSeries <diffSeries>` for each member of the list:
.. code-block:: none
?target=diffSeries(mining.carbon.extracted,mining.carbon.shipped)
&target=diffSeries(mining.graphite.extracted,mining.graphite.shipped)
&target=diffSeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``diff``.
"""
return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'diff') | [
"def",
"diffSeriesLists",
"(",
"requestContext",
",",
"seriesListFirstPos",
",",
"seriesListSecondPos",
")",
":",
"return",
"aggregateSeriesLists",
"(",
"requestContext",
",",
"seriesListFirstPos",
",",
"seriesListSecondPos",
",",
"'diff'",
")"
] | https://github.com/graphite-project/graphite-web/blob/2105089c20786186364733941a3d2863f78b1765/webapp/graphite/render/functions.py#L558-L581 |
|
alaxli/ansible_ui | ea7a76e1de6d2aec3777c0182dd8cc3529c9ccd7 | desktop/apps/ansible/elfinder/volumes/base.py | python | ElfinderVolumeDriver._tmb_name | (self, stat) | return '%s%s.png' % (stat['hash'], stat['ts']) | Return thumbnail file name for required file | Return thumbnail file name for required file | [
"Return",
"thumbnail",
"file",
"name",
"for",
"required",
"file"
] | def _tmb_name(self, stat):
"""
Return thumbnail file name for required file
"""
return '%s%s.png' % (stat['hash'], stat['ts']) | [
"def",
"_tmb_name",
"(",
"self",
",",
"stat",
")",
":",
"return",
"'%s%s.png'",
"%",
"(",
"stat",
"[",
"'hash'",
"]",
",",
"stat",
"[",
"'ts'",
"]",
")"
] | https://github.com/alaxli/ansible_ui/blob/ea7a76e1de6d2aec3777c0182dd8cc3529c9ccd7/desktop/apps/ansible/elfinder/volumes/base.py#L1509-L1513 |
|
JoneXiong/DjangoX | c2a723e209ef13595f571923faac7eb29e4c8150 | xadmin/wizard/views.py | python | WizardView.get_prev_step | (self, step=None) | return None | Returns the previous step before the given `step`. If there are no
steps available, None will be returned. If the `step` argument is
None, the current step will be determined automatically. | Returns the previous step before the given `step`. If there are no
steps available, None will be returned. If the `step` argument is
None, the current step will be determined automatically. | [
"Returns",
"the",
"previous",
"step",
"before",
"the",
"given",
"step",
".",
"If",
"there",
"are",
"no",
"steps",
"available",
"None",
"will",
"be",
"returned",
".",
"If",
"the",
"step",
"argument",
"is",
"None",
"the",
"current",
"step",
"will",
"be",
"determined",
"automatically",
"."
] | def get_prev_step(self, step=None):
"""
Returns the previous step before the given `step`. If there are no
steps available, None will be returned. If the `step` argument is
None, the current step will be determined automatically.
"""
if step is None:
step = self.steps.current
form_list = self.get_form_list()
key = form_list.keyOrder.index(step) - 1
if key >= 0:
return form_list.keyOrder[key]
return None | [
"def",
"get_prev_step",
"(",
"self",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"form_list",
"=",
"self",
".",
"get_form_list",
"(",
")",
"key",
"=",
"form_list",
".",
"keyOrder",
".",
"index",
"(",
"step",
")",
"-",
"1",
"if",
"key",
">=",
"0",
":",
"return",
"form_list",
".",
"keyOrder",
"[",
"key",
"]",
"return",
"None"
] | https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/wizard/views.py#L489-L501 |