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
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/faraday/managers/all.py
python
PluginManager._loadPlugins
(self, plugin_repo_path)
Finds and load all the plugins that are available in the plugin_repo_path.
Finds and load all the plugins that are available in the plugin_repo_path.
[ "Finds", "and", "load", "all", "the", "plugins", "that", "are", "available", "in", "the", "plugin_repo_path", "." ]
def _loadPlugins(self, plugin_repo_path): """ Finds and load all the plugins that are available in the plugin_repo_path. """ try: os.stat(plugin_repo_path) except OSError: pass sys.path.append(plugin_repo_path) dir_name_regexp = re.compile(r"^[\d\w\-\_]+$") for name in os.listdir(plugin_repo_path): if dir_name_regexp.match(name): try: module_path = os.path.join(plugin_repo_path, name) sys.path.append(module_path) module_filename = os.path.join(module_path, "plugin.py") self._plugin_modules[name] = imp.load_source(name, module_filename) except Exception: msg = "An error ocurred while loading plugin %s.\n%s" % (module_filename, traceback.format_exc()) getLogger(self).error(msg) else: pass
[ "def", "_loadPlugins", "(", "self", ",", "plugin_repo_path", ")", ":", "try", ":", "os", ".", "stat", "(", "plugin_repo_path", ")", "except", "OSError", ":", "pass", "sys", ".", "path", ".", "append", "(", "plugin_repo_path", ")", "dir_name_regexp", "=", "re", ".", "compile", "(", "r\"^[\\d\\w\\-\\_]+$\"", ")", "for", "name", "in", "os", ".", "listdir", "(", "plugin_repo_path", ")", ":", "if", "dir_name_regexp", ".", "match", "(", "name", ")", ":", "try", ":", "module_path", "=", "os", ".", "path", ".", "join", "(", "plugin_repo_path", ",", "name", ")", "sys", ".", "path", ".", "append", "(", "module_path", ")", "module_filename", "=", "os", ".", "path", ".", "join", "(", "module_path", ",", "\"plugin.py\"", ")", "self", ".", "_plugin_modules", "[", "name", "]", "=", "imp", ".", "load_source", "(", "name", ",", "module_filename", ")", "except", "Exception", ":", "msg", "=", "\"An error ocurred while loading plugin %s.\\n%s\"", "%", "(", "module_filename", ",", "traceback", ".", "format_exc", "(", ")", ")", "getLogger", "(", "self", ")", ".", "error", "(", "msg", ")", "else", ":", "pass" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/faraday/managers/all.py#L503-L527
BlocklyDuino/BlocklyDuino
265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d
blockly/i18n/xliff_to_json.py
python
sort_units
(units, templates)
return sorted(units, key=key_function)
Sorts the translation units by their definition order in the template. Args: units: A list of dictionaries produced by parse_trans_unit() that have a non-empty value for the key 'meaning'. templates: A string containing the Soy templates in which each of the units' meanings is defined. Returns: A new list of translation units, sorted by the order in which their meaning is defined in the templates. Raises: InputError: If a meaning definition cannot be found in the templates.
Sorts the translation units by their definition order in the template.
[ "Sorts", "the", "translation", "units", "by", "their", "definition", "order", "in", "the", "template", "." ]
def sort_units(units, templates): """Sorts the translation units by their definition order in the template. Args: units: A list of dictionaries produced by parse_trans_unit() that have a non-empty value for the key 'meaning'. templates: A string containing the Soy templates in which each of the units' meanings is defined. Returns: A new list of translation units, sorted by the order in which their meaning is defined in the templates. Raises: InputError: If a meaning definition cannot be found in the templates. """ def key_function(unit): match = re.search( '\\smeaning\\s*=\\s*"{0}"\\s'.format(unit['meaning']), templates) if match: return match.start() else: raise InputError(args.templates, 'msg definition for meaning not found: ' + unit['meaning']) return sorted(units, key=key_function)
[ "def", "sort_units", "(", "units", ",", "templates", ")", ":", "def", "key_function", "(", "unit", ")", ":", "match", "=", "re", ".", "search", "(", "'\\\\smeaning\\\\s*=\\\\s*\"{0}\"\\\\s'", ".", "format", "(", "unit", "[", "'meaning'", "]", ")", ",", "templates", ")", "if", "match", ":", "return", "match", ".", "start", "(", ")", "else", ":", "raise", "InputError", "(", "args", ".", "templates", ",", "'msg definition for meaning not found: '", "+", "unit", "[", "'meaning'", "]", ")", "return", "sorted", "(", "units", ",", "key", "=", "key_function", ")" ]
https://github.com/BlocklyDuino/BlocklyDuino/blob/265b1e0e0d711e2e2771d4fa0a4a40de9c44ac5d/blockly/i18n/xliff_to_json.py#L154-L181
hxxft/lynx-native
a2dd46376f9bcf837a94ac581381b5b06466464f
Core/third_party/jsoncpp/doxybuild.py
python
run_cmd
(cmd, silent=False)
Raise exception on failure.
Raise exception on failure.
[ "Raise", "exception", "on", "failure", "." ]
def run_cmd(cmd, silent=False): """Raise exception on failure. """ info = 'Running: %r in %r' %(' '.join(cmd), os.getcwd()) print(info) sys.stdout.flush() if silent: status, output = getstatusoutput(cmd) else: status, output = subprocess.call(cmd), '' if status: msg = 'Error while %s ...\n\terror=%d, output="""%s"""' %(info, status, output) raise Exception(msg)
[ "def", "run_cmd", "(", "cmd", ",", "silent", "=", "False", ")", ":", "info", "=", "'Running: %r in %r'", "%", "(", "' '", ".", "join", "(", "cmd", ")", ",", "os", ".", "getcwd", "(", ")", ")", "print", "(", "info", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "silent", ":", "status", ",", "output", "=", "getstatusoutput", "(", "cmd", ")", "else", ":", "status", ",", "output", "=", "subprocess", ".", "call", "(", "cmd", ")", ",", "''", "if", "status", ":", "msg", "=", "'Error while %s ...\\n\\terror=%d, output=\"\"\"%s\"\"\"'", "%", "(", "info", ",", "status", ",", "output", ")", "raise", "Exception", "(", "msg", ")" ]
https://github.com/hxxft/lynx-native/blob/a2dd46376f9bcf837a94ac581381b5b06466464f/Core/third_party/jsoncpp/doxybuild.py#L66-L78
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
odoo/addons/base/models/ir_asset.py
python
IrAsset._get_active_addons_list
(self)
return self._get_installed_addons_list()
Can be overridden to filter the returned list of active modules.
Can be overridden to filter the returned list of active modules.
[ "Can", "be", "overridden", "to", "filter", "the", "returned", "list", "of", "active", "modules", "." ]
def _get_active_addons_list(self): """Can be overridden to filter the returned list of active modules.""" return self._get_installed_addons_list()
[ "def", "_get_active_addons_list", "(", "self", ")", ":", "return", "self", ".", "_get_installed_addons_list", "(", ")" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/addons/base/models/ir_asset.py#L260-L262
UKPLab/arxiv2018-xling-sentence-embeddings
95305c1a3d6d3e8c5f5365db463ba11cc9bd33b1
evaluation/experiment/__init__.py
python
Evaluation.start
(self, model, data, sess, valid_only=False)
:type model: Model :type data: Data :type sess: tensorflow.Session :type valid_only: bool :return: scores for all tested runs (data split, language combinations, ...) :rtype: OrderedDict[basestring, float]
[]
def start(self, model, data, sess, valid_only=False): """ :type model: Model :type data: Data :type sess: tensorflow.Session :type valid_only: bool :return: scores for all tested runs (data split, language combinations, ...) :rtype: OrderedDict[basestring, float] """ raise NotImplementedError()
[ "def", "start", "(", "self", ",", "model", ",", "data", ",", "sess", ",", "valid_only", "=", "False", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/UKPLab/arxiv2018-xling-sentence-embeddings/blob/95305c1a3d6d3e8c5f5365db463ba11cc9bd33b1/evaluation/experiment/__init__.py#L45-L55
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/v8/third_party/jinja2/filters.py
python
environmentfilter
(f)
return f
Decorator for marking evironment dependent filters. The current :class:`Environment` is passed to the filter as first argument.
Decorator for marking evironment dependent filters. The current :class:`Environment` is passed to the filter as first argument.
[ "Decorator", "for", "marking", "evironment", "dependent", "filters", ".", "The", "current", ":", "class", ":", "Environment", "is", "passed", "to", "the", "filter", "as", "first", "argument", "." ]
def environmentfilter(f): """Decorator for marking evironment dependent filters. The current :class:`Environment` is passed to the filter as first argument. """ f.environmentfilter = True return f
[ "def", "environmentfilter", "(", "f", ")", ":", "f", ".", "environmentfilter", "=", "True", "return", "f" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/v8/third_party/jinja2/filters.py#L46-L51
Opentrons/opentrons
466e0567065d8773a81c25cd1b5c7998e00adf2c
api/src/opentrons/hardware_control/controller.py
python
Controller.set_active_current
(self, axis_currents: Dict[Axis, float])
This method sets only the 'active' current, i.e., the current for an axis' movement. Smoothie driver automatically resets the current for pipette axis to a low current (dwelling current) after each move
This method sets only the 'active' current, i.e., the current for an axis' movement. Smoothie driver automatically resets the current for pipette axis to a low current (dwelling current) after each move
[ "This", "method", "sets", "only", "the", "active", "current", "i", ".", "e", ".", "the", "current", "for", "an", "axis", "movement", ".", "Smoothie", "driver", "automatically", "resets", "the", "current", "for", "pipette", "axis", "to", "a", "low", "current", "(", "dwelling", "current", ")", "after", "each", "move" ]
def set_active_current(self, axis_currents: Dict[Axis, float]): """ This method sets only the 'active' current, i.e., the current for an axis' movement. Smoothie driver automatically resets the current for pipette axis to a low current (dwelling current) after each move """ self._smoothie_driver.set_active_current( {axis.name: amp for axis, amp in axis_currents.items()} )
[ "def", "set_active_current", "(", "self", ",", "axis_currents", ":", "Dict", "[", "Axis", ",", "float", "]", ")", ":", "self", ".", "_smoothie_driver", ".", "set_active_current", "(", "{", "axis", ".", "name", ":", "amp", "for", "axis", ",", "amp", "in", "axis_currents", ".", "items", "(", ")", "}", ")" ]
https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/hardware_control/controller.py#L210-L218
Skycrab/leakScan
5ab4f4162a060ed5954e8272291eb05201f8fd5f
scanner/thirdparty/requests/packages/urllib3/packages/six.py
python
iteritems
(d)
return iter(getattr(d, _iteritems)())
Return an iterator over the (key, value) pairs of a dictionary.
Return an iterator over the (key, value) pairs of a dictionary.
[ "Return", "an", "iterator", "over", "the", "(", "key", "value", ")", "pairs", "of", "a", "dictionary", "." ]
def iteritems(d): """Return an iterator over the (key, value) pairs of a dictionary.""" return iter(getattr(d, _iteritems)())
[ "def", "iteritems", "(", "d", ")", ":", "return", "iter", "(", "getattr", "(", "d", ",", "_iteritems", ")", "(", ")", ")" ]
https://github.com/Skycrab/leakScan/blob/5ab4f4162a060ed5954e8272291eb05201f8fd5f/scanner/thirdparty/requests/packages/urllib3/packages/six.py#L271-L273
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
tools/configure.d/nodedownload.py
python
retrievefile
(url, targetfile)
fetch file 'url' as 'targetfile'. Return targetfile or throw.
fetch file 'url' as 'targetfile'. Return targetfile or throw.
[ "fetch", "file", "url", "as", "targetfile", ".", "Return", "targetfile", "or", "throw", "." ]
def retrievefile(url, targetfile): """fetch file 'url' as 'targetfile'. Return targetfile or throw.""" try: sys.stdout.write(' <%s>\nConnecting...\r' % url) sys.stdout.flush() msg = ConfigOpener().retrieve(url, targetfile, reporthook=reporthook) print '' # clear the line return targetfile except: print ' ** Error occurred while downloading\n <%s>' % url raise
[ "def", "retrievefile", "(", "url", ",", "targetfile", ")", ":", "try", ":", "sys", ".", "stdout", ".", "write", "(", "' <%s>\\nConnecting...\\r'", "%", "url", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "msg", "=", "ConfigOpener", "(", ")", ".", "retrieve", "(", "url", ",", "targetfile", ",", "reporthook", "=", "reporthook", ")", "print", "''", "# clear the line", "return", "targetfile", "except", ":", "print", "' ** Error occurred while downloading\\n <%s>'", "%", "url", "raise" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/tools/configure.d/nodedownload.py#L33-L43
harvard-lil/perma
c54ff21b3eee931f5094a7654fdddc9ad90fc29c
services/docker/webrecorder/local.py
python
DirectLocalFileStorage.do_delete
(self, target_url, client_url)
Delete file from storage. :param str target_url: target URL :returns: whether successful or not :rtype: bool
Delete file from storage.
[ "Delete", "file", "from", "storage", "." ]
def do_delete(self, target_url, client_url): """Delete file from storage. :param str target_url: target URL :returns: whether successful or not :rtype: bool """ try: logger.debug('Local Store: Deleting: ' + target_url) os.remove(target_url) # if target_url.startswith(self.storage_root): # os.removedirs(os.path.dirname(target_url)) return True except Exception as e: if e.errno != 2: logger.error(str(e)) return False
[ "def", "do_delete", "(", "self", ",", "target_url", ",", "client_url", ")", ":", "try", ":", "logger", ".", "debug", "(", "'Local Store: Deleting: '", "+", "target_url", ")", "os", ".", "remove", "(", "target_url", ")", "# if target_url.startswith(self.storage_root):", "# os.removedirs(os.path.dirname(target_url))", "return", "True", "except", "Exception", "as", "e", ":", "if", "e", ".", "errno", "!=", "2", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "return", "False" ]
https://github.com/harvard-lil/perma/blob/c54ff21b3eee931f5094a7654fdddc9ad90fc29c/services/docker/webrecorder/local.py#L97-L114
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/v8/.ycm_extra_conf.py
python
FlagsForFile
(filename)
return { 'flags': final_flags, 'do_cache': True }
This is the main entry point for YCM. Its interface is fixed. Args: filename: (String) Path to source file being edited. Returns: (Dictionary) 'flags': (List of Strings) Command line flags. 'do_cache': (Boolean) True if the result should be cached.
This is the main entry point for YCM. Its interface is fixed.
[ "This", "is", "the", "main", "entry", "point", "for", "YCM", ".", "Its", "interface", "is", "fixed", "." ]
def FlagsForFile(filename): """This is the main entry point for YCM. Its interface is fixed. Args: filename: (String) Path to source file being edited. Returns: (Dictionary) 'flags': (List of Strings) Command line flags. 'do_cache': (Boolean) True if the result should be cached. """ v8_root = FindV8SrcFromFilename(filename) v8_flags = GetClangCommandFromNinjaForFilename(v8_root, filename) final_flags = flags + v8_flags return { 'flags': final_flags, 'do_cache': True }
[ "def", "FlagsForFile", "(", "filename", ")", ":", "v8_root", "=", "FindV8SrcFromFilename", "(", "filename", ")", "v8_flags", "=", "GetClangCommandFromNinjaForFilename", "(", "v8_root", ",", "filename", ")", "final_flags", "=", "flags", "+", "v8_flags", "return", "{", "'flags'", ":", "final_flags", ",", "'do_cache'", ":", "True", "}" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/v8/.ycm_extra_conf.py#L165-L182
blakeembrey/code-problems
fb40eadcdb4a3d028659477a6478c88ccb9aa37b
solutions/python/largest-continuous-sum.py
python
largest_continuous_sum
(arr)
return largest
returns the highest sum of a continuous sequence in a given list
returns the highest sum of a continuous sequence in a given list
[ "returns", "the", "highest", "sum", "of", "a", "continuous", "sequence", "in", "a", "given", "list" ]
def largest_continuous_sum(arr): """returns the highest sum of a continuous sequence in a given list""" largest = 0 queue = [] for num in arr: if len(queue) > 0 and queue[-1] + 1 != num: sum = reduce(lambda x, y: x + y, queue) if largest < sum: largest = sum queue = [] queue.append(num) return largest
[ "def", "largest_continuous_sum", "(", "arr", ")", ":", "largest", "=", "0", "queue", "=", "[", "]", "for", "num", "in", "arr", ":", "if", "len", "(", "queue", ")", ">", "0", "and", "queue", "[", "-", "1", "]", "+", "1", "!=", "num", ":", "sum", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "queue", ")", "if", "largest", "<", "sum", ":", "largest", "=", "sum", "queue", "=", "[", "]", "queue", ".", "append", "(", "num", ")", "return", "largest" ]
https://github.com/blakeembrey/code-problems/blob/fb40eadcdb4a3d028659477a6478c88ccb9aa37b/solutions/python/largest-continuous-sum.py#L3-L17
Sefaria/Sefaria-Project
506752f49394fadebae283d525af8276eb2e241e
sefaria/history.py
python
get_activity
(query={}, page_size=100, page=1, filter_type=None, initial_skip=0)
return activity
Returns a list of activity items matching query, joins with user info on each item and sets urls.
Returns a list of activity items matching query, joins with user info on each item and sets urls.
[ "Returns", "a", "list", "of", "activity", "items", "matching", "query", "joins", "with", "user", "info", "on", "each", "item", "and", "sets", "urls", "." ]
def get_activity(query={}, page_size=100, page=1, filter_type=None, initial_skip=0): """ Returns a list of activity items matching query, joins with user info on each item and sets urls. """ query.update(filter_type_to_query(filter_type)) skip = initial_skip + (page - 1) * page_size projection = { "revert_patch": 0 } activity = list(db.history.find(query, projection).sort([["date", -1]]).skip(skip).limit(page_size)) for i in range(len(activity)): a = activity[i] if a["rev_type"].endswith("text") or a["rev_type"] == "review": try: a["history_url"] = "/activity/%s/%s/%s" % (Ref(a["ref"]).url(), a["language"], a["version"].replace(" ", "_")) except: a["history_url"] = "#" return activity
[ "def", "get_activity", "(", "query", "=", "{", "}", ",", "page_size", "=", "100", ",", "page", "=", "1", ",", "filter_type", "=", "None", ",", "initial_skip", "=", "0", ")", ":", "query", ".", "update", "(", "filter_type_to_query", "(", "filter_type", ")", ")", "skip", "=", "initial_skip", "+", "(", "page", "-", "1", ")", "*", "page_size", "projection", "=", "{", "\"revert_patch\"", ":", "0", "}", "activity", "=", "list", "(", "db", ".", "history", ".", "find", "(", "query", ",", "projection", ")", ".", "sort", "(", "[", "[", "\"date\"", ",", "-", "1", "]", "]", ")", ".", "skip", "(", "skip", ")", ".", "limit", "(", "page_size", ")", ")", "for", "i", "in", "range", "(", "len", "(", "activity", ")", ")", ":", "a", "=", "activity", "[", "i", "]", "if", "a", "[", "\"rev_type\"", "]", ".", "endswith", "(", "\"text\"", ")", "or", "a", "[", "\"rev_type\"", "]", "==", "\"review\"", ":", "try", ":", "a", "[", "\"history_url\"", "]", "=", "\"/activity/%s/%s/%s\"", "%", "(", "Ref", "(", "a", "[", "\"ref\"", "]", ")", ".", "url", "(", ")", ",", "a", "[", "\"language\"", "]", ",", "a", "[", "\"version\"", "]", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", ")", "except", ":", "a", "[", "\"history_url\"", "]", "=", "\"#\"", "return", "activity" ]
https://github.com/Sefaria/Sefaria-Project/blob/506752f49394fadebae283d525af8276eb2e241e/sefaria/history.py#L16-L33
alibaba/web-editor
e52a7d09dc72bff372a8a5afe41fe41a411b4336
weditor/__main__.py
python
CropHandler.get
(self)
used for crop image
used for crop image
[ "used", "for", "crop", "image" ]
def get(self): """ used for crop image """ pass
[ "def", "get", "(", "self", ")", ":", "pass" ]
https://github.com/alibaba/web-editor/blob/e52a7d09dc72bff372a8a5afe41fe41a411b4336/weditor/__main__.py#L83-L85
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.RootGroupForPath
(self, path)
return (self.SourceGroup(), True)
Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False).
Returns a PBXGroup child of this object to which path should be added.
[ "Returns", "a", "PBXGroup", "child", "of", "this", "object", "to", "which", "path", "should", "be", "added", "." ]
def RootGroupForPath(self, path): """Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False). """ # TODO(mark): make this a class variable and bind to self on call? # Also, this list is nowhere near exhaustive. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by # gyp.generator.xcode. There should probably be some way for that module # to push the names in, rather than having to hard-code them here. source_tree_groups = { 'DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True), 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True), } (source_tree, path) = SourceTreeAndPathFromPath(path) if source_tree != None and source_tree in source_tree_groups: (group_func, hierarchical) = source_tree_groups[source_tree] group = group_func() return (group, hierarchical) # TODO(mark): make additional choices based on file extension. return (self.SourceGroup(), True)
[ "def", "RootGroupForPath", "(", "self", ",", "path", ")", ":", "# TODO(mark): make this a class variable and bind to self on call?", "# Also, this list is nowhere near exhaustive.", "# INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by", "# gyp.generator.xcode. There should probably be some way for that module", "# to push the names in, rather than having to hard-code them here.", "source_tree_groups", "=", "{", "'DERIVED_FILE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "'INTERMEDIATE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "'PROJECT_DERIVED_FILE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "'SHARED_INTERMEDIATE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "}", "(", "source_tree", ",", "path", ")", "=", "SourceTreeAndPathFromPath", "(", "path", ")", "if", "source_tree", "!=", "None", "and", "source_tree", "in", "source_tree_groups", ":", "(", "group_func", ",", "hierarchical", ")", "=", "source_tree_groups", "[", "source_tree", "]", "group", "=", "group_func", "(", ")", "return", "(", "group", ",", "hierarchical", ")", "# TODO(mark): make additional choices based on file extension.", "return", "(", "self", ".", "SourceGroup", "(", ")", ",", "True", ")" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L2584-L2619
facebookarchive/nuclide
2a2a0a642d136768b7d2a6d35a652dc5fb77d70a
modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py
python
FixPEP8.fix_e502
(self, result)
Remove extraneous escape of newline.
Remove extraneous escape of newline.
[ "Remove", "extraneous", "escape", "of", "newline", "." ]
def fix_e502(self, result): """Remove extraneous escape of newline.""" (line_index, _, target) = get_index_offset_contents(result, self.source) self.source[line_index] = target.rstrip('\n\r \t\\') + '\n'
[ "def", "fix_e502", "(", "self", ",", "result", ")", ":", "(", "line_index", ",", "_", ",", "target", ")", "=", "get_index_offset_contents", "(", "result", ",", "self", ".", "source", ")", "self", ".", "source", "[", "line_index", "]", "=", "target", ".", "rstrip", "(", "'\\n\\r \\t\\\\'", ")", "+", "'\\n'" ]
https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py#L903-L907
depjs/dep
cb8def92812d80b1fd8e5ffbbc1ae129a207fff6
node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._Setting
(self, path, config, default=None, prefix="", append=None, map=None)
return self._GetAndMunge( self.msvs_settings[config], path, default, prefix, append, map )
_GetAndMunge for msvs_settings.
_GetAndMunge for msvs_settings.
[ "_GetAndMunge", "for", "msvs_settings", "." ]
def _Setting(self, path, config, default=None, prefix="", append=None, map=None): """_GetAndMunge for msvs_settings.""" return self._GetAndMunge( self.msvs_settings[config], path, default, prefix, append, map )
[ "def", "_Setting", "(", "self", ",", "path", ",", "config", ",", "default", "=", "None", ",", "prefix", "=", "\"\"", ",", "append", "=", "None", ",", "map", "=", "None", ")", ":", "return", "self", ".", "_GetAndMunge", "(", "self", ".", "msvs_settings", "[", "config", "]", ",", "path", ",", "default", ",", "prefix", ",", "append", ",", "map", ")" ]
https://github.com/depjs/dep/blob/cb8def92812d80b1fd8e5ffbbc1ae129a207fff6/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L350-L354
JoneXiong/DjangoX
c2a723e209ef13595f571923faac7eb29e4c8150
xadmin/wizard/legacy.py
python
FormWizard.__call__
(self, request, *args, **kwargs)
return self.render(form, request, current_step)
Main method that does all the hard work, conforming to the Django view interface.
Main method that does all the hard work, conforming to the Django view interface.
[ "Main", "method", "that", "does", "all", "the", "hard", "work", "conforming", "to", "the", "Django", "view", "interface", "." ]
def __call__(self, request, *args, **kwargs): """ Main method that does all the hard work, conforming to the Django view interface. """ if 'extra_context' in kwargs: self.extra_context.update(kwargs['extra_context']) current_step = self.get_current_or_first_step(request, *args, **kwargs) self.parse_params(request, *args, **kwargs) # Validate and process all the previous forms before instantiating the # current step's form in case self.process_step makes changes to # self.form_list. # If any of them fails validation, that must mean the validator relied # on some other input, such as an external Web site. # It is also possible that alidation might fail under certain attack # situations: an attacker might be able to bypass previous stages, and # generate correct security hashes for all the skipped stages by virtue # of: # 1) having filled out an identical form which doesn't have the # validation (and does something different at the end), # 2) or having filled out a previous version of the same form which # had some validation missing, # 3) or previously having filled out the form when they had more # privileges than they do now. # # Since the hashes only take into account values, and not other other # validation the form might do, we must re-do validation now for # security reasons. previous_form_list = [] for i in range(current_step): f = self.get_form(i, request.POST) if not self._check_security_hash(request.POST.get("hash_%d" % i, ''), request, f): return self.render_hash_failure(request, i) if not f.is_valid(): return self.render_revalidation_failure(request, i, f) else: self.process_step(request, f, i) previous_form_list.append(f) # Process the current step. If it's valid, go to the next step or call # done(), depending on whether any steps remain. if request.method == 'POST': form = self.get_form(current_step, request.POST) else: form = self.get_form(current_step) if form.is_valid(): self.process_step(request, form, current_step) next_step = current_step + 1 if next_step == self.num_steps(): return self.done(request, previous_form_list + [form]) else: form = self.get_form(next_step) self.step = current_step = next_step return self.render(form, request, current_step)
[ "def", "__call__", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'extra_context'", "in", "kwargs", ":", "self", ".", "extra_context", ".", "update", "(", "kwargs", "[", "'extra_context'", "]", ")", "current_step", "=", "self", ".", "get_current_or_first_step", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "parse_params", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Validate and process all the previous forms before instantiating the", "# current step's form in case self.process_step makes changes to", "# self.form_list.", "# If any of them fails validation, that must mean the validator relied", "# on some other input, such as an external Web site.", "# It is also possible that alidation might fail under certain attack", "# situations: an attacker might be able to bypass previous stages, and", "# generate correct security hashes for all the skipped stages by virtue", "# of:", "# 1) having filled out an identical form which doesn't have the", "# validation (and does something different at the end),", "# 2) or having filled out a previous version of the same form which", "# had some validation missing,", "# 3) or previously having filled out the form when they had more", "# privileges than they do now.", "#", "# Since the hashes only take into account values, and not other other", "# validation the form might do, we must re-do validation now for", "# security reasons.", "previous_form_list", "=", "[", "]", "for", "i", "in", "range", "(", "current_step", ")", ":", "f", "=", "self", ".", "get_form", "(", "i", ",", "request", ".", "POST", ")", "if", "not", "self", ".", "_check_security_hash", "(", "request", ".", "POST", ".", "get", "(", "\"hash_%d\"", "%", "i", ",", "''", ")", ",", "request", ",", "f", ")", ":", "return", "self", ".", "render_hash_failure", "(", "request", ",", "i", ")", "if", "not", "f", ".", "is_valid", "(", ")", ":", "return", "self", ".", "render_revalidation_failure", "(", "request", ",", "i", ",", "f", ")", "else", ":", "self", ".", "process_step", "(", "request", ",", "f", ",", "i", ")", "previous_form_list", ".", "append", "(", "f", ")", "# Process the current step. If it's valid, go to the next step or call", "# done(), depending on whether any steps remain.", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "self", ".", "get_form", "(", "current_step", ",", "request", ".", "POST", ")", "else", ":", "form", "=", "self", ".", "get_form", "(", "current_step", ")", "if", "form", ".", "is_valid", "(", ")", ":", "self", ".", "process_step", "(", "request", ",", "form", ",", "current_step", ")", "next_step", "=", "current_step", "+", "1", "if", "next_step", "==", "self", ".", "num_steps", "(", ")", ":", "return", "self", ".", "done", "(", "request", ",", "previous_form_list", "+", "[", "form", "]", ")", "else", ":", "form", "=", "self", ".", "get_form", "(", "next_step", ")", "self", ".", "step", "=", "current_step", "=", "next_step", "return", "self", ".", "render", "(", "form", ",", "request", ",", "current_step", ")" ]
https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/wizard/legacy.py#L66-L127
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/Sqlmap/thirdparty/pydes/pyDes.py
python
triple_des.setIV
(self, IV)
Will set the Initial Value, used in conjunction with CBC mode
Will set the Initial Value, used in conjunction with CBC mode
[ "Will", "set", "the", "Initial", "Value", "used", "in", "conjunction", "with", "CBC", "mode" ]
def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" _baseDes.setIV(self, IV) for key in (self.__key1, self.__key2, self.__key3): key.setIV(IV)
[ "def", "setIV", "(", "self", ",", "IV", ")", ":", "_baseDes", ".", "setIV", "(", "self", ",", "IV", ")", "for", "key", "in", "(", "self", ".", "__key1", ",", "self", ".", "__key2", ",", "self", ".", "__key3", ")", ":", "key", ".", "setIV", "(", "IV", ")" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/pydes/pyDes.py#L763-L767
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetCflags
(self, config)
return cflags
Returns the flags that need to be added to .c and .cc compilations.
Returns the flags that need to be added to .c and .cc compilations.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", ".", "c", "and", ".", "cc", "compilations", "." ]
def GetCflags(self, config): """Returns the flags that need to be added to .c and .cc compilations.""" config = self._TargetConfig(config) cflags = [] cflags.extend(['/wd' + w for w in self.msvs_disabled_warnings[config]]) cl = self._GetWrapper(self, self.msvs_settings[config], 'VCCLCompilerTool', append=cflags) cl('Optimization', map={'0': 'd', '1': '1', '2': '2', '3': 'x'}, prefix='/O', default='2') cl('InlineFunctionExpansion', prefix='/Ob') cl('DisableSpecificWarnings', prefix='/wd') cl('StringPooling', map={'true': '/GF'}) cl('EnableFiberSafeOptimizations', map={'true': '/GT'}) cl('OmitFramePointers', map={'false': '-', 'true': ''}, prefix='/Oy') cl('EnableIntrinsicFunctions', map={'false': '-', 'true': ''}, prefix='/Oi') cl('FavorSizeOrSpeed', map={'1': 't', '2': 's'}, prefix='/O') cl('FloatingPointModel', map={'0': 'precise', '1': 'strict', '2': 'fast'}, prefix='/fp:', default='0') cl('CompileAsManaged', map={'false': '', 'true': '/clr'}) cl('WholeProgramOptimization', map={'true': '/GL'}) cl('WarningLevel', prefix='/W') cl('WarnAsError', map={'true': '/WX'}) cl('CallingConvention', map={'0': 'd', '1': 'r', '2': 'z', '3': 'v'}, prefix='/G') cl('DebugInformationFormat', map={'1': '7', '3': 'i', '4': 'I'}, prefix='/Z') cl('RuntimeTypeInfo', map={'true': '/GR', 'false': '/GR-'}) cl('EnableFunctionLevelLinking', map={'true': '/Gy', 'false': '/Gy-'}) cl('MinimalRebuild', map={'true': '/Gm'}) cl('BufferSecurityCheck', map={'true': '/GS', 'false': '/GS-'}) cl('BasicRuntimeChecks', map={'1': 's', '2': 'u', '3': '1'}, prefix='/RTC') cl('RuntimeLibrary', map={'0': 'T', '1': 'Td', '2': 'D', '3': 'Dd'}, prefix='/M') cl('ExceptionHandling', map={'1': 'sc','2': 'a'}, prefix='/EH') cl('DefaultCharIsUnsigned', map={'true': '/J'}) cl('TreatWChar_tAsBuiltInType', map={'false': '-', 'true': ''}, prefix='/Zc:wchar_t') cl('EnablePREfast', map={'true': '/analyze'}) cl('AdditionalOptions', prefix='') cl('EnableEnhancedInstructionSet', map={'1': 'SSE', '2': 'SSE2', '3': 'AVX', '4': 'IA32', '5': 'AVX2'}, prefix='/arch:') cflags.extend(['/FI' + f for f in self._Setting( ('VCCLCompilerTool', 'ForcedIncludeFiles'), config, default=[])]) if self.vs_version.short_name in ('2013', '2013e', '2015'): # New flag required in 2013 to maintain previous PDB behavior. cflags.append('/FS') # ninja handles parallelism by itself, don't have the compiler do it too. cflags = filter(lambda x: not x.startswith('/MP'), cflags) return cflags
[ "def", "GetCflags", "(", "self", ",", "config", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "cflags", "=", "[", "]", "cflags", ".", "extend", "(", "[", "'/wd'", "+", "w", "for", "w", "in", "self", ".", "msvs_disabled_warnings", "[", "config", "]", "]", ")", "cl", "=", "self", ".", "_GetWrapper", "(", "self", ",", "self", ".", "msvs_settings", "[", "config", "]", ",", "'VCCLCompilerTool'", ",", "append", "=", "cflags", ")", "cl", "(", "'Optimization'", ",", "map", "=", "{", "'0'", ":", "'d'", ",", "'1'", ":", "'1'", ",", "'2'", ":", "'2'", ",", "'3'", ":", "'x'", "}", ",", "prefix", "=", "'/O'", ",", "default", "=", "'2'", ")", "cl", "(", "'InlineFunctionExpansion'", ",", "prefix", "=", "'/Ob'", ")", "cl", "(", "'DisableSpecificWarnings'", ",", "prefix", "=", "'/wd'", ")", "cl", "(", "'StringPooling'", ",", "map", "=", "{", "'true'", ":", "'/GF'", "}", ")", "cl", "(", "'EnableFiberSafeOptimizations'", ",", "map", "=", "{", "'true'", ":", "'/GT'", "}", ")", "cl", "(", "'OmitFramePointers'", ",", "map", "=", "{", "'false'", ":", "'-'", ",", "'true'", ":", "''", "}", ",", "prefix", "=", "'/Oy'", ")", "cl", "(", "'EnableIntrinsicFunctions'", ",", "map", "=", "{", "'false'", ":", "'-'", ",", "'true'", ":", "''", "}", ",", "prefix", "=", "'/Oi'", ")", "cl", "(", "'FavorSizeOrSpeed'", ",", "map", "=", "{", "'1'", ":", "'t'", ",", "'2'", ":", "'s'", "}", ",", "prefix", "=", "'/O'", ")", "cl", "(", "'FloatingPointModel'", ",", "map", "=", "{", "'0'", ":", "'precise'", ",", "'1'", ":", "'strict'", ",", "'2'", ":", "'fast'", "}", ",", "prefix", "=", "'/fp:'", ",", "default", "=", "'0'", ")", "cl", "(", "'CompileAsManaged'", ",", "map", "=", "{", "'false'", ":", "''", ",", "'true'", ":", "'/clr'", "}", ")", "cl", "(", "'WholeProgramOptimization'", ",", "map", "=", "{", "'true'", ":", "'/GL'", "}", ")", "cl", "(", "'WarningLevel'", ",", "prefix", "=", "'/W'", ")", "cl", "(", "'WarnAsError'", ",", "map", "=", "{", "'true'", ":", "'/WX'", "}", ")", "cl", "(", "'CallingConvention'", ",", "map", "=", "{", "'0'", ":", "'d'", ",", "'1'", ":", "'r'", ",", "'2'", ":", "'z'", ",", "'3'", ":", "'v'", "}", ",", "prefix", "=", "'/G'", ")", "cl", "(", "'DebugInformationFormat'", ",", "map", "=", "{", "'1'", ":", "'7'", ",", "'3'", ":", "'i'", ",", "'4'", ":", "'I'", "}", ",", "prefix", "=", "'/Z'", ")", "cl", "(", "'RuntimeTypeInfo'", ",", "map", "=", "{", "'true'", ":", "'/GR'", ",", "'false'", ":", "'/GR-'", "}", ")", "cl", "(", "'EnableFunctionLevelLinking'", ",", "map", "=", "{", "'true'", ":", "'/Gy'", ",", "'false'", ":", "'/Gy-'", "}", ")", "cl", "(", "'MinimalRebuild'", ",", "map", "=", "{", "'true'", ":", "'/Gm'", "}", ")", "cl", "(", "'BufferSecurityCheck'", ",", "map", "=", "{", "'true'", ":", "'/GS'", ",", "'false'", ":", "'/GS-'", "}", ")", "cl", "(", "'BasicRuntimeChecks'", ",", "map", "=", "{", "'1'", ":", "'s'", ",", "'2'", ":", "'u'", ",", "'3'", ":", "'1'", "}", ",", "prefix", "=", "'/RTC'", ")", "cl", "(", "'RuntimeLibrary'", ",", "map", "=", "{", "'0'", ":", "'T'", ",", "'1'", ":", "'Td'", ",", "'2'", ":", "'D'", ",", "'3'", ":", "'Dd'", "}", ",", "prefix", "=", "'/M'", ")", "cl", "(", "'ExceptionHandling'", ",", "map", "=", "{", "'1'", ":", "'sc'", ",", "'2'", ":", "'a'", "}", ",", "prefix", "=", "'/EH'", ")", "cl", "(", "'DefaultCharIsUnsigned'", ",", "map", "=", "{", "'true'", ":", "'/J'", "}", ")", "cl", "(", "'TreatWChar_tAsBuiltInType'", ",", "map", "=", "{", "'false'", ":", "'-'", ",", "'true'", ":", "''", "}", ",", "prefix", "=", "'/Zc:wchar_t'", ")", "cl", "(", "'EnablePREfast'", ",", "map", "=", "{", "'true'", ":", "'/analyze'", "}", ")", "cl", "(", "'AdditionalOptions'", ",", "prefix", "=", "''", ")", "cl", "(", "'EnableEnhancedInstructionSet'", ",", "map", "=", "{", "'1'", ":", "'SSE'", ",", "'2'", ":", "'SSE2'", ",", "'3'", ":", "'AVX'", ",", "'4'", ":", "'IA32'", ",", "'5'", ":", "'AVX2'", "}", ",", "prefix", "=", "'/arch:'", ")", "cflags", ".", "extend", "(", "[", "'/FI'", "+", "f", "for", "f", "in", "self", ".", "_Setting", "(", "(", "'VCCLCompilerTool'", ",", "'ForcedIncludeFiles'", ")", ",", "config", ",", "default", "=", "[", "]", ")", "]", ")", "if", "self", ".", "vs_version", ".", "short_name", "in", "(", "'2013'", ",", "'2013e'", ",", "'2015'", ")", ":", "# New flag required in 2013 to maintain previous PDB behavior.", "cflags", ".", "append", "(", "'/FS'", ")", "# ninja handles parallelism by itself, don't have the compiler do it too.", "cflags", "=", "filter", "(", "lambda", "x", ":", "not", "x", ".", "startswith", "(", "'/MP'", ")", ",", "cflags", ")", "return", "cflags" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L426-L476
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/textio.py
python
Color.bk_red
(cls)
Make the text background color red.
Make the text background color red.
[ "Make", "the", "text", "background", "color", "red", "." ]
def bk_red(cls): "Make the text background color red." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_RED cls._set_text_attributes(wAttributes)
[ "def", "bk_red", "(", "cls", ")", ":", "wAttributes", "=", "cls", ".", "_get_text_attributes", "(", ")", "wAttributes", "&=", "~", "win32", ".", "BACKGROUND_MASK", "wAttributes", "|=", "win32", ".", "BACKGROUND_RED", "cls", ".", "_set_text_attributes", "(", "wAttributes", ")" ]
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/textio.py#L1048-L1053
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/packages/six.py
python
add_move
(move)
Add an item to six.moves.
Add an item to six.moves.
[ "Add", "an", "item", "to", "six", ".", "moves", "." ]
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
[ "def", "add_move", "(", "move", ")", ":", "setattr", "(", "_MovedItems", ",", "move", ".", "name", ",", "move", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/packages/six.py#L486-L488
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/ERP5Site.py
python
ERP5Site.getPortalDiscountTypeList
(self)
return self._getPortalGroupedTypeList('discount') or \ self._getPortalConfiguration('portal_discount_type_list')
Return discount types.
Return discount types.
[ "Return", "discount", "types", "." ]
def getPortalDiscountTypeList(self): """ Return discount types. """ return self._getPortalGroupedTypeList('discount') or \ self._getPortalConfiguration('portal_discount_type_list')
[ "def", "getPortalDiscountTypeList", "(", "self", ")", ":", "return", "self", ".", "_getPortalGroupedTypeList", "(", "'discount'", ")", "or", "self", ".", "_getPortalConfiguration", "(", "'portal_discount_type_list'", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/ERP5Site.py#L1249-L1254
IonicChina/ioniclub
208d5298939672ef44076bb8a7e8e6df5278e286
node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/input.py
python
TurnIntIntoStrInDict
(the_dict)
Given dict the_dict, recursively converts all integers into strings.
Given dict the_dict, recursively converts all integers into strings.
[ "Given", "dict", "the_dict", "recursively", "converts", "all", "integers", "into", "strings", "." ]
def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if isinstance(v, int): v = str(v) the_dict[k] = v elif isinstance(v, dict): TurnIntIntoStrInDict(v) elif isinstance(v, list): TurnIntIntoStrInList(v) if isinstance(k, int): the_dict[str(k)] = v del the_dict[k]
[ "def", "TurnIntIntoStrInDict", "(", "the_dict", ")", ":", "# Use items instead of iteritems because there's no need to try to look at", "# reinserted keys and their associated values.", "for", "k", ",", "v", "in", "the_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "int", ")", ":", "v", "=", "str", "(", "v", ")", "the_dict", "[", "k", "]", "=", "v", "elif", "isinstance", "(", "v", ",", "dict", ")", ":", "TurnIntIntoStrInDict", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "list", ")", ":", "TurnIntIntoStrInList", "(", "v", ")", "if", "isinstance", "(", "k", ",", "int", ")", ":", "the_dict", "[", "str", "(", "k", ")", "]", "=", "v", "del", "the_dict", "[", "k", "]" ]
https://github.com/IonicChina/ioniclub/blob/208d5298939672ef44076bb8a7e8e6df5278e286/node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/input.py#L2552-L2568
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/DocXMLRPCServer.py
python
DocCGIXMLRPCRequestHandler.handle_get
(self)
Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.
Handles the HTTP GET request.
[ "Handles", "the", "HTTP", "GET", "request", "." ]
def handle_get(self): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ response = self.generate_html_documentation() print 'Content-Type: text/html' print 'Content-Length: %d' % len(response) print sys.stdout.write(response)
[ "def", "handle_get", "(", "self", ")", ":", "response", "=", "self", ".", "generate_html_documentation", "(", ")", "print", "'Content-Type: text/html'", "print", "'Content-Length: %d'", "%", "len", "(", "response", ")", "print", "sys", ".", "stdout", ".", "write", "(", "response", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/DocXMLRPCServer.py#L263-L275
nodejs/node
ac3c33c1646bf46104c15ae035982c06364da9b8
deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.writeline
(self, x, node=None, extra=0)
Combination of newline and write.
Combination of newline and write.
[ "Combination", "of", "newline", "and", "write", "." ]
def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
[ "def", "writeline", "(", "self", ",", "x", ",", "node", "=", "None", ",", "extra", "=", "0", ")", ":", "self", ".", "newline", "(", "node", ",", "extra", ")", "self", ".", "write", "(", "x", ")" ]
https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/deps/v8/third_party/jinja2/compiler.py#L399-L402
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Backup/20170602095117/mdpopups/st3/mdpopups/__init__.py
python
clear_cache
()
Clear cache.
Clear cache.
[ "Clear", "cache", "." ]
def clear_cache(): """Clear cache.""" _clear_cache()
[ "def", "clear_cache", "(", ")", ":", "_clear_cache", "(", ")" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20170602095117/mdpopups/st3/mdpopups/__init__.py#L509-L512
Dieterbe/anthracite
10d5b54e21a79aa0abc66d638828f0f251beacb5
bottle.py
python
HooksPlugin.remove
(self, name, func)
Remove a callback from a hook.
Remove a callback from a hook.
[ "Remove", "a", "callback", "from", "a", "hook", "." ]
def remove(self, name, func): ''' Remove a callback from a hook. ''' was_empty = self._empty() if name in self.hooks and func in self.hooks[name]: self.hooks[name].remove(func) if self.app and not was_empty and self._empty(): self.app.reset()
[ "def", "remove", "(", "self", ",", "name", ",", "func", ")", ":", "was_empty", "=", "self", ".", "_empty", "(", ")", "if", "name", "in", "self", ".", "hooks", "and", "func", "in", "self", ".", "hooks", "[", "name", "]", ":", "self", ".", "hooks", "[", "name", "]", ".", "remove", "(", "func", ")", "if", "self", ".", "app", "and", "not", "was_empty", "and", "self", ".", "_empty", "(", ")", ":", "self", ".", "app", ".", "reset", "(", ")" ]
https://github.com/Dieterbe/anthracite/blob/10d5b54e21a79aa0abc66d638828f0f251beacb5/bottle.py#L1605-L1610
RASSec/A_Scan_Framework
4a46cf14b8c717dc0196071bbfd27e2d9c85bb17
pocscan/plugins/pocsuite/packages/requests/packages/urllib3/packages/six.py
python
with_metaclass
(meta, base=object)
return meta("NewBase", (base,), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, base=object): """Create a base class with a metaclass.""" return meta("NewBase", (base,), {})
[ "def", "with_metaclass", "(", "meta", ",", "base", "=", "object", ")", ":", "return", "meta", "(", "\"NewBase\"", ",", "(", "base", ",", ")", ",", "{", "}", ")" ]
https://github.com/RASSec/A_Scan_Framework/blob/4a46cf14b8c717dc0196071bbfd27e2d9c85bb17/pocscan/plugins/pocsuite/packages/requests/packages/urllib3/packages/six.py#L383-L385
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/werkzeug/datastructures.py
python
ContentRange.unset
(self)
Sets the units to `None` which indicates that the header should no longer be used.
Sets the units to `None` which indicates that the header should no longer be used.
[ "Sets", "the", "units", "to", "None", "which", "indicates", "that", "the", "header", "should", "no", "longer", "be", "used", "." ]
def unset(self): """Sets the units to `None` which indicates that the header should no longer be used. """ self.set(None, None, units=None)
[ "def", "unset", "(", "self", ")", ":", "self", ".", "set", "(", "None", ",", "None", ",", "units", "=", "None", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/werkzeug/datastructures.py#L2676-L2680
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/SimpleXMLRPCServer.py
python
SimpleXMLRPCDispatcher.register_instance
(self, instance, allow_dotted_names=False)
Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.
Registers an instance to respond to XML-RPC requests.
[ "Registers", "an", "instance", "to", "respond", "to", "XML", "-", "RPC", "requests", "." ]
def register_instance(self, instance, allow_dotted_names=False): """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. """ self.instance = instance self.allow_dotted_names = allow_dotted_names
[ "def", "register_instance", "(", "self", ",", "instance", ",", "allow_dotted_names", "=", "False", ")", ":", "self", ".", "instance", "=", "instance", "self", ".", "allow_dotted_names", "=", "allow_dotted_names" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/SimpleXMLRPCServer.py#L175-L209
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.start_write
(self, frame, node=None)
Yield or write into the frame buffer.
Yield or write into the frame buffer.
[ "Yield", "or", "write", "into", "the", "frame", "buffer", "." ]
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
[ "def", "start_write", "(", "self", ",", "frame", ",", "node", "=", "None", ")", ":", "if", "frame", ".", "buffer", "is", "None", ":", "self", ".", "writeline", "(", "'yield '", ",", "node", ")", "else", ":", "self", ".", "writeline", "(", "'%s.append('", "%", "frame", ".", "buffer", ",", "node", ")" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/v8/third_party/jinja2/compiler.py#L463-L468
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/distro.py
python
LinuxDistribution.version
(self, pretty=False, best=False)
return version
Return the version of the OS distribution, as a string. For details, see :func:`distro.version`.
Return the version of the OS distribution, as a string.
[ "Return", "the", "version", "of", "the", "OS", "distribution", "as", "a", "string", "." ]
def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ self.os_release_attr('version_id'), self.lsb_release_attr('release'), self.distro_release_attr('version_id'), self._parse_distro_release_content( self.os_release_attr('pretty_name')).get('version_id', ''), self._parse_distro_release_content( self.lsb_release_attr('description')).get('version_id', ''), self.uname_attr('release') ] version = '' if best: # This algorithm uses the last version in priority order that has # the best precision. If the versions are not in conflict, that # does not matter; otherwise, using the last one instead of the # first one might be considered a surprise. for v in versions: if v.count(".") > version.count(".") or version == '': version = v else: for v in versions: if v != '': version = v break if pretty and version and self.codename(): version = u'{0} ({1})'.format(version, self.codename()) return version
[ "def", "version", "(", "self", ",", "pretty", "=", "False", ",", "best", "=", "False", ")", ":", "versions", "=", "[", "self", ".", "os_release_attr", "(", "'version_id'", ")", ",", "self", ".", "lsb_release_attr", "(", "'release'", ")", ",", "self", ".", "distro_release_attr", "(", "'version_id'", ")", ",", "self", ".", "_parse_distro_release_content", "(", "self", ".", "os_release_attr", "(", "'pretty_name'", ")", ")", ".", "get", "(", "'version_id'", ",", "''", ")", ",", "self", ".", "_parse_distro_release_content", "(", "self", ".", "lsb_release_attr", "(", "'description'", ")", ")", ".", "get", "(", "'version_id'", ",", "''", ")", ",", "self", ".", "uname_attr", "(", "'release'", ")", "]", "version", "=", "''", "if", "best", ":", "# This algorithm uses the last version in priority order that has", "# the best precision. If the versions are not in conflict, that", "# does not matter; otherwise, using the last one instead of the", "# first one might be considered a surprise.", "for", "v", "in", "versions", ":", "if", "v", ".", "count", "(", "\".\"", ")", ">", "version", ".", "count", "(", "\".\"", ")", "or", "version", "==", "''", ":", "version", "=", "v", "else", ":", "for", "v", "in", "versions", ":", "if", "v", "!=", "''", ":", "version", "=", "v", "break", "if", "pretty", "and", "version", "and", "self", ".", "codename", "(", ")", ":", "version", "=", "u'{0} ({1})'", ".", "format", "(", "version", ",", "self", ".", "codename", "(", ")", ")", "return", "version" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/distro.py#L729-L761
OWASP/SecureTea-Project
ae55082d4a342f10099db4dead23267a517e1a66
securetea/lib/firewall/utils.py
python
check_port
(port)
return (int(port) >= 0 and int(port) < 65536)
Check whether the port is valid or not. Args: port (str): Port to check Raises: None Returns: bool: True if valid, else False
Check whether the port is valid or not.
[ "Check", "whether", "the", "port", "is", "valid", "or", "not", "." ]
def check_port(port): """ Check whether the port is valid or not. Args: port (str): Port to check Raises: None Returns: bool: True if valid, else False """ return (int(port) >= 0 and int(port) < 65536)
[ "def", "check_port", "(", "port", ")", ":", "return", "(", "int", "(", "port", ")", ">=", "0", "and", "int", "(", "port", ")", "<", "65536", ")" ]
https://github.com/OWASP/SecureTea-Project/blob/ae55082d4a342f10099db4dead23267a517e1a66/securetea/lib/firewall/utils.py#L160-L174
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/npm/node_modules/node-gyp/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/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py#L83-L85
taskcluster/taskcluster
7e7aa2d7b9a026cee78a3c970244f91d638c45a1
clients/client-py/taskcluster/generated/hooks.py
python
Hooks.triggerHook
(self, *args, **kwargs)
return self._makeApiCall(self.funcinfo["triggerHook"], *args, **kwargs)
Trigger a hook This endpoint will trigger the creation of a task from a hook definition. The HTTP payload must match the hooks `triggerSchema`. If it does, it is provided as the `payload` property of the JSON-e context used to render the task template. This method is ``stable``
Trigger a hook
[ "Trigger", "a", "hook" ]
def triggerHook(self, *args, **kwargs): """ Trigger a hook This endpoint will trigger the creation of a task from a hook definition. The HTTP payload must match the hooks `triggerSchema`. If it does, it is provided as the `payload` property of the JSON-e context used to render the task template. This method is ``stable`` """ return self._makeApiCall(self.funcinfo["triggerHook"], *args, **kwargs)
[ "def", "triggerHook", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"triggerHook\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/taskcluster/taskcluster/blob/7e7aa2d7b9a026cee78a3c970244f91d638c45a1/clients/client-py/taskcluster/generated/hooks.py#L124-L137
stdlib-js/stdlib
e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df
lib/node_modules/@stdlib/math/base/special/inv/benchmark/python/benchmark.py
python
print_summary
(total, passing)
Print the benchmark summary. # Arguments * `total`: total number of tests * `passing`: number of passing tests
Print the benchmark summary.
[ "Print", "the", "benchmark", "summary", "." ]
def print_summary(total, passing): """Print the benchmark summary. # Arguments * `total`: total number of tests * `passing`: number of passing tests """ print("#") print("1.." + str(total)) # TAP plan print("# total " + str(total)) print("# pass " + str(passing)) print("#") print("# ok")
[ "def", "print_summary", "(", "total", ",", "passing", ")", ":", "print", "(", "\"#\"", ")", "print", "(", "\"1..\"", "+", "str", "(", "total", ")", ")", "# TAP plan", "print", "(", "\"# total \"", "+", "str", "(", "total", ")", ")", "print", "(", "\"# pass \"", "+", "str", "(", "passing", ")", ")", "print", "(", "\"#\"", ")", "print", "(", "\"# ok\"", ")" ]
https://github.com/stdlib-js/stdlib/blob/e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df/lib/node_modules/@stdlib/math/base/special/inv/benchmark/python/benchmark.py#L34-L48
hyperledger/cello
000905d29e502a38d7576f20884de3c5aa371307
src/api-engine/api/lib/peer/channel.py
python
Channel.signconfigtx
(self, channel_tx)
return res
Signs a configtx update. params: channel_tx: Configuration transaction file generated by a tool such as configtxgen for submitting to orderer
Signs a configtx update. params: channel_tx: Configuration transaction file generated by a tool such as configtxgen for submitting to orderer
[ "Signs", "a", "configtx", "update", ".", "params", ":", "channel_tx", ":", "Configuration", "transaction", "file", "generated", "by", "a", "tool", "such", "as", "configtxgen", "for", "submitting", "to", "orderer" ]
def signconfigtx(self, channel_tx): """ Signs a configtx update. params: channel_tx: Configuration transaction file generated by a tool such as configtxgen for submitting to orderer """ try: res = os.system( "{} channel signconfigtx -f {}".format(self.peer, channel_tx)) except Exception as e: err_msg = "signs a configtx update failed {}".format(e) raise Exception(err_msg) res = res >> 8 return res
[ "def", "signconfigtx", "(", "self", ",", "channel_tx", ")", ":", "try", ":", "res", "=", "os", ".", "system", "(", "\"{} channel signconfigtx -f {}\"", ".", "format", "(", "self", ".", "peer", ",", "channel_tx", ")", ")", "except", "Exception", "as", "e", ":", "err_msg", "=", "\"signs a configtx update failed {}\"", ".", "format", "(", "e", ")", "raise", "Exception", "(", "err_msg", ")", "res", "=", "res", ">>", "8", "return", "res" ]
https://github.com/hyperledger/cello/blob/000905d29e502a38d7576f20884de3c5aa371307/src/api-engine/api/lib/peer/channel.py#L87-L100
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Folder_getContentListReportSectionList.py
python
getReportSectionForObject
(doc)
return ReportSection(path=doc.getPath(), form_id=form_id, title=doc.getTitleOrId())
Get all possible report section for object.
Get all possible report section for object.
[ "Get", "all", "possible", "report", "section", "for", "object", "." ]
def getReportSectionForObject(doc): """ Get all possible report section for object. """ doc = doc.getObject() actions = portal.portal_actions.listFilteredActionsFor(doc) # use the default view action = actions['object_view'][0] # unless a print action exists if actions.get('object_print'): # we ignore the default print action. valid_print_dialog_list = [ai for ai in actions['object_print'] if getFormIdFromAction(ai) != 'Base_viewPrintDialog'] if valid_print_dialog_list: action = valid_print_dialog_list[0] form_id = getFormIdFromAction(action) return ReportSection(path=doc.getPath(), form_id=form_id, title=doc.getTitleOrId())
[ "def", "getReportSectionForObject", "(", "doc", ")", ":", "doc", "=", "doc", ".", "getObject", "(", ")", "actions", "=", "portal", ".", "portal_actions", ".", "listFilteredActionsFor", "(", "doc", ")", "# use the default view", "action", "=", "actions", "[", "'object_view'", "]", "[", "0", "]", "# unless a print action exists", "if", "actions", ".", "get", "(", "'object_print'", ")", ":", "# we ignore the default print action.", "valid_print_dialog_list", "=", "[", "ai", "for", "ai", "in", "actions", "[", "'object_print'", "]", "if", "getFormIdFromAction", "(", "ai", ")", "!=", "'Base_viewPrintDialog'", "]", "if", "valid_print_dialog_list", ":", "action", "=", "valid_print_dialog_list", "[", "0", "]", "form_id", "=", "getFormIdFromAction", "(", "action", ")", "return", "ReportSection", "(", "path", "=", "doc", ".", "getPath", "(", ")", ",", "form_id", "=", "form_id", ",", "title", "=", "doc", ".", "getTitleOrId", "(", ")", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Folder_getContentListReportSectionList.py#L12-L27
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/closured/lib/python2.7/nntplib.py
python
NNTP.getwelcome
(self)
return self.welcome
Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.
Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.
[ "Get", "the", "welcome", "message", "from", "the", "server", "(", "this", "is", "read", "and", "squirreled", "away", "by", "__init__", "()", ")", ".", "If", "the", "response", "code", "is", "200", "posting", "is", "allowed", ";", "if", "it", "201", "posting", "is", "not", "allowed", "." ]
def getwelcome(self): """Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.""" if self.debugging: print '*welcome*', repr(self.welcome) return self.welcome
[ "def", "getwelcome", "(", "self", ")", ":", "if", "self", ".", "debugging", ":", "print", "'*welcome*'", ",", "repr", "(", "self", ".", "welcome", ")", "return", "self", ".", "welcome" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/nntplib.py#L171-L178
OWASP/DVSA
cfa5c67068a4b8657fc1cf9a0d0d6e006c4a126f
backend/src/functions/admin/admin_shell/jsonpickle/backend.py
python
JSONBackend.decode
(self, string)
Attempt to decode an object from a JSON string. This tries the loaded backends in order and passes along the last exception if no backends are able to decode the string.
Attempt to decode an object from a JSON string.
[ "Attempt", "to", "decode", "an", "object", "from", "a", "JSON", "string", "." ]
def decode(self, string): """ Attempt to decode an object from a JSON string. This tries the loaded backends in order and passes along the last exception if no backends are able to decode the string. """ self._verify() if not self._fallthrough: name = self._backend_names[0] return self.backend_decode(name, string) for idx, name in enumerate(self._backend_names): try: return self.backend_decode(name, string) except self._decoder_exceptions[name] as e: if idx == len(self._backend_names) - 1: raise e else: pass
[ "def", "decode", "(", "self", ",", "string", ")", ":", "self", ".", "_verify", "(", ")", "if", "not", "self", ".", "_fallthrough", ":", "name", "=", "self", ".", "_backend_names", "[", "0", "]", "return", "self", ".", "backend_decode", "(", "name", ",", "string", ")", "for", "idx", ",", "name", "in", "enumerate", "(", "self", ".", "_backend_names", ")", ":", "try", ":", "return", "self", ".", "backend_decode", "(", "name", ",", "string", ")", "except", "self", ".", "_decoder_exceptions", "[", "name", "]", "as", "e", ":", "if", "idx", "==", "len", "(", "self", ".", "_backend_names", ")", "-", "1", ":", "raise", "e", "else", ":", "pass" ]
https://github.com/OWASP/DVSA/blob/cfa5c67068a4b8657fc1cf9a0d0d6e006c4a126f/backend/src/functions/admin/admin_shell/jsonpickle/backend.py#L191-L212
inkscope/inkscope
8c4303691a17837c6d3b5c89b40b89d9f5de4252
inkscopeCtrl/S3/utils.py
python
_amz_canonicalize
(headers)
return "".join(parts)
r"""Canonicalize AMZ headers in that certain AWS way. >>> _amz_canonicalize({"x-amz-test": "test"}) 'x-amz-test:test\n' >>> _amz_canonicalize({"x-amz-first": "test", ... "x-amz-second": "hello"}) 'x-amz-first:test\nx-amz-second:hello\n' >>> _amz_canonicalize({}) ''
r"""Canonicalize AMZ headers in that certain AWS way.
[ "r", "Canonicalize", "AMZ", "headers", "in", "that", "certain", "AWS", "way", "." ]
def _amz_canonicalize(headers): r"""Canonicalize AMZ headers in that certain AWS way. >>> _amz_canonicalize({"x-amz-test": "test"}) 'x-amz-test:test\n' >>> _amz_canonicalize({"x-amz-first": "test", ... "x-amz-second": "hello"}) 'x-amz-first:test\nx-amz-second:hello\n' >>> _amz_canonicalize({}) '' """ rv = {} for header, value in headers.iteritems(): header = header.lower() if header.startswith("x-amz-"): rv.setdefault(header, []).append(value) parts = [] for key in sorted(rv): parts.append("%s:%s\n" % (key, ",".join(rv[key]))) return "".join(parts)
[ "def", "_amz_canonicalize", "(", "headers", ")", ":", "rv", "=", "{", "}", "for", "header", ",", "value", "in", "headers", ".", "iteritems", "(", ")", ":", "header", "=", "header", ".", "lower", "(", ")", "if", "header", ".", "startswith", "(", "\"x-amz-\"", ")", ":", "rv", ".", "setdefault", "(", "header", ",", "[", "]", ")", ".", "append", "(", "value", ")", "parts", "=", "[", "]", "for", "key", "in", "sorted", "(", "rv", ")", ":", "parts", ".", "append", "(", "\"%s:%s\\n\"", "%", "(", "key", ",", "\",\"", ".", "join", "(", "rv", "[", "key", "]", ")", ")", ")", "return", "\"\"", ".", "join", "(", "parts", ")" ]
https://github.com/inkscope/inkscope/blob/8c4303691a17837c6d3b5c89b40b89d9f5de4252/inkscopeCtrl/S3/utils.py#L37-L56
xtk/X
04c1aa856664a8517d23aefd94c470d47130aead
lib/selenium/selenium/selenium.py
python
selenium.get_all_fields
(self)
return self.get_string_array("getAllFields", [])
Returns the IDs of all input fields on the page. If a given field has no ID, it will appear as "" in this array.
Returns the IDs of all input fields on the page. If a given field has no ID, it will appear as "" in this array.
[ "Returns", "the", "IDs", "of", "all", "input", "fields", "on", "the", "page", ".", "If", "a", "given", "field", "has", "no", "ID", "it", "will", "appear", "as", "in", "this", "array", "." ]
def get_all_fields(self): """ Returns the IDs of all input fields on the page. If a given field has no ID, it will appear as "" in this array. """ return self.get_string_array("getAllFields", [])
[ "def", "get_all_fields", "(", "self", ")", ":", "return", "self", ".", "get_string_array", "(", "\"getAllFields\"", ",", "[", "]", ")" ]
https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/selenium/selenium/selenium.py#L1419-L1428
wotermelon/toJump
3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f
lib/mac/systrace/catapult/devil/devil/android/apk_helper.py
python
ApkHelper.HasIsolatedProcesses
(self)
Returns whether any services exist that use isolatedProcess=true.
Returns whether any services exist that use isolatedProcess=true.
[ "Returns", "whether", "any", "services", "exist", "that", "use", "isolatedProcess", "=", "true", "." ]
def HasIsolatedProcesses(self): """Returns whether any services exist that use isolatedProcess=true.""" manifest_info = self._GetManifest() try: applications = manifest_info['manifest'][0].get('application', []) services = itertools.chain( *(application.get('service', []) for application in applications)) return any( int(s.get('android:isolatedProcess', '0'), 0) for s in services) except KeyError: return False
[ "def", "HasIsolatedProcesses", "(", "self", ")", ":", "manifest_info", "=", "self", ".", "_GetManifest", "(", ")", "try", ":", "applications", "=", "manifest_info", "[", "'manifest'", "]", "[", "0", "]", ".", "get", "(", "'application'", ",", "[", "]", ")", "services", "=", "itertools", ".", "chain", "(", "*", "(", "application", ".", "get", "(", "'service'", ",", "[", "]", ")", "for", "application", "in", "applications", ")", ")", "return", "any", "(", "int", "(", "s", ".", "get", "(", "'android:isolatedProcess'", ",", "'0'", ")", ",", "0", ")", "for", "s", "in", "services", ")", "except", "KeyError", ":", "return", "False" ]
https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/devil/devil/android/apk_helper.py#L147-L158
getredash/redash
49fe29579a56e7a8e206895586eca1736a6d210d
redash/settings/helpers.py
python
add_decode_responses_to_redis_url
(url)
return urlunparse( [ parsed.scheme, parsed.netloc, parsed.path, parsed.params, query, parsed.fragment, ] )
Make sure that the Redis URL includes the `decode_responses` option.
Make sure that the Redis URL includes the `decode_responses` option.
[ "Make", "sure", "that", "the", "Redis", "URL", "includes", "the", "decode_responses", "option", "." ]
def add_decode_responses_to_redis_url(url): """Make sure that the Redis URL includes the `decode_responses` option.""" parsed = urlparse(url) query = "decode_responses=True" if parsed.query and "decode_responses" not in parsed.query: query = "{}&{}".format(parsed.query, query) elif "decode_responses" in parsed.query: query = parsed.query return urlunparse( [ parsed.scheme, parsed.netloc, parsed.path, parsed.params, query, parsed.fragment, ] )
[ "def", "add_decode_responses_to_redis_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "query", "=", "\"decode_responses=True\"", "if", "parsed", ".", "query", "and", "\"decode_responses\"", "not", "in", "parsed", ".", "query", ":", "query", "=", "\"{}&{}\"", ".", "format", "(", "parsed", ".", "query", ",", "query", ")", "elif", "\"decode_responses\"", "in", "parsed", ".", "query", ":", "query", "=", "parsed", ".", "query", "return", "urlunparse", "(", "[", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "parsed", ".", "path", ",", "parsed", ".", "params", ",", "query", ",", "parsed", ".", "fragment", ",", "]", ")" ]
https://github.com/getredash/redash/blob/49fe29579a56e7a8e206895586eca1736a6d210d/redash/settings/helpers.py#L45-L64
JoneXiong/DjangoX
c2a723e209ef13595f571923faac7eb29e4c8150
xadmin/plugins/quickform.py
python
RelatedFieldWidgetWrapper.build_attrs
(self, extra_attrs=None, **kwargs)
return self.attrs
Helper function for building an attribute dictionary.
Helper function for building an attribute dictionary.
[ "Helper", "function", "for", "building", "an", "attribute", "dictionary", "." ]
def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
[ "def", "build_attrs", "(", "self", ",", "extra_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "attrs", "=", "self", ".", "widget", ".", "build_attrs", "(", "extra_attrs", "=", "None", ",", "*", "*", "kwargs", ")", "return", "self", ".", "attrs" ]
https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/plugins/quickform.py#L87-L90
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python2/site-packages/cherrypy/_helper.py
python
_ClassPropertyDescriptor.__init__
(self, fget, fset=None)
Instantiated by ``_helper.classproperty``.
Instantiated by ``_helper.classproperty``.
[ "Instantiated", "by", "_helper", ".", "classproperty", "." ]
def __init__(self, fget, fset=None): """Instantiated by ``_helper.classproperty``.""" self.fget = fget self.fset = fset
[ "def", "__init__", "(", "self", ",", "fget", ",", "fset", "=", "None", ")", ":", "self", ".", "fget", "=", "fget", "self", ".", "fset", "=", "fset" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python2/site-packages/cherrypy/_helper.py#L323-L326
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
tools/gyp/pylib/gyp/win_tool.py
python
WinTool.ExecRecursiveMirror
(self, source, dest)
Emulation of rm -rf out && cp -af in out.
Emulation of rm -rf out && cp -af in out.
[ "Emulation", "of", "rm", "-", "rf", "out", "&&", "cp", "-", "af", "in", "out", "." ]
def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): def _on_error(fn, path, excinfo): # The operation failed, possibly because the file is set to # read-only. If that's why, make it writable and try the op again. if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWRITE) fn(path) shutil.rmtree(dest, onerror=_on_error) else: if not os.access(dest, os.W_OK): # Attempt to make the file writable before deleting it. os.chmod(dest, stat.S_IWRITE) os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest)
[ "def", "ExecRecursiveMirror", "(", "self", ",", "source", ",", "dest", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "dest", ")", ":", "def", "_on_error", "(", "fn", ",", "path", ",", "excinfo", ")", ":", "# The operation failed, possibly because the file is set to", "# read-only. If that's why, make it writable and try the op again.", "if", "not", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")", ":", "os", ".", "chmod", "(", "path", ",", "stat", ".", "S_IWRITE", ")", "fn", "(", "path", ")", "shutil", ".", "rmtree", "(", "dest", ",", "onerror", "=", "_on_error", ")", "else", ":", "if", "not", "os", ".", "access", "(", "dest", ",", "os", ".", "W_OK", ")", ":", "# Attempt to make the file writable before deleting it.", "os", ".", "chmod", "(", "dest", ",", "stat", ".", "S_IWRITE", ")", "os", ".", "unlink", "(", "dest", ")", "if", "os", ".", "path", ".", "isdir", "(", "source", ")", ":", "shutil", ".", "copytree", "(", "source", ",", "dest", ")", "else", ":", "shutil", ".", "copy2", "(", "source", ",", "dest", ")" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/tools/gyp/pylib/gyp/win_tool.py#L89-L109
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/hr_timesheet/models/hr_timesheet.py
python
AccountAnalyticLine.fields_view_get
(self, view_id=None, view_type='form', toolbar=False, submenu=False)
return result
Set the correct label for `unit_amount`, depending on company UoM
Set the correct label for `unit_amount`, depending on company UoM
[ "Set", "the", "correct", "label", "for", "unit_amount", "depending", "on", "company", "UoM" ]
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): """ Set the correct label for `unit_amount`, depending on company UoM """ result = super(AccountAnalyticLine, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) result['arch'] = self._apply_timesheet_label(result['arch'], view_type=view_type) return result
[ "def", "fields_view_get", "(", "self", ",", "view_id", "=", "None", ",", "view_type", "=", "'form'", ",", "toolbar", "=", "False", ",", "submenu", "=", "False", ")", ":", "result", "=", "super", "(", "AccountAnalyticLine", ",", "self", ")", ".", "fields_view_get", "(", "view_id", "=", "view_id", ",", "view_type", "=", "view_type", ",", "toolbar", "=", "toolbar", ",", "submenu", "=", "submenu", ")", "result", "[", "'arch'", "]", "=", "self", ".", "_apply_timesheet_label", "(", "result", "[", "'arch'", "]", ",", "view_type", "=", "view_type", ")", "return", "result" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/hr_timesheet/models/hr_timesheet.py#L154-L158
anpylar/anpylar
ed80696b25a42ee0e7b845042bbb108326abae69
anpylar/future.py
python
Future.exception
(self)
Return the exception that was set on this future. The exception (or None if no exception was set) is returned only if the future is done. If the future has been cancelled, raises CancelledError. If the future isn’t done yet, raises InvalidStateError.
Return the exception that was set on this future.
[ "Return", "the", "exception", "that", "was", "set", "on", "this", "future", "." ]
def exception(self): """Return the exception that was set on this future. The exception (or None if no exception was set) is returned only if the future is done. If the future has been cancelled, raises CancelledError. If the future isn’t done yet, raises InvalidStateError. """ if self._status == Future.STATUS_STARTED: raise InvalidStateError() if self._status == Future.STATUS_CANCELED: raise CancelledError() if self._status == Future.STATUS_ERROR: return self._exception
[ "def", "exception", "(", "self", ")", ":", "if", "self", ".", "_status", "==", "Future", ".", "STATUS_STARTED", ":", "raise", "InvalidStateError", "(", ")", "if", "self", ".", "_status", "==", "Future", ".", "STATUS_CANCELED", ":", "raise", "CancelledError", "(", ")", "if", "self", ".", "_status", "==", "Future", ".", "STATUS_ERROR", ":", "return", "self", ".", "_exception" ]
https://github.com/anpylar/anpylar/blob/ed80696b25a42ee0e7b845042bbb108326abae69/anpylar/future.py#L102-L115
webrtc/apprtc
db975e22ea07a0c11a4179d4beb2feb31cf344f4
src/third_party/apiclient/http.py
python
MediaFileUpload.to_json
(self)
return self._to_json(strip=['_fd'])
Creating a JSON representation of an instance of MediaFileUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json().
Creating a JSON representation of an instance of MediaFileUpload.
[ "Creating", "a", "JSON", "representation", "of", "an", "instance", "of", "MediaFileUpload", "." ]
def to_json(self): """Creating a JSON representation of an instance of MediaFileUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(strip=['_fd'])
[ "def", "to_json", "(", "self", ")", ":", "return", "self", ".", "_to_json", "(", "strip", "=", "[", "'_fd'", "]", ")" ]
https://github.com/webrtc/apprtc/blob/db975e22ea07a0c11a4179d4beb2feb31cf344f4/src/third_party/apiclient/http.py#L428-L435
aosabook/500lines
fba689d101eb5600f5c8f4d7fd79912498e950e2
incomplete/bytecode-compiler/check_subset.py
python
Checker.generic_visit
(self, t)
Any node type we don't know about is an error.
Any node type we don't know about is an error.
[ "Any", "node", "type", "we", "don", "t", "know", "about", "is", "an", "error", "." ]
def generic_visit(self, t): "Any node type we don't know about is an error." assert False, t
[ "def", "generic_visit", "(", "self", ",", "t", ")", ":", "assert", "False", ",", "t" ]
https://github.com/aosabook/500lines/blob/fba689d101eb5600f5c8f4d7fd79912498e950e2/incomplete/bytecode-compiler/check_subset.py#L19-L21
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/setuptools/command/easy_install.py
python
get_site_dirs
()
return sitedirs
Return a list of 'site' dirs
Return a list of 'site' dirs
[ "Return", "a", "list", "of", "site", "dirs" ]
def get_site_dirs(): """ Return a list of 'site' dirs """ sitedirs = [] # start with PYTHONPATH sitedirs.extend(_pythonpath()) prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: if sys.platform in ('os2emx', 'riscos'): sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) elif os.sep == '/': sitedirs.extend([ os.path.join( prefix, "lib", "python" + sys.version[:3], "site-packages", ), os.path.join(prefix, "lib", "site-python"), ]) else: sitedirs.extend([ prefix, os.path.join(prefix, "lib", "site-packages"), ]) if sys.platform == 'darwin': # for framework builds *only* we add the standard Apple # locations. Currently only per-user, but /Library and # /Network/Library could be added too if 'Python.framework' in prefix: home = os.environ.get('HOME') if home: home_sp = os.path.join( home, 'Library', 'Python', sys.version[:3], 'site-packages', ) sitedirs.append(home_sp) lib_paths = get_path('purelib'), get_path('platlib') for site_lib in lib_paths: if site_lib not in sitedirs: sitedirs.append(site_lib) if site.ENABLE_USER_SITE: sitedirs.append(site.USER_SITE) try: sitedirs.extend(site.getsitepackages()) except AttributeError: pass sitedirs = list(map(normalize_path, sitedirs)) return sitedirs
[ "def", "get_site_dirs", "(", ")", ":", "sitedirs", "=", "[", "]", "# start with PYTHONPATH", "sitedirs", ".", "extend", "(", "_pythonpath", "(", ")", ")", "prefixes", "=", "[", "sys", ".", "prefix", "]", "if", "sys", ".", "exec_prefix", "!=", "sys", ".", "prefix", ":", "prefixes", ".", "append", "(", "sys", ".", "exec_prefix", ")", "for", "prefix", "in", "prefixes", ":", "if", "prefix", ":", "if", "sys", ".", "platform", "in", "(", "'os2emx'", ",", "'riscos'", ")", ":", "sitedirs", ".", "append", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "\"Lib\"", ",", "\"site-packages\"", ")", ")", "elif", "os", ".", "sep", "==", "'/'", ":", "sitedirs", ".", "extend", "(", "[", "os", ".", "path", ".", "join", "(", "prefix", ",", "\"lib\"", ",", "\"python\"", "+", "sys", ".", "version", "[", ":", "3", "]", ",", "\"site-packages\"", ",", ")", ",", "os", ".", "path", ".", "join", "(", "prefix", ",", "\"lib\"", ",", "\"site-python\"", ")", ",", "]", ")", "else", ":", "sitedirs", ".", "extend", "(", "[", "prefix", ",", "os", ".", "path", ".", "join", "(", "prefix", ",", "\"lib\"", ",", "\"site-packages\"", ")", ",", "]", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# for framework builds *only* we add the standard Apple", "# locations. Currently only per-user, but /Library and", "# /Network/Library could be added too", "if", "'Python.framework'", "in", "prefix", ":", "home", "=", "os", ".", "environ", ".", "get", "(", "'HOME'", ")", "if", "home", ":", "home_sp", "=", "os", ".", "path", ".", "join", "(", "home", ",", "'Library'", ",", "'Python'", ",", "sys", ".", "version", "[", ":", "3", "]", ",", "'site-packages'", ",", ")", "sitedirs", ".", "append", "(", "home_sp", ")", "lib_paths", "=", "get_path", "(", "'purelib'", ")", ",", "get_path", "(", "'platlib'", ")", "for", "site_lib", "in", "lib_paths", ":", "if", "site_lib", "not", "in", "sitedirs", ":", "sitedirs", ".", "append", "(", "site_lib", ")", "if", "site", ".", "ENABLE_USER_SITE", ":", "sitedirs", ".", "append", "(", "site", ".", "USER_SITE", ")", "try", ":", "sitedirs", ".", "extend", "(", "site", ".", "getsitepackages", "(", ")", ")", "except", "AttributeError", ":", "pass", "sitedirs", "=", "list", "(", "map", "(", "normalize_path", ",", "sitedirs", ")", ")", "return", "sitedirs" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/setuptools/command/easy_install.py#L1393-L1455
scottrogowski/code2flow
37e45ca4340289f8ceec79b3fe5131c401387c58
code2flow/ruby.py
python
get_call_from_send_el
(func_el)
return Call(token=token, owner_token=owner)
Given an ast that represents a send call, clear and create our generic Call object. Some calls have no chance at resolution (e.g. array[2](param)) so we return nothing instead. :param func_el ast: :rtype: Call|None
Given an ast that represents a send call, clear and create our generic Call object. Some calls have no chance at resolution (e.g. array[2](param)) so we return nothing instead.
[ "Given", "an", "ast", "that", "represents", "a", "send", "call", "clear", "and", "create", "our", "generic", "Call", "object", ".", "Some", "calls", "have", "no", "chance", "at", "resolution", "(", "e", ".", "g", ".", "array", "[", "2", "]", "(", "param", "))", "so", "we", "return", "nothing", "instead", "." ]
def get_call_from_send_el(func_el): """ Given an ast that represents a send call, clear and create our generic Call object. Some calls have no chance at resolution (e.g. array[2](param)) so we return nothing instead. :param func_el ast: :rtype: Call|None """ owner_el = func_el[1] token = func_el[2] owner = resolve_owner(owner_el) if owner and token == 'new': # Taking out owner_token for constructors as a little hack to make it work return Call(token=owner) return Call(token=token, owner_token=owner)
[ "def", "get_call_from_send_el", "(", "func_el", ")", ":", "owner_el", "=", "func_el", "[", "1", "]", "token", "=", "func_el", "[", "2", "]", "owner", "=", "resolve_owner", "(", "owner_el", ")", "if", "owner", "and", "token", "==", "'new'", ":", "# Taking out owner_token for constructors as a little hack to make it work", "return", "Call", "(", "token", "=", "owner", ")", "return", "Call", "(", "token", "=", "token", ",", "owner_token", "=", "owner", ")" ]
https://github.com/scottrogowski/code2flow/blob/37e45ca4340289f8ceec79b3fe5131c401387c58/code2flow/ruby.py#L39-L55
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetCflagsObjCC
(self, configname)
return cflags_objcc
Returns flags that need to be added to .mm compilations.
Returns flags that need to be added to .mm compilations.
[ "Returns", "flags", "that", "need", "to", "be", "added", "to", ".", "mm", "compilations", "." ]
def GetCflagsObjCC(self, configname): """Returns flags that need to be added to .mm compilations.""" self.configname = configname cflags_objcc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) self._AddObjectiveCARCFlags(cflags_objcc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc) if self._Test('GCC_OBJC_CALL_CXX_CDTORS', 'YES', default='NO'): cflags_objcc.append('-fobjc-call-cxx-cdtors') self.configname = None return cflags_objcc
[ "def", "GetCflagsObjCC", "(", "self", ",", "configname", ")", ":", "self", ".", "configname", "=", "configname", "cflags_objcc", "=", "[", "]", "self", ".", "_AddObjectiveCGarbageCollectionFlags", "(", "cflags_objcc", ")", "self", ".", "_AddObjectiveCARCFlags", "(", "cflags_objcc", ")", "self", ".", "_AddObjectiveCMissingPropertySynthesisFlags", "(", "cflags_objcc", ")", "if", "self", ".", "_Test", "(", "'GCC_OBJC_CALL_CXX_CDTORS'", ",", "'YES'", ",", "default", "=", "'NO'", ")", ":", "cflags_objcc", ".", "append", "(", "'-fobjc-call-cxx-cdtors'", ")", "self", ".", "configname", "=", "None", "return", "cflags_objcc" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L662-L672
IonicChina/ioniclub
208d5298939672ef44076bb8a7e8e6df5278e286
node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/generator/make.py
python
EscapeCppDefine
(s)
return s.replace('#', r'\#')
Escapes a CPP define so that it will reach the compiler unaltered.
Escapes a CPP define so that it will reach the compiler unaltered.
[ "Escapes", "a", "CPP", "define", "so", "that", "it", "will", "reach", "the", "compiler", "unaltered", "." ]
def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace('#', r'\#')
[ "def", "EscapeCppDefine", "(", "s", ")", ":", "s", "=", "EscapeShellArgument", "(", "s", ")", "s", "=", "EscapeMakeVariableExpansion", "(", "s", ")", "# '#' characters must be escaped even embedded in a string, else Make will", "# treat it as the start of a comment.", "return", "s", ".", "replace", "(", "'#'", ",", "r'\\#'", ")" ]
https://github.com/IonicChina/ioniclub/blob/208d5298939672ef44076bb8a7e8e6df5278e286/node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/generator/make.py#L598-L604
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
deps/v8/third_party/jinja2/parser.py
python
Parser.fail_eof
(self, end_tokens=None, lineno=None)
return self._fail_ut_eof(None, stack, lineno)
Like fail_unknown_tag but for end of template situations.
Like fail_unknown_tag but for end of template situations.
[ "Like", "fail_unknown_tag", "but", "for", "end", "of", "template", "situations", "." ]
def fail_eof(self, end_tokens=None, lineno=None): """Like fail_unknown_tag but for end of template situations.""" stack = list(self._end_token_stack) if end_tokens is not None: stack.append(end_tokens) return self._fail_ut_eof(None, stack, lineno)
[ "def", "fail_eof", "(", "self", ",", "end_tokens", "=", "None", ",", "lineno", "=", "None", ")", ":", "stack", "=", "list", "(", "self", ".", "_end_token_stack", ")", "if", "end_tokens", "is", "not", "None", ":", "stack", ".", "append", "(", "end_tokens", ")", "return", "self", ".", "_fail_ut_eof", "(", "None", ",", "stack", ",", "lineno", ")" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/v8/third_party/jinja2/parser.py#L90-L95
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/werkzeug/datastructures.py
python
ContentRange.set
(self, start, stop, length=None, units="bytes")
Simple method to update the ranges.
Simple method to update the ranges.
[ "Simple", "method", "to", "update", "the", "ranges", "." ]
def set(self, start, stop, length=None, units="bytes"): """Simple method to update the ranges.""" assert is_byte_range_valid(start, stop, length), "Bad range provided" self._units = units self._start = start self._stop = stop self._length = length if self.on_update is not None: self.on_update(self)
[ "def", "set", "(", "self", ",", "start", ",", "stop", ",", "length", "=", "None", ",", "units", "=", "\"bytes\"", ")", ":", "assert", "is_byte_range_valid", "(", "start", ",", "stop", ",", "length", ")", ",", "\"Bad range provided\"", "self", ".", "_units", "=", "units", "self", ".", "_start", "=", "start", "self", ".", "_stop", "=", "stop", "self", ".", "_length", "=", "length", "if", "self", ".", "on_update", "is", "not", "None", ":", "self", ".", "on_update", "(", "self", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/werkzeug/datastructures.py#L2666-L2674
voilet/cmdb
b4c8452ac341dc4b9848e2eefa50f1c34ff688e2
monitor/views.py
python
HttpMonitorPage
(request, uuid)
return render_to_response('monitor/httppage.html', locals(), context_instance=RequestContext(request))
http监控列表
http监控列表
[ "http监控列表" ]
def HttpMonitorPage(request, uuid): """ http监控列表 """ data = MonitorHttp.objects.get(pk=uuid) log_data = MonitorHttpLog.objects.filter(monitorId=uuid).order_by("-createtime") return render_to_response('monitor/httppage.html', locals(), context_instance=RequestContext(request))
[ "def", "HttpMonitorPage", "(", "request", ",", "uuid", ")", ":", "data", "=", "MonitorHttp", ".", "objects", ".", "get", "(", "pk", "=", "uuid", ")", "log_data", "=", "MonitorHttpLog", ".", "objects", ".", "filter", "(", "monitorId", "=", "uuid", ")", ".", "order_by", "(", "\"-createtime\"", ")", "return", "render_to_response", "(", "'monitor/httppage.html'", ",", "locals", "(", ")", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")" ]
https://github.com/voilet/cmdb/blob/b4c8452ac341dc4b9848e2eefa50f1c34ff688e2/monitor/views.py#L73-L77
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py
python
Process.poke_dword
(self, lpBaseAddress, unpackedValue)
return self.__poke_c_type(lpBaseAddress, '=L', unpackedValue)
Writes a DWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write.
Writes a DWORD to the memory of the process.
[ "Writes", "a", "DWORD", "to", "the", "memory", "of", "the", "process", "." ]
def poke_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=L', unpackedValue)
[ "def", "poke_dword", "(", "self", ",", "lpBaseAddress", ",", "unpackedValue", ")", ":", "return", "self", ".", "__poke_c_type", "(", "lpBaseAddress", ",", "'=L'", ",", "unpackedValue", ")" ]
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/process.py#L2280-L2298
yiifans/lulucms2
d5c92b952ad6e8520e5d9a9514406689dafb9a77
statics/admin/dandelion/plugins/elfinder/connectors/python/elFinder.py
python
connector.__remove
(self, target)
Internal remove procedure
Internal remove procedure
[ "Internal", "remove", "procedure" ]
def __remove(self, target): """Internal remove procedure""" if not self.__isAllowed(target, 'rm'): self.__errorData(target, 'Access denied') if not os.path.isdir(target): try: os.unlink(target) return True except: self.__errorData(target, 'Remove failed') return False else: for i in os.listdir(target): if self.__isAccepted(i): self.__remove(os.path.join(target, i)) try: os.rmdir(target) return True except: self.__errorData(target, 'Remove failed') return False pass
[ "def", "__remove", "(", "self", ",", "target", ")", ":", "if", "not", "self", ".", "__isAllowed", "(", "target", ",", "'rm'", ")", ":", "self", ".", "__errorData", "(", "target", ",", "'Access denied'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "target", ")", ":", "try", ":", "os", ".", "unlink", "(", "target", ")", "return", "True", "except", ":", "self", ".", "__errorData", "(", "target", ",", "'Remove failed'", ")", "return", "False", "else", ":", "for", "i", "in", "os", ".", "listdir", "(", "target", ")", ":", "if", "self", ".", "__isAccepted", "(", "i", ")", ":", "self", ".", "__remove", "(", "os", ".", "path", ".", "join", "(", "target", ",", "i", ")", ")", "try", ":", "os", ".", "rmdir", "(", "target", ")", "return", "True", "except", ":", "self", ".", "__errorData", "(", "target", ",", "'Remove failed'", ")", "return", "False", "pass" ]
https://github.com/yiifans/lulucms2/blob/d5c92b952ad6e8520e5d9a9514406689dafb9a77/statics/admin/dandelion/plugins/elfinder/connectors/python/elFinder.py#L855-L878
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/kernel32.py
python
ThreadHandle.__init__
(self, aHandle = None, bOwnership = True, dwAccess = THREAD_ALL_ACCESS)
@type aHandle: int @param aHandle: Win32 handle value. @type bOwnership: bool @param bOwnership: C{True} if we own the handle and we need to close it. C{False} if someone else will be calling L{CloseHandle}. @type dwAccess: int @param dwAccess: Current access flags to this handle. This is the same value passed to L{OpenThread}. Can only be C{None} if C{aHandle} is also C{None}. Defaults to L{THREAD_ALL_ACCESS}.
@type aHandle: int @param aHandle: Win32 handle value.
[ "@type", "aHandle", ":", "int", "@param", "aHandle", ":", "Win32", "handle", "value", "." ]
def __init__(self, aHandle = None, bOwnership = True, dwAccess = THREAD_ALL_ACCESS): """ @type aHandle: int @param aHandle: Win32 handle value. @type bOwnership: bool @param bOwnership: C{True} if we own the handle and we need to close it. C{False} if someone else will be calling L{CloseHandle}. @type dwAccess: int @param dwAccess: Current access flags to this handle. This is the same value passed to L{OpenThread}. Can only be C{None} if C{aHandle} is also C{None}. Defaults to L{THREAD_ALL_ACCESS}. """ super(ThreadHandle, self).__init__(aHandle, bOwnership) self.dwAccess = dwAccess if aHandle is not None and dwAccess is None: msg = "Missing access flags for thread handle: %x" % aHandle raise TypeError(msg)
[ "def", "__init__", "(", "self", ",", "aHandle", "=", "None", ",", "bOwnership", "=", "True", ",", "dwAccess", "=", "THREAD_ALL_ACCESS", ")", ":", "super", "(", "ThreadHandle", ",", "self", ")", ".", "__init__", "(", "aHandle", ",", "bOwnership", ")", "self", ".", "dwAccess", "=", "dwAccess", "if", "aHandle", "is", "not", "None", "and", "dwAccess", "is", "None", ":", "msg", "=", "\"Missing access flags for thread handle: %x\"", "%", "aHandle", "raise", "TypeError", "(", "msg", ")" ]
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/win32/kernel32.py#L874-L895
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
odoo/fields.py
python
Field.update_db
(self, model, columns)
return not column
Update the database schema to implement this field. :param model: an instance of the field's model :param columns: a dict mapping column names to their configuration in database :return: ``True`` if the field must be recomputed on existing rows
Update the database schema to implement this field.
[ "Update", "the", "database", "schema", "to", "implement", "this", "field", "." ]
def update_db(self, model, columns): """ Update the database schema to implement this field. :param model: an instance of the field's model :param columns: a dict mapping column names to their configuration in database :return: ``True`` if the field must be recomputed on existing rows """ if not self.column_type: return column = columns.get(self.name) # create/update the column, not null constraint; the index will be # managed by registry.check_indexes() self.update_db_column(model, column) self.update_db_notnull(model, column) # optimization for computing simple related fields like 'foo_id.bar' if ( not column and self.related and self.related.count('.') == 1 and self.related_field.store and not self.related_field.compute and not (self.related_field.type == 'binary' and self.related_field.attachment) and self.related_field.type not in ('one2many', 'many2many') ): join_field = model._fields[self.related.split('.')[0]] if ( join_field.type == 'many2one' and join_field.store and not join_field.compute ): model.pool.post_init(self.update_db_related, model) # discard the "classical" computation return False return not column
[ "def", "update_db", "(", "self", ",", "model", ",", "columns", ")", ":", "if", "not", "self", ".", "column_type", ":", "return", "column", "=", "columns", ".", "get", "(", "self", ".", "name", ")", "# create/update the column, not null constraint; the index will be", "# managed by registry.check_indexes()", "self", ".", "update_db_column", "(", "model", ",", "column", ")", "self", ".", "update_db_notnull", "(", "model", ",", "column", ")", "# optimization for computing simple related fields like 'foo_id.bar'", "if", "(", "not", "column", "and", "self", ".", "related", "and", "self", ".", "related", ".", "count", "(", "'.'", ")", "==", "1", "and", "self", ".", "related_field", ".", "store", "and", "not", "self", ".", "related_field", ".", "compute", "and", "not", "(", "self", ".", "related_field", ".", "type", "==", "'binary'", "and", "self", ".", "related_field", ".", "attachment", ")", "and", "self", ".", "related_field", ".", "type", "not", "in", "(", "'one2many'", ",", "'many2many'", ")", ")", ":", "join_field", "=", "model", ".", "_fields", "[", "self", ".", "related", ".", "split", "(", "'.'", ")", "[", "0", "]", "]", "if", "(", "join_field", ".", "type", "==", "'many2one'", "and", "join_field", ".", "store", "and", "not", "join_field", ".", "compute", ")", ":", "model", ".", "pool", ".", "post_init", "(", "self", ".", "update_db_related", ",", "model", ")", "# discard the \"classical\" computation", "return", "False", "return", "not", "column" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/fields.py#L881-L915
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/v8/tools/jsmin.py
python
JavaScriptMinifier.LookAtIdentifier
(self, m)
Records identifiers or keywords that we see in use. (So we can avoid renaming variables to these strings.) Args: m: The match object returned by re.search. Returns: Nothing.
Records identifiers or keywords that we see in use.
[ "Records", "identifiers", "or", "keywords", "that", "we", "see", "in", "use", "." ]
def LookAtIdentifier(self, m): """Records identifiers or keywords that we see in use. (So we can avoid renaming variables to these strings.) Args: m: The match object returned by re.search. Returns: Nothing. """ identifier = m.group(1) self.seen_identifiers[identifier] = True
[ "def", "LookAtIdentifier", "(", "self", ",", "m", ")", ":", "identifier", "=", "m", ".", "group", "(", "1", ")", "self", ".", "seen_identifiers", "[", "identifier", "]", "=", "True" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/v8/tools/jsmin.py#L63-L74
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/mailcap.py
python
parseline
(line)
return key, fields
Parse one entry in a mailcap file and return a dictionary. The viewing command is stored as the value with the key "view", and the rest of the fields produce key-value pairs in the dict.
Parse one entry in a mailcap file and return a dictionary.
[ "Parse", "one", "entry", "in", "a", "mailcap", "file", "and", "return", "a", "dictionary", "." ]
def parseline(line): """Parse one entry in a mailcap file and return a dictionary. The viewing command is stored as the value with the key "view", and the rest of the fields produce key-value pairs in the dict. """ fields = [] i, n = 0, len(line) while i < n: field, i = parsefield(line, i, n) fields.append(field) i = i+1 # Skip semicolon if len(fields) < 2: return None, None key, view, rest = fields[0], fields[1], fields[2:] fields = {'view': view} for field in rest: i = field.find('=') if i < 0: fkey = field fvalue = "" else: fkey = field[:i].strip() fvalue = field[i+1:].strip() if fkey in fields: # Ignore it pass else: fields[fkey] = fvalue return key, fields
[ "def", "parseline", "(", "line", ")", ":", "fields", "=", "[", "]", "i", ",", "n", "=", "0", ",", "len", "(", "line", ")", "while", "i", "<", "n", ":", "field", ",", "i", "=", "parsefield", "(", "line", ",", "i", ",", "n", ")", "fields", ".", "append", "(", "field", ")", "i", "=", "i", "+", "1", "# Skip semicolon", "if", "len", "(", "fields", ")", "<", "2", ":", "return", "None", ",", "None", "key", ",", "view", ",", "rest", "=", "fields", "[", "0", "]", ",", "fields", "[", "1", "]", ",", "fields", "[", "2", ":", "]", "fields", "=", "{", "'view'", ":", "view", "}", "for", "field", "in", "rest", ":", "i", "=", "field", ".", "find", "(", "'='", ")", "if", "i", "<", "0", ":", "fkey", "=", "field", "fvalue", "=", "\"\"", "else", ":", "fkey", "=", "field", "[", ":", "i", "]", ".", "strip", "(", ")", "fvalue", "=", "field", "[", "i", "+", "1", ":", "]", ".", "strip", "(", ")", "if", "fkey", "in", "fields", ":", "# Ignore it", "pass", "else", ":", "fields", "[", "fkey", "]", "=", "fvalue", "return", "key", ",", "fields" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/mailcap.py#L91-L120
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/logging/__init__.py
python
Handler.close
(self)
Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.
Tidy up any resources used by the handler.
[ "Tidy", "up", "any", "resources", "used", "by", "the", "handler", "." ]
def close(self): """ Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. """ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock()
[ "def", "close", "(", "self", ")", ":", "#get the module data lock, as we're updating a shared structure.", "_acquireLock", "(", ")", "try", ":", "#unlikely to raise an exception, but you never know...", "if", "self", ".", "_name", "and", "self", ".", "_name", "in", "_handlers", ":", "del", "_handlers", "[", "self", ".", "_name", "]", "finally", ":", "_releaseLock", "(", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/logging/__init__.py#L764-L779
jasonsanjose/brackets-sass
88b351f2ebc3aaa514494eac368d197f63438caf
node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.AddOrGetFileInRootGroup
(self, path)
return group.AddOrGetFileByPath(path, hierarchical)
Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics. If an existing PBXFileReference for path exists, it will be returned. Otherwise, one will be created and returned.
Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics.
[ "Returns", "a", "PBXFileReference", "corresponding", "to", "path", "in", "the", "correct", "group", "according", "to", "RootGroupForPath", "s", "heuristics", "." ]
def AddOrGetFileInRootGroup(self, path): """Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics. If an existing PBXFileReference for path exists, it will be returned. Otherwise, one will be created and returned. """ (group, hierarchical) = self.RootGroupForPath(path) return group.AddOrGetFileByPath(path, hierarchical)
[ "def", "AddOrGetFileInRootGroup", "(", "self", ",", "path", ")", ":", "(", "group", ",", "hierarchical", ")", "=", "self", ".", "RootGroupForPath", "(", "path", ")", "return", "group", ".", "AddOrGetFileByPath", "(", "path", ",", "hierarchical", ")" ]
https://github.com/jasonsanjose/brackets-sass/blob/88b351f2ebc3aaa514494eac368d197f63438caf/node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/xcodeproj_file.py#L2610-L2619
klaasnicolaas/Smarthome-homeassistant-config
610bd35f4e8cdb4a1f41165b0ccb9251c76f5644
custom_components/hacs/repositories/integration.py
python
HacsIntegration.reload_custom_components
(self)
Reload custom_components (and config flows)in HA.
Reload custom_components (and config flows)in HA.
[ "Reload", "custom_components", "(", "and", "config", "flows", ")", "in", "HA", "." ]
async def reload_custom_components(self): """Reload custom_components (and config flows)in HA.""" self.logger.info("Reloading custom_component cache") del self.hacs.hass.data["custom_components"] await async_get_custom_components(self.hacs.hass) self.logger.info("Custom_component cache reloaded")
[ "async", "def", "reload_custom_components", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Reloading custom_component cache\"", ")", "del", "self", ".", "hacs", ".", "hass", ".", "data", "[", "\"custom_components\"", "]", "await", "async_get_custom_components", "(", "self", ".", "hacs", ".", "hass", ")", "self", ".", "logger", ".", "info", "(", "\"Custom_component cache reloaded\"", ")" ]
https://github.com/klaasnicolaas/Smarthome-homeassistant-config/blob/610bd35f4e8cdb4a1f41165b0ccb9251c76f5644/custom_components/hacs/repositories/integration.py#L89-L94
wotermelon/toJump
3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f
lib/mac/systrace/catapult/third_party/pyserial/serial/rfc2217.py
python
RFC2217Serial.fromURL
(self, url)
return (host, port)
extract host and port from an URL string
extract host and port from an URL string
[ "extract", "host", "and", "port", "from", "an", "URL", "string" ]
def fromURL(self, url): """extract host and port from an URL string""" if url.lower().startswith("rfc2217://"): url = url[10:] try: # is there a "path" (our options)? if '/' in url: # cut away options url, options = url.split('/', 1) # process options now, directly altering self for option in options.split('/'): if '=' in option: option, value = option.split('=', 1) else: value = None if option == 'logging': logging.basicConfig() # XXX is that good to call it here? self.logger = logging.getLogger('pySerial.rfc2217') self.logger.setLevel(LOGGER_LEVELS[value]) self.logger.debug('enabled logging') elif option == 'ign_set_control': self._ignore_set_control_answer = True elif option == 'poll_modem': self._poll_modem_state = True elif option == 'timeout': self._network_timeout = float(value) else: raise ValueError('unknown option: %r' % (option,)) # get host and port host, port = url.split(':', 1) # may raise ValueError because of unpacking port = int(port) # and this if it's not a number if not 0 <= port < 65536: raise ValueError("port not in range 0...65535") except ValueError, e: raise SerialException('expected a string in the form "[rfc2217://]<host>:<port>[/option[/option...]]": %s' % e) return (host, port)
[ "def", "fromURL", "(", "self", ",", "url", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "\"rfc2217://\"", ")", ":", "url", "=", "url", "[", "10", ":", "]", "try", ":", "# is there a \"path\" (our options)?", "if", "'/'", "in", "url", ":", "# cut away options", "url", ",", "options", "=", "url", ".", "split", "(", "'/'", ",", "1", ")", "# process options now, directly altering self", "for", "option", "in", "options", ".", "split", "(", "'/'", ")", ":", "if", "'='", "in", "option", ":", "option", ",", "value", "=", "option", ".", "split", "(", "'='", ",", "1", ")", "else", ":", "value", "=", "None", "if", "option", "==", "'logging'", ":", "logging", ".", "basicConfig", "(", ")", "# XXX is that good to call it here?", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "'pySerial.rfc2217'", ")", "self", ".", "logger", ".", "setLevel", "(", "LOGGER_LEVELS", "[", "value", "]", ")", "self", ".", "logger", ".", "debug", "(", "'enabled logging'", ")", "elif", "option", "==", "'ign_set_control'", ":", "self", ".", "_ignore_set_control_answer", "=", "True", "elif", "option", "==", "'poll_modem'", ":", "self", ".", "_poll_modem_state", "=", "True", "elif", "option", "==", "'timeout'", ":", "self", ".", "_network_timeout", "=", "float", "(", "value", ")", "else", ":", "raise", "ValueError", "(", "'unknown option: %r'", "%", "(", "option", ",", ")", ")", "# get host and port", "host", ",", "port", "=", "url", ".", "split", "(", "':'", ",", "1", ")", "# may raise ValueError because of unpacking", "port", "=", "int", "(", "port", ")", "# and this if it's not a number", "if", "not", "0", "<=", "port", "<", "65536", ":", "raise", "ValueError", "(", "\"port not in range 0...65535\"", ")", "except", "ValueError", ",", "e", ":", "raise", "SerialException", "(", "'expected a string in the form \"[rfc2217://]<host>:<port>[/option[/option...]]\": %s'", "%", "e", ")", "return", "(", "host", ",", "port", ")" ]
https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/third_party/pyserial/serial/rfc2217.py#L526-L559
Opentrons/opentrons
466e0567065d8773a81c25cd1b5c7998e00adf2c
api/docs/v1/api_cache/pipette.py
python
Pipette.blow_out
(self, location=None)
Force any remaining liquid to dispense, by moving this pipette's plunger to the calibrated `blow_out` position Notes ----- If no `location` is passed, the pipette will blow_out from it's current position. Parameters ---------- location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`) The :any:`Placeable` (:any:`Well`) to perform the blow_out. Can also be a tuple with first item :any:`Placeable`, second item relative :any:`Vector` Returns ------- This instance of :class:`Pipette`. Examples -------- >>> from opentrons import instruments, robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP >>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP >>> p300.aspirate(50).dispense().blow_out() # doctest: +SKIP
Force any remaining liquid to dispense, by moving this pipette's plunger to the calibrated `blow_out` position
[ "Force", "any", "remaining", "liquid", "to", "dispense", "by", "moving", "this", "pipette", "s", "plunger", "to", "the", "calibrated", "blow_out", "position" ]
def blow_out(self, location=None): """ Force any remaining liquid to dispense, by moving this pipette's plunger to the calibrated `blow_out` position Notes ----- If no `location` is passed, the pipette will blow_out from it's current position. Parameters ---------- location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`) The :any:`Placeable` (:any:`Well`) to perform the blow_out. Can also be a tuple with first item :any:`Placeable`, second item relative :any:`Vector` Returns ------- This instance of :class:`Pipette`. Examples -------- >>> from opentrons import instruments, robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP >>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP >>> p300.aspirate(50).dispense().blow_out() # doctest: +SKIP """
[ "def", "blow_out", "(", "self", ",", "location", "=", "None", ")", ":" ]
https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/docs/v1/api_cache/pipette.py#L318-L347
ernw/Windows-Insight
e04bf8554c61671c4ffbcb453138308bccbe1497
files/wintel_etwmonitor/tiv/graphs/writesPerMinuteGraph.py
python
WritesPerMinuteGraph.get_graph_data
(self)
return GraphData(WPM_NAME, WPM_TYPE,values, labels, WPM_LABEL, WPM_TITLE, WPM_FILENAME + JS_EXTENSION, WPM_DISPLAY_LEGEND, WPM_GRAPH_WITH_TIME)
Return the GraphData object related to the data of this graph
Return the GraphData object related to the data of this graph
[ "Return", "the", "GraphData", "object", "related", "to", "the", "data", "of", "this", "graph" ]
def get_graph_data(self): """ Return the GraphData object related to the data of this graph """ list_format = list(self.writes_per_minute.items()) labels = [elem[0].strftime(WPM_DATE_FORMAT) for elem in list_format] values = [elem[1] for elem in list_format] return GraphData(WPM_NAME, WPM_TYPE,values, labels, WPM_LABEL, WPM_TITLE, WPM_FILENAME + JS_EXTENSION, WPM_DISPLAY_LEGEND, WPM_GRAPH_WITH_TIME)
[ "def", "get_graph_data", "(", "self", ")", ":", "list_format", "=", "list", "(", "self", ".", "writes_per_minute", ".", "items", "(", ")", ")", "labels", "=", "[", "elem", "[", "0", "]", ".", "strftime", "(", "WPM_DATE_FORMAT", ")", "for", "elem", "in", "list_format", "]", "values", "=", "[", "elem", "[", "1", "]", "for", "elem", "in", "list_format", "]", "return", "GraphData", "(", "WPM_NAME", ",", "WPM_TYPE", ",", "values", ",", "labels", ",", "WPM_LABEL", ",", "WPM_TITLE", ",", "WPM_FILENAME", "+", "JS_EXTENSION", ",", "WPM_DISPLAY_LEGEND", ",", "WPM_GRAPH_WITH_TIME", ")" ]
https://github.com/ernw/Windows-Insight/blob/e04bf8554c61671c4ffbcb453138308bccbe1497/files/wintel_etwmonitor/tiv/graphs/writesPerMinuteGraph.py#L54-L64
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
bt5/erp5_safeimage/ExtensionTemplateItem/portal_components/extension.erp5.ERP5ZoomifyImage.py
python
ZoomifyZopeProcessor.saveTile
(self, image, scaleNumber, column, row)
return
save the cropped region
save the cropped region
[ "save", "the", "cropped", "region" ]
def saveTile(self, image, scaleNumber, column, row): """ save the cropped region """ w,h = image.size if w != 0 and h != 0: tileFileName = self.getTileFileName(scaleNumber, column, row) tileContainerName = self.getAssignedTileContainerName( tileFileName=tileFileName) tileImageData = StringIO() image.save(tileImageData, 'JPEG', quality=self.qualitySetting) tileImageData.seek(0) if hasattr(self._v_saveFolderObject, tileContainerName): tileFolder = getattr(self._v_saveFolderObject, tileContainerName) # if an image of this name already exists, delete and replace it. if hasattr(tileFolder, tileFileName): tileFolder._delObject(tileFileName) # finally, save the image data as a Zope Image object tileFolder._setObject(tileFileName, Image(tileFileName, '', '', 'image/jpeg', '')) tileFolder._getOb(tileFileName).manage_upload(tileImageData) self._v_transactionCount += 1 if self._v_transactionCount % 10 == 0: transaction.savepoint() return
[ "def", "saveTile", "(", "self", ",", "image", ",", "scaleNumber", ",", "column", ",", "row", ")", ":", "w", ",", "h", "=", "image", ".", "size", "if", "w", "!=", "0", "and", "h", "!=", "0", ":", "tileFileName", "=", "self", ".", "getTileFileName", "(", "scaleNumber", ",", "column", ",", "row", ")", "tileContainerName", "=", "self", ".", "getAssignedTileContainerName", "(", "tileFileName", "=", "tileFileName", ")", "tileImageData", "=", "StringIO", "(", ")", "image", ".", "save", "(", "tileImageData", ",", "'JPEG'", ",", "quality", "=", "self", ".", "qualitySetting", ")", "tileImageData", ".", "seek", "(", "0", ")", "if", "hasattr", "(", "self", ".", "_v_saveFolderObject", ",", "tileContainerName", ")", ":", "tileFolder", "=", "getattr", "(", "self", ".", "_v_saveFolderObject", ",", "tileContainerName", ")", "# if an image of this name already exists, delete and replace it.", "if", "hasattr", "(", "tileFolder", ",", "tileFileName", ")", ":", "tileFolder", ".", "_delObject", "(", "tileFileName", ")", "# finally, save the image data as a Zope Image object", "tileFolder", ".", "_setObject", "(", "tileFileName", ",", "Image", "(", "tileFileName", ",", "''", ",", "''", ",", "'image/jpeg'", ",", "''", ")", ")", "tileFolder", ".", "_getOb", "(", "tileFileName", ")", ".", "manage_upload", "(", "tileImageData", ")", "self", ".", "_v_transactionCount", "+=", "1", "if", "self", ".", "_v_transactionCount", "%", "10", "==", "0", ":", "transaction", ".", "savepoint", "(", ")", "return" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_safeimage/ExtensionTemplateItem/portal_components/extension.erp5.ERP5ZoomifyImage.py#L402-L425
googleglass/mirror-quickstart-python
e34077bae91657170c305702471f5c249eb1b686
lib/oauth2client/client.py
python
Credentials.refresh
(self, http)
Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request.
Forces a refresh of the access_token.
[ "Forces", "a", "refresh", "of", "the", "access_token", "." ]
def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ _abstract()
[ "def", "refresh", "(", "self", ",", "http", ")", ":", "_abstract", "(", ")" ]
https://github.com/googleglass/mirror-quickstart-python/blob/e34077bae91657170c305702471f5c249eb1b686/lib/oauth2client/client.py#L147-L154
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
tools/gyp/tools/pretty_gyp.py
python
mask_comments
(input)
return [search_re.sub(comment_replace, line) for line in input]
Mask the quoted strings so we skip braces inside quoted strings.
Mask the quoted strings so we skip braces inside quoted strings.
[ "Mask", "the", "quoted", "strings", "so", "we", "skip", "braces", "inside", "quoted", "strings", "." ]
def mask_comments(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input]
[ "def", "mask_comments", "(", "input", ")", ":", "search_re", "=", "re", ".", "compile", "(", "r'(.*?)(#)(.*)'", ")", "return", "[", "search_re", ".", "sub", "(", "comment_replace", ",", "line", ")", "for", "line", "in", "input", "]" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/tools/pretty_gyp.py#L28-L31
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
tools/gyp/pylib/gyp/input.py
python
CheckedEval
(file_contents)
return CheckNode(c3[0], [])
Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is.
Return the eval of a gyp file.
[ "Return", "the", "eval", "of", "a", "gyp", "file", "." ]
def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() assert c1[0] is None assert isinstance(c1[1], Stmt) c2 = c1[1].getChildren() assert isinstance(c2[0], Discard) c3 = c2[0].getChildren() assert len(c3) == 1 return CheckNode(c3[0], [])
[ "def", "CheckedEval", "(", "file_contents", ")", ":", "ast", "=", "compiler", ".", "parse", "(", "file_contents", ")", "assert", "isinstance", "(", "ast", ",", "Module", ")", "c1", "=", "ast", ".", "getChildren", "(", ")", "assert", "c1", "[", "0", "]", "is", "None", "assert", "isinstance", "(", "c1", "[", "1", "]", ",", "Stmt", ")", "c2", "=", "c1", "[", "1", "]", ".", "getChildren", "(", ")", "assert", "isinstance", "(", "c2", "[", "0", "]", ",", "Discard", ")", "c3", "=", "c2", "[", "0", "]", ".", "getChildren", "(", ")", "assert", "len", "(", "c3", ")", "==", "1", "return", "CheckNode", "(", "c3", "[", "0", "]", ",", "[", "]", ")" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/tools/gyp/pylib/gyp/input.py#L177-L195
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/wrapped_for_pydev/ctypes/macholib/dyld.py
python
ensure_utf8
(s)
return s
Not all of PyObjC and Python understand unicode paths very well yet
Not all of PyObjC and Python understand unicode paths very well yet
[ "Not", "all", "of", "PyObjC", "and", "Python", "understand", "unicode", "paths", "very", "well", "yet" ]
def ensure_utf8(s): """Not all of PyObjC and Python understand unicode paths very well yet""" if isinstance(s, unicode): return s.encode('utf8') return s
[ "def", "ensure_utf8", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", ".", "encode", "(", "'utf8'", ")", "return", "s" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/wrapped_for_pydev/ctypes/macholib/dyld.py#L32-L36
GeoNode/geonode
326d70153ad79e1ed831d46a0e3b239d422757a8
geonode/utils.py
python
rename_shp_columnnames
(inLayer, fieldnames)
Rename columns in a layer to those specified in the given mapping
Rename columns in a layer to those specified in the given mapping
[ "Rename", "columns", "in", "a", "layer", "to", "those", "specified", "in", "the", "given", "mapping" ]
def rename_shp_columnnames(inLayer, fieldnames): """ Rename columns in a layer to those specified in the given mapping """ inLayerDefn = inLayer.GetLayerDefn() for i in range(inLayerDefn.GetFieldCount()): srcFieldDefn = inLayerDefn.GetFieldDefn(i) dstFieldName = fieldnames.get(srcFieldDefn.GetName()) if dstFieldName is not None: dstFieldDefn = clone_shp_field_defn(srcFieldDefn, dstFieldName) inLayer.AlterFieldDefn(i, dstFieldDefn, ogr.ALTER_NAME_FLAG)
[ "def", "rename_shp_columnnames", "(", "inLayer", ",", "fieldnames", ")", ":", "inLayerDefn", "=", "inLayer", ".", "GetLayerDefn", "(", ")", "for", "i", "in", "range", "(", "inLayerDefn", ".", "GetFieldCount", "(", ")", ")", ":", "srcFieldDefn", "=", "inLayerDefn", ".", "GetFieldDefn", "(", "i", ")", "dstFieldName", "=", "fieldnames", ".", "get", "(", "srcFieldDefn", ".", "GetName", "(", ")", ")", "if", "dstFieldName", "is", "not", "None", ":", "dstFieldDefn", "=", "clone_shp_field_defn", "(", "srcFieldDefn", ",", "dstFieldName", ")", "inLayer", ".", "AlterFieldDefn", "(", "i", ",", "dstFieldDefn", ",", "ogr", ".", "ALTER_NAME_FLAG", ")" ]
https://github.com/GeoNode/geonode/blob/326d70153ad79e1ed831d46a0e3b239d422757a8/geonode/utils.py#L845-L857
prometheus-ar/vot.ar
72d8fa1ea08fe417b64340b98dff68df8364afdf
msa/modulos/mantenimiento/controlador.py
python
Controlador.get_pir_mode
(self, display=False)
return modo_actual
Devuelve el modo del PIR.
Devuelve el modo del PIR.
[ "Devuelve", "el", "modo", "del", "PIR", "." ]
def get_pir_mode(self, display=False): """Devuelve el modo del PIR.""" try: modo_actual = self.pir_mode except: if USAR_PIR and self.rampa.tiene_conexion: self.pir_mode = self.rampa.get_pir_mode() modo_actual = self.pir_mode else: modo_actual = None if display: self.send_command("mostrar_modo_pir", {'pir_activado': modo_actual}) return modo_actual
[ "def", "get_pir_mode", "(", "self", ",", "display", "=", "False", ")", ":", "try", ":", "modo_actual", "=", "self", ".", "pir_mode", "except", ":", "if", "USAR_PIR", "and", "self", ".", "rampa", ".", "tiene_conexion", ":", "self", ".", "pir_mode", "=", "self", ".", "rampa", ".", "get_pir_mode", "(", ")", "modo_actual", "=", "self", ".", "pir_mode", "else", ":", "modo_actual", "=", "None", "if", "display", ":", "self", ".", "send_command", "(", "\"mostrar_modo_pir\"", ",", "{", "'pir_activado'", ":", "modo_actual", "}", ")", "return", "modo_actual" ]
https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/modulos/mantenimiento/controlador.py#L397-L410
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/decimal.py
python
Context._raise_error
(self, condition, explanation = None, *args)
Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag.
Handles an error
[ "Handles", "an", "error" ]
def _raise_error(self, condition, explanation = None, *args): """Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) if error in self._ignored_flags: # Don't touch the flag return error().handle(self, *args) self.flags[error] = 1 if not self.traps[error]: # The errors define how to handle themselves. return condition().handle(self, *args) # Errors should only be risked on copies of the context # self._ignored_flags = [] raise error(explanation)
[ "def", "_raise_error", "(", "self", ",", "condition", ",", "explanation", "=", "None", ",", "*", "args", ")", ":", "error", "=", "_condition_map", ".", "get", "(", "condition", ",", "condition", ")", "if", "error", "in", "self", ".", "_ignored_flags", ":", "# Don't touch the flag", "return", "error", "(", ")", ".", "handle", "(", "self", ",", "*", "args", ")", "self", ".", "flags", "[", "error", "]", "=", "1", "if", "not", "self", ".", "traps", "[", "error", "]", ":", "# The errors define how to handle themselves.", "return", "condition", "(", ")", ".", "handle", "(", "self", ",", "*", "args", ")", "# Errors should only be risked on copies of the context", "# self._ignored_flags = []", "raise", "error", "(", "explanation", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/decimal.py#L3824-L3844
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/mailbox.py
python
Babyl.get_message
(self, key)
return msg
Return a Message representation or raise a KeyError.
Return a Message representation or raise a KeyError.
[ "Return", "a", "Message", "representation", "or", "raise", "a", "KeyError", "." ]
def get_message(self, key): """Return a Message representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) self._file.readline() # Skip '1,' line specifying labels. original_headers = StringIO.StringIO() while True: line = self._file.readline() if line == '*** EOOH ***' + os.linesep or line == '': break original_headers.write(line.replace(os.linesep, '\n')) visible_headers = StringIO.StringIO() while True: line = self._file.readline() if line == os.linesep or line == '': break visible_headers.write(line.replace(os.linesep, '\n')) body = self._file.read(stop - self._file.tell()).replace(os.linesep, '\n') msg = BabylMessage(original_headers.getvalue() + body) msg.set_visible(visible_headers.getvalue()) if key in self._labels: msg.set_labels(self._labels[key]) return msg
[ "def", "get_message", "(", "self", ",", "key", ")", ":", "start", ",", "stop", "=", "self", ".", "_lookup", "(", "key", ")", "self", ".", "_file", ".", "seek", "(", "start", ")", "self", ".", "_file", ".", "readline", "(", ")", "# Skip '1,' line specifying labels.", "original_headers", "=", "StringIO", ".", "StringIO", "(", ")", "while", "True", ":", "line", "=", "self", ".", "_file", ".", "readline", "(", ")", "if", "line", "==", "'*** EOOH ***'", "+", "os", ".", "linesep", "or", "line", "==", "''", ":", "break", "original_headers", ".", "write", "(", "line", ".", "replace", "(", "os", ".", "linesep", ",", "'\\n'", ")", ")", "visible_headers", "=", "StringIO", ".", "StringIO", "(", ")", "while", "True", ":", "line", "=", "self", ".", "_file", ".", "readline", "(", ")", "if", "line", "==", "os", ".", "linesep", "or", "line", "==", "''", ":", "break", "visible_headers", ".", "write", "(", "line", ".", "replace", "(", "os", ".", "linesep", ",", "'\\n'", ")", ")", "body", "=", "self", ".", "_file", ".", "read", "(", "stop", "-", "self", ".", "_file", ".", "tell", "(", ")", ")", ".", "replace", "(", "os", ".", "linesep", ",", "'\\n'", ")", "msg", "=", "BabylMessage", "(", "original_headers", ".", "getvalue", "(", ")", "+", "body", ")", "msg", ".", "set_visible", "(", "visible_headers", ".", "getvalue", "(", ")", ")", "if", "key", "in", "self", ".", "_labels", ":", "msg", ".", "set_labels", "(", "self", ".", "_labels", "[", "key", "]", ")", "return", "msg" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/mailbox.py#L1198-L1221
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/spidershim/spidermonkey/python/mozbuild/mozbuild/controller/building.py
python
BuildMonitor._get_finder_cpu_usage
(self)
return None
Obtain the CPU usage of the Finder app on OS X. This is used to detect high CPU usage.
Obtain the CPU usage of the Finder app on OS X.
[ "Obtain", "the", "CPU", "usage", "of", "the", "Finder", "app", "on", "OS", "X", "." ]
def _get_finder_cpu_usage(self): """Obtain the CPU usage of the Finder app on OS X. This is used to detect high CPU usage. """ if not sys.platform.startswith('darwin'): return None if not psutil: return None for proc in psutil.process_iter(): if proc.name != 'Finder': continue if proc.username != getpass.getuser(): continue # Try to isolate system finder as opposed to other "Finder" # processes. if not proc.exe.endswith('CoreServices/Finder.app/Contents/MacOS/Finder'): continue return proc.get_cpu_times() return None
[ "def", "_get_finder_cpu_usage", "(", "self", ")", ":", "if", "not", "sys", ".", "platform", ".", "startswith", "(", "'darwin'", ")", ":", "return", "None", "if", "not", "psutil", ":", "return", "None", "for", "proc", "in", "psutil", ".", "process_iter", "(", ")", ":", "if", "proc", ".", "name", "!=", "'Finder'", ":", "continue", "if", "proc", ".", "username", "!=", "getpass", ".", "getuser", "(", ")", ":", "continue", "# Try to isolate system finder as opposed to other \"Finder\"", "# processes.", "if", "not", "proc", ".", "exe", ".", "endswith", "(", "'CoreServices/Finder.app/Contents/MacOS/Finder'", ")", ":", "continue", "return", "proc", ".", "get_cpu_times", "(", ")", "return", "None" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/spidershim/spidermonkey/python/mozbuild/mozbuild/controller/building.py#L288-L313
FOSSEE/online_test
88866259d77c01c50c274fed700289144ccabec5
yaksh/views.py
python
monitor
(request, quiz_id=None, course_id=None, attempt_number=1)
return my_render_to_response(request, 'yaksh/monitor.html', context)
Monitor the progress of the papers taken so far.
Monitor the progress of the papers taken so far.
[ "Monitor", "the", "progress", "of", "the", "papers", "taken", "so", "far", "." ]
def monitor(request, quiz_id=None, course_id=None, attempt_number=1): """Monitor the progress of the papers taken so far.""" user = request.user if not is_moderator(user): raise Http404('You are not allowed to view this page!') course = get_object_or_404(Course, id=course_id) if not course.is_creator(user) and not course.is_teacher(user): raise Http404('This course does not belong to you') quiz = get_object_or_404(Quiz, id=quiz_id) q_paper = QuestionPaper.objects.filter(quiz__is_trial=False, quiz_id=quiz_id).distinct().last() attempt_numbers = AnswerPaper.objects.get_attempt_numbers( q_paper.id, course.id ) questions_count = 0 questions_attempted = {} completed_papers = 0 inprogress_papers = 0 papers = AnswerPaper.objects.filter( question_paper_id=q_paper.id, attempt_number=attempt_number, course_id=course_id ).order_by('user__first_name') papers = papers.filter(attempt_number=attempt_number) if not papers.exists(): messages.warning(request, "No AnswerPapers found") else: questions_count = q_paper.get_questions_count() questions_attempted = AnswerPaper.objects.get_questions_attempted( papers.values_list("id", flat=True) ) completed_papers = papers.filter(status="completed").count() inprogress_papers = papers.filter(status="inprogress").count() context = { "papers": papers, "quiz": quiz, "inprogress_papers": inprogress_papers, "attempt_numbers": attempt_numbers, "course": course, "total_papers": papers.count(), "completed_papers": completed_papers, "questions_attempted": questions_attempted, "questions_count": questions_count } return my_render_to_response(request, 'yaksh/monitor.html', context)
[ "def", "monitor", "(", "request", ",", "quiz_id", "=", "None", ",", "course_id", "=", "None", ",", "attempt_number", "=", "1", ")", ":", "user", "=", "request", ".", "user", "if", "not", "is_moderator", "(", "user", ")", ":", "raise", "Http404", "(", "'You are not allowed to view this page!'", ")", "course", "=", "get_object_or_404", "(", "Course", ",", "id", "=", "course_id", ")", "if", "not", "course", ".", "is_creator", "(", "user", ")", "and", "not", "course", ".", "is_teacher", "(", "user", ")", ":", "raise", "Http404", "(", "'This course does not belong to you'", ")", "quiz", "=", "get_object_or_404", "(", "Quiz", ",", "id", "=", "quiz_id", ")", "q_paper", "=", "QuestionPaper", ".", "objects", ".", "filter", "(", "quiz__is_trial", "=", "False", ",", "quiz_id", "=", "quiz_id", ")", ".", "distinct", "(", ")", ".", "last", "(", ")", "attempt_numbers", "=", "AnswerPaper", ".", "objects", ".", "get_attempt_numbers", "(", "q_paper", ".", "id", ",", "course", ".", "id", ")", "questions_count", "=", "0", "questions_attempted", "=", "{", "}", "completed_papers", "=", "0", "inprogress_papers", "=", "0", "papers", "=", "AnswerPaper", ".", "objects", ".", "filter", "(", "question_paper_id", "=", "q_paper", ".", "id", ",", "attempt_number", "=", "attempt_number", ",", "course_id", "=", "course_id", ")", ".", "order_by", "(", "'user__first_name'", ")", "papers", "=", "papers", ".", "filter", "(", "attempt_number", "=", "attempt_number", ")", "if", "not", "papers", ".", "exists", "(", ")", ":", "messages", ".", "warning", "(", "request", ",", "\"No AnswerPapers found\"", ")", "else", ":", "questions_count", "=", "q_paper", ".", "get_questions_count", "(", ")", "questions_attempted", "=", "AnswerPaper", ".", "objects", ".", "get_questions_attempted", "(", "papers", ".", "values_list", "(", "\"id\"", ",", "flat", "=", "True", ")", ")", "completed_papers", "=", "papers", ".", "filter", "(", "status", "=", "\"completed\"", ")", ".", "count", "(", ")", "inprogress_papers", "=", "papers", ".", "filter", "(", "status", "=", "\"inprogress\"", ")", ".", "count", "(", ")", "context", "=", "{", "\"papers\"", ":", "papers", ",", "\"quiz\"", ":", "quiz", ",", "\"inprogress_papers\"", ":", "inprogress_papers", ",", "\"attempt_numbers\"", ":", "attempt_numbers", ",", "\"course\"", ":", "course", ",", "\"total_papers\"", ":", "papers", ".", "count", "(", ")", ",", "\"completed_papers\"", ":", "completed_papers", ",", "\"questions_attempted\"", ":", "questions_attempted", ",", "\"questions_count\"", ":", "questions_count", "}", "return", "my_render_to_response", "(", "request", ",", "'yaksh/monitor.html'", ",", "context", ")" ]
https://github.com/FOSSEE/online_test/blob/88866259d77c01c50c274fed700289144ccabec5/yaksh/views.py#L1385-L1429
harvard-lil/perma
c54ff21b3eee931f5094a7654fdddc9ad90fc29c
perma_web/perma/models.py
python
Folder.display_level
(self)
return self.level + (1 if self.organization_id else 0)
Get hierarchical level for this folder. If this is a shared folder, level should be one higher because it is displayed below user's root folder.
Get hierarchical level for this folder. If this is a shared folder, level should be one higher because it is displayed below user's root folder.
[ "Get", "hierarchical", "level", "for", "this", "folder", ".", "If", "this", "is", "a", "shared", "folder", "level", "should", "be", "one", "higher", "because", "it", "is", "displayed", "below", "user", "s", "root", "folder", "." ]
def display_level(self): """ Get hierarchical level for this folder. If this is a shared folder, level should be one higher because it is displayed below user's root folder. """ return self.level + (1 if self.organization_id else 0)
[ "def", "display_level", "(", "self", ")", ":", "return", "self", ".", "level", "+", "(", "1", "if", "self", ".", "organization_id", "else", "0", ")" ]
https://github.com/harvard-lil/perma/blob/c54ff21b3eee931f5094a7654fdddc9ad90fc29c/perma_web/perma/models.py#L1256-L1261
robplatek/Massive-Coupon---Open-source-groupon-clone
1d725356eeb41c6328605cef6e8779ab472db2b4
debug_toolbar/utils/sqlparse/tokens.py
python
string_to_tokentype
(s)
return node
Convert a string into a token type:: >>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number >>> string_to_token('') Token Tokens that are already tokens are returned unchanged: >>> string_to_token(String) Token.Literal.String
Convert a string into a token type::
[ "Convert", "a", "string", "into", "a", "token", "type", "::" ]
def string_to_tokentype(s): """ Convert a string into a token type:: >>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number >>> string_to_token('') Token Tokens that are already tokens are returned unchanged: >>> string_to_token(String) Token.Literal.String """ if isinstance(s, _TokenType): return s if not s: return Token node = Token for item in s.split('.'): node = getattr(node, item) return node
[ "def", "string_to_tokentype", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "_TokenType", ")", ":", "return", "s", "if", "not", "s", ":", "return", "Token", "node", "=", "Token", "for", "item", "in", "s", ".", "split", "(", "'.'", ")", ":", "node", "=", "getattr", "(", "node", ",", "item", ")", "return", "node" ]
https://github.com/robplatek/Massive-Coupon---Open-source-groupon-clone/blob/1d725356eeb41c6328605cef6e8779ab472db2b4/debug_toolbar/utils/sqlparse/tokens.py#L107-L130
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/trace.py
python
CoverageResults.write_results
(self, show_missing=True, summary=False, coverdir=None)
@param coverdir
[]
def write_results(self, show_missing=True, summary=False, coverdir=None): """ @param coverdir """ if self.calledfuncs: print print "functions called:" calls = self.calledfuncs.keys() calls.sort() for filename, modulename, funcname in calls: print ("filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname)) if self.callers: print print "calling relationships:" calls = self.callers.keys() calls.sort() lastfile = lastcfile = "" for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: if pfile != lastfile: print print "***", pfile, "***" lastfile = pfile lastcfile = "" if cfile != pfile and lastcfile != cfile: print " -->", cfile lastcfile = cfile print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc) # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for filename, lineno in self.counts.keys(): lines_hit = per_file[filename] = per_file.get(filename, {}) lines_hit[lineno] = self.counts[(filename, lineno)] # accumulate summary info, if needed sums = {} for filename, count in per_file.iteritems(): # skip some "files" we don't care about... if filename == "<string>": continue if filename.startswith("<doctest "): continue if filename.endswith((".pyc", ".pyo")): filename = filename[:-1] if coverdir is None: dir = os.path.dirname(os.path.abspath(filename)) modulename = modname(filename) else: dir = coverdir if not os.path.exists(dir): os.makedirs(dir) modulename = fullmodname(filename) # If desired, get a list of the line numbers which represent # executable content (returned as a dict for better lookup speed) if show_missing: lnotab = find_executable_linenos(filename) else: lnotab = {} source = linecache.getlines(filename) coverpath = os.path.join(dir, modulename + ".cover") n_hits, n_lines = self.write_results_file(coverpath, source, lnotab, count) if summary and n_lines: percent = 100 * n_hits // n_lines sums[modulename] = n_lines, percent, modulename, filename if summary and sums: mods = sums.keys() mods.sort() print "lines cov% module (path)" for m in mods: n_lines, percent, modulename, filename = sums[m] print "%5d %3d%% %s (%s)" % sums[m] if self.outfile: # try and store counts and module info into self.outfile try: pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) except IOError, err: print >> sys.stderr, "Can't save counts files because %s" % err
[ "def", "write_results", "(", "self", ",", "show_missing", "=", "True", ",", "summary", "=", "False", ",", "coverdir", "=", "None", ")", ":", "if", "self", ".", "calledfuncs", ":", "print", "print", "\"functions called:\"", "calls", "=", "self", ".", "calledfuncs", ".", "keys", "(", ")", "calls", ".", "sort", "(", ")", "for", "filename", ",", "modulename", ",", "funcname", "in", "calls", ":", "print", "(", "\"filename: %s, modulename: %s, funcname: %s\"", "%", "(", "filename", ",", "modulename", ",", "funcname", ")", ")", "if", "self", ".", "callers", ":", "print", "print", "\"calling relationships:\"", "calls", "=", "self", ".", "callers", ".", "keys", "(", ")", "calls", ".", "sort", "(", ")", "lastfile", "=", "lastcfile", "=", "\"\"", "for", "(", "(", "pfile", ",", "pmod", ",", "pfunc", ")", ",", "(", "cfile", ",", "cmod", ",", "cfunc", ")", ")", "in", "calls", ":", "if", "pfile", "!=", "lastfile", ":", "print", "print", "\"***\"", ",", "pfile", ",", "\"***\"", "lastfile", "=", "pfile", "lastcfile", "=", "\"\"", "if", "cfile", "!=", "pfile", "and", "lastcfile", "!=", "cfile", ":", "print", "\" -->\"", ",", "cfile", "lastcfile", "=", "cfile", "print", "\" %s.%s -> %s.%s\"", "%", "(", "pmod", ",", "pfunc", ",", "cmod", ",", "cfunc", ")", "# turn the counts data (\"(filename, lineno) = count\") into something", "# accessible on a per-file basis", "per_file", "=", "{", "}", "for", "filename", ",", "lineno", "in", "self", ".", "counts", ".", "keys", "(", ")", ":", "lines_hit", "=", "per_file", "[", "filename", "]", "=", "per_file", ".", "get", "(", "filename", ",", "{", "}", ")", "lines_hit", "[", "lineno", "]", "=", "self", ".", "counts", "[", "(", "filename", ",", "lineno", ")", "]", "# accumulate summary info, if needed", "sums", "=", "{", "}", "for", "filename", ",", "count", "in", "per_file", ".", "iteritems", "(", ")", ":", "# skip some \"files\" we don't care about...", "if", "filename", "==", "\"<string>\"", ":", "continue", "if", "filename", ".", "startswith", "(", "\"<doctest \"", ")", ":", "continue", "if", "filename", ".", "endswith", "(", "(", "\".pyc\"", ",", "\".pyo\"", ")", ")", ":", "filename", "=", "filename", "[", ":", "-", "1", "]", "if", "coverdir", "is", "None", ":", "dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "modulename", "=", "modname", "(", "filename", ")", "else", ":", "dir", "=", "coverdir", "if", "not", "os", ".", "path", ".", "exists", "(", "dir", ")", ":", "os", ".", "makedirs", "(", "dir", ")", "modulename", "=", "fullmodname", "(", "filename", ")", "# If desired, get a list of the line numbers which represent", "# executable content (returned as a dict for better lookup speed)", "if", "show_missing", ":", "lnotab", "=", "find_executable_linenos", "(", "filename", ")", "else", ":", "lnotab", "=", "{", "}", "source", "=", "linecache", ".", "getlines", "(", "filename", ")", "coverpath", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "modulename", "+", "\".cover\"", ")", "n_hits", ",", "n_lines", "=", "self", ".", "write_results_file", "(", "coverpath", ",", "source", ",", "lnotab", ",", "count", ")", "if", "summary", "and", "n_lines", ":", "percent", "=", "100", "*", "n_hits", "//", "n_lines", "sums", "[", "modulename", "]", "=", "n_lines", ",", "percent", ",", "modulename", ",", "filename", "if", "summary", "and", "sums", ":", "mods", "=", "sums", ".", "keys", "(", ")", "mods", ".", "sort", "(", ")", "print", "\"lines cov% module (path)\"", "for", "m", "in", "mods", ":", "n_lines", ",", "percent", ",", "modulename", ",", "filename", "=", "sums", "[", "m", "]", "print", "\"%5d %3d%% %s (%s)\"", "%", "sums", "[", "m", "]", "if", "self", ".", "outfile", ":", "# try and store counts and module info into self.outfile", "try", ":", "pickle", ".", "dump", "(", "(", "self", ".", "counts", ",", "self", ".", "calledfuncs", ",", "self", ".", "callers", ")", ",", "open", "(", "self", ".", "outfile", ",", "'wb'", ")", ",", "1", ")", "except", "IOError", ",", "err", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Can't save counts files because %s\"", "%", "err" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/trace.py#L266-L355
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
bt5/erp5_budget/DocumentTemplateItem/portal_components/document.erp5.NodeBudgetVariation.py
python
NodeBudgetVariation.initializeBudget
(self, budget)
Initialize a budget.
Initialize a budget.
[ "Initialize", "a", "budget", "." ]
def initializeBudget(self, budget): """Initialize a budget. """ budget_variation_base_category_list =\ list(budget.getVariationBaseCategoryList() or []) budget_membership_criterion_base_category_list =\ list(budget.getMembershipCriterionBaseCategoryList() or []) base_category = self.getProperty('variation_base_category') if base_category: if base_category not in budget_variation_base_category_list: budget_variation_base_category_list.append(base_category) if base_category not in budget_membership_criterion_base_category_list: budget_membership_criterion_base_category_list.append(base_category) budget.setVariationBaseCategoryList( budget_variation_base_category_list) budget.setMembershipCriterionBaseCategoryList( budget_membership_criterion_base_category_list)
[ "def", "initializeBudget", "(", "self", ",", "budget", ")", ":", "budget_variation_base_category_list", "=", "list", "(", "budget", ".", "getVariationBaseCategoryList", "(", ")", "or", "[", "]", ")", "budget_membership_criterion_base_category_list", "=", "list", "(", "budget", ".", "getMembershipCriterionBaseCategoryList", "(", ")", "or", "[", "]", ")", "base_category", "=", "self", ".", "getProperty", "(", "'variation_base_category'", ")", "if", "base_category", ":", "if", "base_category", "not", "in", "budget_variation_base_category_list", ":", "budget_variation_base_category_list", ".", "append", "(", "base_category", ")", "if", "base_category", "not", "in", "budget_membership_criterion_base_category_list", ":", "budget_membership_criterion_base_category_list", ".", "append", "(", "base_category", ")", "budget", ".", "setVariationBaseCategoryList", "(", "budget_variation_base_category_list", ")", "budget", ".", "setMembershipCriterionBaseCategoryList", "(", "budget_membership_criterion_base_category_list", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_budget/DocumentTemplateItem/portal_components/document.erp5.NodeBudgetVariation.py#L369-L385
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/client/tactic_client_lib/tactic_server_stub.py
python
TacticServerStub.set_config_definition
(self, search_type, element_name, config_xml="", login=None)
return self.server.set_config_definition(self.ticket, search_type, element_name, config_xml, login)
API Function: set_config_definition(search_type, element_name, config_xml="", login=None) Set the widget configuration definition for an element @param: search_type - search type that this config relates to element_name - name of the element @keyparam: config_xml - The configuration xml to be set login - A user's login name, if specifically choosing one @return: True on success, exception message on failure
API Function: set_config_definition(search_type, element_name, config_xml="", login=None) Set the widget configuration definition for an element
[ "API", "Function", ":", "set_config_definition", "(", "search_type", "element_name", "config_xml", "=", "login", "=", "None", ")", "Set", "the", "widget", "configuration", "definition", "for", "an", "element" ]
def set_config_definition(self, search_type, element_name, config_xml="", login=None): '''API Function: set_config_definition(search_type, element_name, config_xml="", login=None) Set the widget configuration definition for an element @param: search_type - search type that this config relates to element_name - name of the element @keyparam: config_xml - The configuration xml to be set login - A user's login name, if specifically choosing one @return: True on success, exception message on failure ''' return self.server.set_config_definition(self.ticket, search_type, element_name, config_xml, login)
[ "def", "set_config_definition", "(", "self", ",", "search_type", ",", "element_name", ",", "config_xml", "=", "\"\"", ",", "login", "=", "None", ")", ":", "return", "self", ".", "server", ".", "set_config_definition", "(", "self", ".", "ticket", ",", "search_type", ",", "element_name", ",", "config_xml", ",", "login", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/client/tactic_client_lib/tactic_server_stub.py#L3846-L3863
Blizzard/node-rdkafka
a6ddf07a3231e09d4d52a4f1437a5ff95fab56d9
cpplint.py
python
Error
(filename, linenum, category, confidence, message)
Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message.
Logs the fact we've found a lint error.
[ "Logs", "the", "fact", "we", "ve", "found", "a", "lint", "error", "." ]
def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence))
[ "def", "Error", "(", "filename", ",", "linenum", ",", "category", ",", "confidence", ",", "message", ")", ":", "if", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "_cpplint_state", ".", "IncrementErrorCount", "(", "category", ")", "if", "_cpplint_state", ".", "output_format", "==", "'vs7'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s(%s): %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "elif", "_cpplint_state", ".", "output_format", "==", "'eclipse'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: warning: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")" ]
https://github.com/Blizzard/node-rdkafka/blob/a6ddf07a3231e09d4d52a4f1437a5ff95fab56d9/cpplint.py#L1094-L1126
tobegit3hub/simple_tensorflow_serving
6aa1aad5f2cb68d195beddb5af2f249adbffa6bd
simple_tensorflow_serving/service_utils/request_util.py
python
get_image_channel_layout
(request_layout, support_signatures=None)
return layout
Try select a channel layout by requested layout and model signatures
Try select a channel layout by requested layout and model signatures
[ "Try", "select", "a", "channel", "layout", "by", "requested", "layout", "and", "model", "signatures" ]
def get_image_channel_layout(request_layout, support_signatures=None): """ Try select a channel layout by requested layout and model signatures """ layout = request_layout if support_signatures is not None: # get input tensor "image" for item in support_signatures["inputs"]: if item["name"] == "image": shape = item["shape"] if len(shape) == 4: channel_size = shape[-1] if channel_size == 1: layout = "L" elif channel_size == 3: layout = "RGB" elif channel_size == 4: layout = "RGBA" break return layout
[ "def", "get_image_channel_layout", "(", "request_layout", ",", "support_signatures", "=", "None", ")", ":", "layout", "=", "request_layout", "if", "support_signatures", "is", "not", "None", ":", "# get input tensor \"image\"", "for", "item", "in", "support_signatures", "[", "\"inputs\"", "]", ":", "if", "item", "[", "\"name\"", "]", "==", "\"image\"", ":", "shape", "=", "item", "[", "\"shape\"", "]", "if", "len", "(", "shape", ")", "==", "4", ":", "channel_size", "=", "shape", "[", "-", "1", "]", "if", "channel_size", "==", "1", ":", "layout", "=", "\"L\"", "elif", "channel_size", "==", "3", ":", "layout", "=", "\"RGB\"", "elif", "channel_size", "==", "4", ":", "layout", "=", "\"RGBA\"", "break", "return", "layout" ]
https://github.com/tobegit3hub/simple_tensorflow_serving/blob/6aa1aad5f2cb68d195beddb5af2f249adbffa6bd/simple_tensorflow_serving/service_utils/request_util.py#L18-L37
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetLdflags
(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir)
return ldflags, intermediate_manifest, manifest_files
Returns the flags that need to be added to link commands, and the manifest files.
Returns the flags that need to be added to link commands, and the manifest files.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", "link", "commands", "and", "the", "manifest", "files", "." ]
def GetLdflags(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir): """Returns the flags that need to be added to link commands, and the manifest files.""" config = self._TargetConfig(config) ldflags = [] ld = self._GetWrapper(self, self.msvs_settings[config], 'VCLinkerTool', append=ldflags) self._GetDefFileAsLdflags(ldflags, gyp_to_build_path) ld('GenerateDebugInformation', map={'true': '/DEBUG'}) ld('TargetMachine', map={'1': 'X86', '17': 'X64'}, prefix='/MACHINE:') ldflags.extend(self._GetAdditionalLibraryDirectories( 'VCLinkerTool', config, gyp_to_build_path)) ld('DelayLoadDLLs', prefix='/DELAYLOAD:') ld('TreatLinkerWarningAsErrors', prefix='/WX', map={'true': '', 'false': ':NO'}) out = self.GetOutputName(config, expand_special) if out: ldflags.append('/OUT:' + out) pdb = self.GetPDBName(config, expand_special, output_name + '.pdb') if pdb: ldflags.append('/PDB:' + pdb) pgd = self.GetPGDName(config, expand_special) if pgd: ldflags.append('/PGD:' + pgd) map_file = self.GetMapFileName(config, expand_special) ld('GenerateMapFile', map={'true': '/MAP:' + map_file if map_file else '/MAP'}) ld('MapExports', map={'true': '/MAPINFO:EXPORTS'}) ld('AdditionalOptions', prefix='') minimum_required_version = self._Setting( ('VCLinkerTool', 'MinimumRequiredVersion'), config, default='') if minimum_required_version: minimum_required_version = ',' + minimum_required_version ld('SubSystem', map={'1': 'CONSOLE%s' % minimum_required_version, '2': 'WINDOWS%s' % minimum_required_version}, prefix='/SUBSYSTEM:') ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE') ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL') ld('BaseAddress', prefix='/BASE:') ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED') ld('RandomizedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE') ld('DataExecutionPrevention', map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT') ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:') ld('ForceSymbolReferences', prefix='/INCLUDE:') ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:') ld('LinkTimeCodeGeneration', map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE', '4': ':PGUPDATE'}, prefix='/LTCG') ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:') ld('ResourceOnlyDLL', map={'true': '/NOENTRY'}) ld('EntryPointSymbol', prefix='/ENTRY:') ld('Profile', map={'true': '/PROFILE'}) ld('LargeAddressAware', map={'1': ':NO', '2': ''}, prefix='/LARGEADDRESSAWARE') # TODO(scottmg): This should sort of be somewhere else (not really a flag). ld('AdditionalDependencies', prefix='') # If the base address is not specifically controlled, DYNAMICBASE should # be on by default. base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED', ldflags) if not base_flags: ldflags.append('/DYNAMICBASE') # If the NXCOMPAT flag has not been specified, default to on. Despite the # documentation that says this only defaults to on when the subsystem is # Vista or greater (which applies to the linker), the IDE defaults it on # unless it's explicitly off. if not filter(lambda x: 'NXCOMPAT' in x, ldflags): ldflags.append('/NXCOMPAT') have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags) manifest_flags, intermediate_manifest, manifest_files = \ self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path, is_executable and not have_def_file, build_dir) ldflags.extend(manifest_flags) return ldflags, intermediate_manifest, manifest_files
[ "def", "GetLdflags", "(", "self", ",", "config", ",", "gyp_to_build_path", ",", "expand_special", ",", "manifest_base_name", ",", "output_name", ",", "is_executable", ",", "build_dir", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "ldflags", "=", "[", "]", "ld", "=", "self", ".", "_GetWrapper", "(", "self", ",", "self", ".", "msvs_settings", "[", "config", "]", ",", "'VCLinkerTool'", ",", "append", "=", "ldflags", ")", "self", ".", "_GetDefFileAsLdflags", "(", "ldflags", ",", "gyp_to_build_path", ")", "ld", "(", "'GenerateDebugInformation'", ",", "map", "=", "{", "'true'", ":", "'/DEBUG'", "}", ")", "ld", "(", "'TargetMachine'", ",", "map", "=", "{", "'1'", ":", "'X86'", ",", "'17'", ":", "'X64'", "}", ",", "prefix", "=", "'/MACHINE:'", ")", "ldflags", ".", "extend", "(", "self", ".", "_GetAdditionalLibraryDirectories", "(", "'VCLinkerTool'", ",", "config", ",", "gyp_to_build_path", ")", ")", "ld", "(", "'DelayLoadDLLs'", ",", "prefix", "=", "'/DELAYLOAD:'", ")", "ld", "(", "'TreatLinkerWarningAsErrors'", ",", "prefix", "=", "'/WX'", ",", "map", "=", "{", "'true'", ":", "''", ",", "'false'", ":", "':NO'", "}", ")", "out", "=", "self", ".", "GetOutputName", "(", "config", ",", "expand_special", ")", "if", "out", ":", "ldflags", ".", "append", "(", "'/OUT:'", "+", "out", ")", "pdb", "=", "self", ".", "GetPDBName", "(", "config", ",", "expand_special", ",", "output_name", "+", "'.pdb'", ")", "if", "pdb", ":", "ldflags", ".", "append", "(", "'/PDB:'", "+", "pdb", ")", "pgd", "=", "self", ".", "GetPGDName", "(", "config", ",", "expand_special", ")", "if", "pgd", ":", "ldflags", ".", "append", "(", "'/PGD:'", "+", "pgd", ")", "map_file", "=", "self", ".", "GetMapFileName", "(", "config", ",", "expand_special", ")", "ld", "(", "'GenerateMapFile'", ",", "map", "=", "{", "'true'", ":", "'/MAP:'", "+", "map_file", "if", "map_file", "else", "'/MAP'", "}", ")", "ld", "(", "'MapExports'", ",", "map", "=", "{", "'true'", ":", "'/MAPINFO:EXPORTS'", "}", ")", "ld", "(", "'AdditionalOptions'", ",", "prefix", "=", "''", ")", "minimum_required_version", "=", "self", ".", "_Setting", "(", "(", "'VCLinkerTool'", ",", "'MinimumRequiredVersion'", ")", ",", "config", ",", "default", "=", "''", ")", "if", "minimum_required_version", ":", "minimum_required_version", "=", "','", "+", "minimum_required_version", "ld", "(", "'SubSystem'", ",", "map", "=", "{", "'1'", ":", "'CONSOLE%s'", "%", "minimum_required_version", ",", "'2'", ":", "'WINDOWS%s'", "%", "minimum_required_version", "}", ",", "prefix", "=", "'/SUBSYSTEM:'", ")", "ld", "(", "'TerminalServerAware'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/TSAWARE'", ")", "ld", "(", "'LinkIncremental'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/INCREMENTAL'", ")", "ld", "(", "'BaseAddress'", ",", "prefix", "=", "'/BASE:'", ")", "ld", "(", "'FixedBaseAddress'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/FIXED'", ")", "ld", "(", "'RandomizedBaseAddress'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/DYNAMICBASE'", ")", "ld", "(", "'DataExecutionPrevention'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/NXCOMPAT'", ")", "ld", "(", "'OptimizeReferences'", ",", "map", "=", "{", "'1'", ":", "'NOREF'", ",", "'2'", ":", "'REF'", "}", ",", "prefix", "=", "'/OPT:'", ")", "ld", "(", "'ForceSymbolReferences'", ",", "prefix", "=", "'/INCLUDE:'", ")", "ld", "(", "'EnableCOMDATFolding'", ",", "map", "=", "{", "'1'", ":", "'NOICF'", ",", "'2'", ":", "'ICF'", "}", ",", "prefix", "=", "'/OPT:'", ")", "ld", "(", "'LinkTimeCodeGeneration'", ",", "map", "=", "{", "'1'", ":", "''", ",", "'2'", ":", "':PGINSTRUMENT'", ",", "'3'", ":", "':PGOPTIMIZE'", ",", "'4'", ":", "':PGUPDATE'", "}", ",", "prefix", "=", "'/LTCG'", ")", "ld", "(", "'IgnoreDefaultLibraryNames'", ",", "prefix", "=", "'/NODEFAULTLIB:'", ")", "ld", "(", "'ResourceOnlyDLL'", ",", "map", "=", "{", "'true'", ":", "'/NOENTRY'", "}", ")", "ld", "(", "'EntryPointSymbol'", ",", "prefix", "=", "'/ENTRY:'", ")", "ld", "(", "'Profile'", ",", "map", "=", "{", "'true'", ":", "'/PROFILE'", "}", ")", "ld", "(", "'LargeAddressAware'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/LARGEADDRESSAWARE'", ")", "# TODO(scottmg): This should sort of be somewhere else (not really a flag).", "ld", "(", "'AdditionalDependencies'", ",", "prefix", "=", "''", ")", "# If the base address is not specifically controlled, DYNAMICBASE should", "# be on by default.", "base_flags", "=", "filter", "(", "lambda", "x", ":", "'DYNAMICBASE'", "in", "x", "or", "x", "==", "'/FIXED'", ",", "ldflags", ")", "if", "not", "base_flags", ":", "ldflags", ".", "append", "(", "'/DYNAMICBASE'", ")", "# If the NXCOMPAT flag has not been specified, default to on. Despite the", "# documentation that says this only defaults to on when the subsystem is", "# Vista or greater (which applies to the linker), the IDE defaults it on", "# unless it's explicitly off.", "if", "not", "filter", "(", "lambda", "x", ":", "'NXCOMPAT'", "in", "x", ",", "ldflags", ")", ":", "ldflags", ".", "append", "(", "'/NXCOMPAT'", ")", "have_def_file", "=", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "'/DEF:'", ")", ",", "ldflags", ")", "manifest_flags", ",", "intermediate_manifest", ",", "manifest_files", "=", "self", ".", "_GetLdManifestFlags", "(", "config", ",", "manifest_base_name", ",", "gyp_to_build_path", ",", "is_executable", "and", "not", "have_def_file", ",", "build_dir", ")", "ldflags", ".", "extend", "(", "manifest_flags", ")", "return", "ldflags", ",", "intermediate_manifest", ",", "manifest_files" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/tools/gyp/pylib/gyp/msvs_emulation.py#L461-L544
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
tools/gyp/pylib/gyp/generator/cmake.py
python
CMakeStringEscape
(a)
return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"')
Escapes the string 'a' for use inside a CMake string. This means escaping '\' otherwise it may be seen as modifying the next character '"' otherwise it will end the string ';' otherwise the string becomes a list The following do not need to be escaped '#' when the lexer is in string state, this does not start a comment The following are yet unknown '$' generator variables (like ${obj}) must not be escaped, but text $ should be escaped what is wanted is to know which $ come from generator variables
Escapes the string 'a' for use inside a CMake string.
[ "Escapes", "the", "string", "a", "for", "use", "inside", "a", "CMake", "string", "." ]
def CMakeStringEscape(a): """Escapes the string 'a' for use inside a CMake string. This means escaping '\' otherwise it may be seen as modifying the next character '"' otherwise it will end the string ';' otherwise the string becomes a list The following do not need to be escaped '#' when the lexer is in string state, this does not start a comment The following are yet unknown '$' generator variables (like ${obj}) must not be escaped, but text $ should be escaped what is wanted is to know which $ come from generator variables """ return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"')
[ "def", "CMakeStringEscape", "(", "a", ")", ":", "return", "a", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "';'", ",", "'\\\\;'", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/tools/gyp/pylib/gyp/generator/cmake.py#L121-L137
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/client/tactic_client_lib/tactic_server_stub.py
python
TacticServerStub.execute_js_script
(self, script_path, kwargs={})
return self.server.execute_js_script(self.ticket, script_path, kwargs)
API Function: execute_js_script(script_path, kwargs) Execute a js script defined in Script Editor @param: script_path - script path in Script Editor, e.g. test/eval_sobj @keyparam: kwargs - keyword arguments for this script @return: dictionary - returned data structure
API Function: execute_js_script(script_path, kwargs) Execute a js script defined in Script Editor
[ "API", "Function", ":", "execute_js_script", "(", "script_path", "kwargs", ")", "Execute", "a", "js", "script", "defined", "in", "Script", "Editor" ]
def execute_js_script(self, script_path, kwargs={}): '''API Function: execute_js_script(script_path, kwargs) Execute a js script defined in Script Editor @param: script_path - script path in Script Editor, e.g. test/eval_sobj @keyparam: kwargs - keyword arguments for this script @return: dictionary - returned data structure ''' return self.server.execute_js_script(self.ticket, script_path, kwargs)
[ "def", "execute_js_script", "(", "self", ",", "script_path", ",", "kwargs", "=", "{", "}", ")", ":", "return", "self", ".", "server", ".", "execute_js_script", "(", "self", ".", "ticket", ",", "script_path", ",", "kwargs", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/client/tactic_client_lib/tactic_server_stub.py#L3735-L3747
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
deps/v8/tools/foozzie/v8_suppressions.py
python
diff_output
(output1, output2, allowed, ignore1, ignore2)
return None, source
Returns a tuple (difference, source). The difference is None if there's no difference, otherwise a string with a readable diff. The source is the last source output within the test case, or None if no such output existed.
Returns a tuple (difference, source).
[ "Returns", "a", "tuple", "(", "difference", "source", ")", "." ]
def diff_output(output1, output2, allowed, ignore1, ignore2): """Returns a tuple (difference, source). The difference is None if there's no difference, otherwise a string with a readable diff. The source is the last source output within the test case, or None if no such output existed. """ def useful_line(ignore): def fun(line): return all(not e.match(line) for e in ignore) return fun lines1 = filter(useful_line(ignore1), output1) lines2 = filter(useful_line(ignore2), output2) # This keeps track where we are in the original source file of the fuzz # test case. source = None for ((line1, lookahead1), (line2, lookahead2)) in itertools.izip_longest( line_pairs(lines1), line_pairs(lines2), fillvalue=(None, None)): # Only one of the two iterators should run out. assert not (line1 is None and line2 is None) # One iterator ends earlier. if line1 is None: return '+ %s' % short_line_output(line2), source if line2 is None: return '- %s' % short_line_output(line1), source # If lines are equal, no further checks are necessary. if line1 == line2: # Instrumented original-source-file output must be equal in both # versions. It only makes sense to update it here when both lines # are equal. if line1.startswith(ORIGINAL_SOURCE_PREFIX): source = line1[len(ORIGINAL_SOURCE_PREFIX):] continue # Look ahead. If next line is a caret, ignore this line. if caret_match(lookahead1, lookahead2): continue # Check if a regexp allows these lines to be different. if ignore_by_regexp(line1, line2, allowed): continue # Lines are different. return ( '- %s\n+ %s' % (short_line_output(line1), short_line_output(line2)), source, ) # No difference found. return None, source
[ "def", "diff_output", "(", "output1", ",", "output2", ",", "allowed", ",", "ignore1", ",", "ignore2", ")", ":", "def", "useful_line", "(", "ignore", ")", ":", "def", "fun", "(", "line", ")", ":", "return", "all", "(", "not", "e", ".", "match", "(", "line", ")", "for", "e", "in", "ignore", ")", "return", "fun", "lines1", "=", "filter", "(", "useful_line", "(", "ignore1", ")", ",", "output1", ")", "lines2", "=", "filter", "(", "useful_line", "(", "ignore2", ")", ",", "output2", ")", "# This keeps track where we are in the original source file of the fuzz", "# test case.", "source", "=", "None", "for", "(", "(", "line1", ",", "lookahead1", ")", ",", "(", "line2", ",", "lookahead2", ")", ")", "in", "itertools", ".", "izip_longest", "(", "line_pairs", "(", "lines1", ")", ",", "line_pairs", "(", "lines2", ")", ",", "fillvalue", "=", "(", "None", ",", "None", ")", ")", ":", "# Only one of the two iterators should run out.", "assert", "not", "(", "line1", "is", "None", "and", "line2", "is", "None", ")", "# One iterator ends earlier.", "if", "line1", "is", "None", ":", "return", "'+ %s'", "%", "short_line_output", "(", "line2", ")", ",", "source", "if", "line2", "is", "None", ":", "return", "'- %s'", "%", "short_line_output", "(", "line1", ")", ",", "source", "# If lines are equal, no further checks are necessary.", "if", "line1", "==", "line2", ":", "# Instrumented original-source-file output must be equal in both", "# versions. It only makes sense to update it here when both lines", "# are equal.", "if", "line1", ".", "startswith", "(", "ORIGINAL_SOURCE_PREFIX", ")", ":", "source", "=", "line1", "[", "len", "(", "ORIGINAL_SOURCE_PREFIX", ")", ":", "]", "continue", "# Look ahead. If next line is a caret, ignore this line.", "if", "caret_match", "(", "lookahead1", ",", "lookahead2", ")", ":", "continue", "# Check if a regexp allows these lines to be different.", "if", "ignore_by_regexp", "(", "line1", ",", "line2", ",", "allowed", ")", ":", "continue", "# Lines are different.", "return", "(", "'- %s\\n+ %s'", "%", "(", "short_line_output", "(", "line1", ")", ",", "short_line_output", "(", "line2", ")", ")", ",", "source", ",", ")", "# No difference found.", "return", "None", ",", "source" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/v8/tools/foozzie/v8_suppressions.py#L180-L237
datahuborg/datahub
f066b472c2b66cc3b868bbe433aed2d4557aea32
src/account/views.py
python
get_user_details
(request)
return render(request, "username_form.html", context)
DataHub account registration form for social accounts. Gives new users a chance to choose a DataHub username and set their email address. Called by the Python Social Auth pipeline's get_user_details step. For more details, look for pipeline.py and the SOCIAL_AUTH_PIPELINE section of settings.py.
DataHub account registration form for social accounts.
[ "DataHub", "account", "registration", "form", "for", "social", "accounts", "." ]
def get_user_details(request): """ DataHub account registration form for social accounts. Gives new users a chance to choose a DataHub username and set their email address. Called by the Python Social Auth pipeline's get_user_details step. For more details, look for pipeline.py and the SOCIAL_AUTH_PIPELINE section of settings.py. """ # Prepopulate the form with values provided by the identity provider. backend = request.session['partial_pipeline']['backend'] try: details = request.session['partial_pipeline']['kwargs']['details'] except KeyError: details = None try: # Include details about the social login being used, # e.g. "Authenticated as Facebook user Foo Bar." social = provider_details(backend=backend) social['username'] = details['username'] except KeyError: social = None if request.method == 'POST': form = UsernameForm(request.POST) if form.is_valid(): # Because of FIELDS_STORED_IN_SESSION, preferred_username will be # copied to the request dictionary when the pipeline resumes. d = { 'preferred_username': form.cleaned_data['username'].lower(), 'email': form.cleaned_data['email'].lower(), } request.session.update(d) # Once we have the password stashed in the session, we can # tell the pipeline to resume by using the "complete" endpoint return redirect('social:complete', backend=backend) else: form = UsernameForm(initial={'email': details['email']}) context = RequestContext(request, { 'form': form, 'details': details, 'social': social}) return render(request, "username_form.html", context)
[ "def", "get_user_details", "(", "request", ")", ":", "# Prepopulate the form with values provided by the identity provider.", "backend", "=", "request", ".", "session", "[", "'partial_pipeline'", "]", "[", "'backend'", "]", "try", ":", "details", "=", "request", ".", "session", "[", "'partial_pipeline'", "]", "[", "'kwargs'", "]", "[", "'details'", "]", "except", "KeyError", ":", "details", "=", "None", "try", ":", "# Include details about the social login being used,", "# e.g. \"Authenticated as Facebook user Foo Bar.\"", "social", "=", "provider_details", "(", "backend", "=", "backend", ")", "social", "[", "'username'", "]", "=", "details", "[", "'username'", "]", "except", "KeyError", ":", "social", "=", "None", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "UsernameForm", "(", "request", ".", "POST", ")", "if", "form", ".", "is_valid", "(", ")", ":", "# Because of FIELDS_STORED_IN_SESSION, preferred_username will be", "# copied to the request dictionary when the pipeline resumes.", "d", "=", "{", "'preferred_username'", ":", "form", ".", "cleaned_data", "[", "'username'", "]", ".", "lower", "(", ")", ",", "'email'", ":", "form", ".", "cleaned_data", "[", "'email'", "]", ".", "lower", "(", ")", ",", "}", "request", ".", "session", ".", "update", "(", "d", ")", "# Once we have the password stashed in the session, we can", "# tell the pipeline to resume by using the \"complete\" endpoint", "return", "redirect", "(", "'social:complete'", ",", "backend", "=", "backend", ")", "else", ":", "form", "=", "UsernameForm", "(", "initial", "=", "{", "'email'", ":", "details", "[", "'email'", "]", "}", ")", "context", "=", "RequestContext", "(", "request", ",", "{", "'form'", ":", "form", ",", "'details'", ":", "details", ",", "'social'", ":", "social", "}", ")", "return", "render", "(", "request", ",", "\"username_form.html\"", ",", "context", ")" ]
https://github.com/datahuborg/datahub/blob/f066b472c2b66cc3b868bbe433aed2d4557aea32/src/account/views.py#L126-L173
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/uuid.py
python
_windll_getnode
()
Get the hardware address on Windows using ctypes.
Get the hardware address on Windows using ctypes.
[ "Get", "the", "hardware", "address", "on", "Windows", "using", "ctypes", "." ]
def _windll_getnode(): """Get the hardware address on Windows using ctypes.""" _buffer = ctypes.create_string_buffer(16) if _UuidCreate(_buffer) == 0: return UUID(bytes=_buffer.raw).node
[ "def", "_windll_getnode", "(", ")", ":", "_buffer", "=", "ctypes", ".", "create_string_buffer", "(", "16", ")", "if", "_UuidCreate", "(", "_buffer", ")", "==", "0", ":", "return", "UUID", "(", "bytes", "=", "_buffer", ".", "raw", ")", ".", "node" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/uuid.py#L448-L452
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
XCObject.Name
(self)
Return the name corresponding to an object. Not all objects necessarily need to be nameable, and not all that do have a "name" property. Override as needed.
Return the name corresponding to an object.
[ "Return", "the", "name", "corresponding", "to", "an", "object", "." ]
def Name(self): """Return the name corresponding to an object. Not all objects necessarily need to be nameable, and not all that do have a "name" property. Override as needed. """ # If the schema indicates that "name" is required, try to access the # property even if it doesn't exist. This will result in a KeyError # being raised for the property that should be present, which seems more # appropriate than NotImplementedError in this case. if 'name' in self._properties or \ ('name' in self._schema and self._schema['name'][3]): return self._properties['name'] raise NotImplementedError(self.__class__.__name__ + ' must implement Name')
[ "def", "Name", "(", "self", ")", ":", "# If the schema indicates that \"name\" is required, try to access the", "# property even if it doesn't exist. This will result in a KeyError", "# being raised for the property that should be present, which seems more", "# appropriate than NotImplementedError in this case.", "if", "'name'", "in", "self", ".", "_properties", "or", "(", "'name'", "in", "self", ".", "_schema", "and", "self", ".", "_schema", "[", "'name'", "]", "[", "3", "]", ")", ":", "return", "self", ".", "_properties", "[", "'name'", "]", "raise", "NotImplementedError", "(", "self", ".", "__class__", ".", "__name__", "+", "' must implement Name'", ")" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L354-L369
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_GetLibraryDirs
(config)
return library_dirs
Returns the list of directories to be used for library search paths. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths.
Returns the list of directories to be used for library search paths.
[ "Returns", "the", "list", "of", "directories", "to", "be", "used", "for", "library", "search", "paths", "." ]
def _GetLibraryDirs(config): """Returns the list of directories to be used for library search paths. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths. """ library_dirs = config.get('library_dirs', []) library_dirs = _FixPaths(library_dirs) return library_dirs
[ "def", "_GetLibraryDirs", "(", "config", ")", ":", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "library_dirs", "=", "_FixPaths", "(", "library_dirs", ")", "return", "library_dirs" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1227-L1239
SpiderOak/Encryptr
e18624e203cb35d9561de26707c4808de308cec4
resources/linux-build-helper.py
python
replace_str_in_file
(file_path, source_str, replace_str)
Replace all appearences of source_str for replace_str in the file from file_path.
Replace all appearences of source_str for replace_str in the file from file_path.
[ "Replace", "all", "appearences", "of", "source_str", "for", "replace_str", "in", "the", "file", "from", "file_path", "." ]
def replace_str_in_file(file_path, source_str, replace_str): """Replace all appearences of source_str for replace_str in the file from file_path. """ # In Python 2.X FileInput cannot be used as context manager f = fileinput.FileInput(file_path, inplace=True) for line in f: # replace the string on each line of the file # we use the trailing comma to avoid double line jumps, # because each line already contains a \n char print line.replace(source_str, replace_str), f.close()
[ "def", "replace_str_in_file", "(", "file_path", ",", "source_str", ",", "replace_str", ")", ":", "# In Python 2.X FileInput cannot be used as context manager", "f", "=", "fileinput", ".", "FileInput", "(", "file_path", ",", "inplace", "=", "True", ")", "for", "line", "in", "f", ":", "# replace the string on each line of the file", "# we use the trailing comma to avoid double line jumps,", "# because each line already contains a \\n char", "print", "line", ".", "replace", "(", "source_str", ",", "replace_str", ")", ",", "f", ".", "close", "(", ")" ]
https://github.com/SpiderOak/Encryptr/blob/e18624e203cb35d9561de26707c4808de308cec4/resources/linux-build-helper.py#L36-L47
nodejs/node
ac3c33c1646bf46104c15ae035982c06364da9b8
tools/cpplint.py
python
_SetOutputFormat
(output_format)
Sets the module's output format.
Sets the module's output format.
[ "Sets", "the", "module", "s", "output", "format", "." ]
def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format)
[ "def", "_SetOutputFormat", "(", "output_format", ")", ":", "_cpplint_state", ".", "SetOutputFormat", "(", "output_format", ")" ]
https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/cpplint.py#L1434-L1436
ElasticHQ/elasticsearch-HQ
8197e21d09b1312492dcb6998a2349d73b06efc6
elastichq/vendor/elasticsearch/helpers/__init__.py
python
scan
(client, query=None, scroll='5m', raise_on_error=True, preserve_order=False, size=1000, request_timeout=None, clear_scroll=True, scroll_kwargs=None, **kwargs)
Simple abstraction on top of the :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that yields all hits as returned by underlining scroll requests. By default scan does not return results in any pre-determined order. To have a standard order in the returned documents (either by score or explicit sort definition) when scrolling, use ``preserve_order=True``. This may be an expensive operation and will negate the performance benefits of using ``scan``. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg raise_on_error: raises an exception (``ScanError``) if an error is encountered (some shards fail to execute). By default we raise. :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will cause the scroll to paginate with preserving the order. Note that this can be an extremely expensive operation and can easily lead to unpredictable results, use with caution. :arg size: size (per shard) of the batch send at each iteration. :arg request_timeout: explicit timeout for each call to ``scan`` :arg clear_scroll: explicitly calls delete on the scroll id via the clear scroll API at the end of the method on completion or error, defaults to true. :arg scroll_kwargs: additional kwargs to be passed to :meth:`~elasticsearch.Elasticsearch.scroll` Any additional keyword arguments will be passed to the initial :meth:`~elasticsearch.Elasticsearch.search` call:: scan(es, query={"query": {"match": {"title": "python"}}}, index="orders-*", doc_type="books" )
Simple abstraction on top of the :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that yields all hits as returned by underlining scroll requests.
[ "Simple", "abstraction", "on", "top", "of", "the", ":", "meth", ":", "~elasticsearch", ".", "Elasticsearch", ".", "scroll", "api", "-", "a", "simple", "iterator", "that", "yields", "all", "hits", "as", "returned", "by", "underlining", "scroll", "requests", "." ]
def scan(client, query=None, scroll='5m', raise_on_error=True, preserve_order=False, size=1000, request_timeout=None, clear_scroll=True, scroll_kwargs=None, **kwargs): """ Simple abstraction on top of the :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that yields all hits as returned by underlining scroll requests. By default scan does not return results in any pre-determined order. To have a standard order in the returned documents (either by score or explicit sort definition) when scrolling, use ``preserve_order=True``. This may be an expensive operation and will negate the performance benefits of using ``scan``. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg raise_on_error: raises an exception (``ScanError``) if an error is encountered (some shards fail to execute). By default we raise. :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will cause the scroll to paginate with preserving the order. Note that this can be an extremely expensive operation and can easily lead to unpredictable results, use with caution. :arg size: size (per shard) of the batch send at each iteration. :arg request_timeout: explicit timeout for each call to ``scan`` :arg clear_scroll: explicitly calls delete on the scroll id via the clear scroll API at the end of the method on completion or error, defaults to true. :arg scroll_kwargs: additional kwargs to be passed to :meth:`~elasticsearch.Elasticsearch.scroll` Any additional keyword arguments will be passed to the initial :meth:`~elasticsearch.Elasticsearch.search` call:: scan(es, query={"query": {"match": {"title": "python"}}}, index="orders-*", doc_type="books" ) """ scroll_kwargs = scroll_kwargs or {} if not preserve_order: query = query.copy() if query else {} query["sort"] = "_doc" # initial search resp = client.search(body=query, scroll=scroll, size=size, request_timeout=request_timeout, **kwargs) scroll_id = resp.get('_scroll_id') if scroll_id is None: return try: first_run = True while True: # if we didn't set search_type to scan initial search contains data if first_run: first_run = False else: resp = client.scroll(scroll_id, scroll=scroll, request_timeout=request_timeout, **scroll_kwargs) for hit in resp['hits']['hits']: yield hit # check if we have any errrors if resp["_shards"]["successful"] < resp["_shards"]["total"]: logger.warning( 'Scroll request has only succeeded on %d shards out of %d.', resp['_shards']['successful'], resp['_shards']['total'] ) if raise_on_error: raise ScanError( scroll_id, 'Scroll request has only succeeded on %d shards out of %d.' % (resp['_shards']['successful'], resp['_shards']['total']) ) scroll_id = resp.get('_scroll_id') # end of scroll if scroll_id is None or not resp['hits']['hits']: break finally: if scroll_id and clear_scroll: client.clear_scroll(body={'scroll_id': [scroll_id]}, ignore=(404, ))
[ "def", "scan", "(", "client", ",", "query", "=", "None", ",", "scroll", "=", "'5m'", ",", "raise_on_error", "=", "True", ",", "preserve_order", "=", "False", ",", "size", "=", "1000", ",", "request_timeout", "=", "None", ",", "clear_scroll", "=", "True", ",", "scroll_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "scroll_kwargs", "=", "scroll_kwargs", "or", "{", "}", "if", "not", "preserve_order", ":", "query", "=", "query", ".", "copy", "(", ")", "if", "query", "else", "{", "}", "query", "[", "\"sort\"", "]", "=", "\"_doc\"", "# initial search", "resp", "=", "client", ".", "search", "(", "body", "=", "query", ",", "scroll", "=", "scroll", ",", "size", "=", "size", ",", "request_timeout", "=", "request_timeout", ",", "*", "*", "kwargs", ")", "scroll_id", "=", "resp", ".", "get", "(", "'_scroll_id'", ")", "if", "scroll_id", "is", "None", ":", "return", "try", ":", "first_run", "=", "True", "while", "True", ":", "# if we didn't set search_type to scan initial search contains data", "if", "first_run", ":", "first_run", "=", "False", "else", ":", "resp", "=", "client", ".", "scroll", "(", "scroll_id", ",", "scroll", "=", "scroll", ",", "request_timeout", "=", "request_timeout", ",", "*", "*", "scroll_kwargs", ")", "for", "hit", "in", "resp", "[", "'hits'", "]", "[", "'hits'", "]", ":", "yield", "hit", "# check if we have any errrors", "if", "resp", "[", "\"_shards\"", "]", "[", "\"successful\"", "]", "<", "resp", "[", "\"_shards\"", "]", "[", "\"total\"", "]", ":", "logger", ".", "warning", "(", "'Scroll request has only succeeded on %d shards out of %d.'", ",", "resp", "[", "'_shards'", "]", "[", "'successful'", "]", ",", "resp", "[", "'_shards'", "]", "[", "'total'", "]", ")", "if", "raise_on_error", ":", "raise", "ScanError", "(", "scroll_id", ",", "'Scroll request has only succeeded on %d shards out of %d.'", "%", "(", "resp", "[", "'_shards'", "]", "[", "'successful'", "]", ",", "resp", "[", "'_shards'", "]", "[", "'total'", "]", ")", ")", "scroll_id", "=", "resp", ".", "get", "(", "'_scroll_id'", ")", "# end of scroll", "if", "scroll_id", "is", "None", "or", "not", "resp", "[", "'hits'", "]", "[", "'hits'", "]", ":", "break", "finally", ":", "if", "scroll_id", "and", "clear_scroll", ":", "client", ".", "clear_scroll", "(", "body", "=", "{", "'scroll_id'", ":", "[", "scroll_id", "]", "}", ",", "ignore", "=", "(", "404", ",", ")", ")" ]
https://github.com/ElasticHQ/elasticsearch-HQ/blob/8197e21d09b1312492dcb6998a2349d73b06efc6/elastichq/vendor/elasticsearch/helpers/__init__.py#L315-L403