nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
mit-han-lab/data-efficient-gans
6858275f08f43a33026844c8c2ac4e703e8a07ba
DiffAugment-stylegan2-pytorch/dnnlib/util.py
python
call_func_by_name
(*args, func_name: str = None, **kwargs)
return func_obj(*args, **kwargs)
Finds the python object with the given name and calls it as a function.
Finds the python object with the given name and calls it as a function.
[ "Finds", "the", "python", "object", "with", "the", "given", "name", "and", "calls", "it", "as", "a", "function", "." ]
def call_func_by_name(*args, func_name: str = None, **kwargs) -> Any: """Finds the python object with the given name and calls it as a function.""" assert func_name is not None func_obj = get_obj_by_name(func_name) assert callable(func_obj) return func_obj(*args, **kwargs)
[ "def", "call_func_by_name", "(", "*", "args", ",", "func_name", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "assert", "func_name", "is", "not", "None", "func_obj", "=", "get_obj_by_name", "(", "func_name", ")", "assert", "cal...
https://github.com/mit-han-lab/data-efficient-gans/blob/6858275f08f43a33026844c8c2ac4e703e8a07ba/DiffAugment-stylegan2-pytorch/dnnlib/util.py#L279-L284
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/glfw.py
python
wait_events
()
Waits until events are pending and processes them. Wrapper for: void glfwWaitEvents(void);
Waits until events are pending and processes them.
[ "Waits", "until", "events", "are", "pending", "and", "processes", "them", "." ]
def wait_events(): ''' Waits until events are pending and processes them. Wrapper for: void glfwWaitEvents(void); ''' _glfw.glfwWaitEvents()
[ "def", "wait_events", "(", ")", ":", "_glfw", ".", "glfwWaitEvents", "(", ")" ]
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/glfw.py#L1215-L1222
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/oauth/models.py
python
Application.is_mutable_by
(self, user, local_site=None)
return self.is_accessible_by(user, local_site=local_site)
Return whether or not the user can modify this Application. A user has access if one of the following conditions is met: * The user owns the Application. * The user is an administrator. * The user is a Local Site administrator on the Local Site the Application is assigned to. Args: user (django.contrib.auth.models.User): The user in question. local_site (reviewboard.site.models.LocalSite): The Local Site the user would modify this Application under. Returns: bool: Whether or not the given user can modify this Application.
Return whether or not the user can modify this Application.
[ "Return", "whether", "or", "not", "the", "user", "can", "modify", "this", "Application", "." ]
def is_mutable_by(self, user, local_site=None): """Return whether or not the user can modify this Application. A user has access if one of the following conditions is met: * The user owns the Application. * The user is an administrator. * The user is a Local Site administrator on the Local Site the Application is assigned to. Args: user (django.contrib.auth.models.User): The user in question. local_site (reviewboard.site.models.LocalSite): The Local Site the user would modify this Application under. Returns: bool: Whether or not the given user can modify this Application. """ return self.is_accessible_by(user, local_site=local_site)
[ "def", "is_mutable_by", "(", "self", ",", "user", ",", "local_site", "=", "None", ")", ":", "return", "self", ".", "is_accessible_by", "(", "user", ",", "local_site", "=", "local_site", ")" ]
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/oauth/models.py#L106-L127
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/digitalbitbox/digitalbitbox.py
python
to_hexstr
(s)
return binascii.hexlify(s).decode('ascii')
[]
def to_hexstr(s): return binascii.hexlify(s).decode('ascii')
[ "def", "to_hexstr", "(", "s", ")", ":", "return", "binascii", ".", "hexlify", "(", "s", ")", ".", "decode", "(", "'ascii'", ")" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/digitalbitbox/digitalbitbox.py#L53-L54
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/io/excel/_util.py
python
_range2cols
(areas: str)
return cols
Convert comma separated list of column names and ranges to indices. Parameters ---------- areas : str A string containing a sequence of column ranges (or areas). Returns ------- cols : list A list of 0-based column indices. Examples -------- >>> _range2cols('A:E') [0, 1, 2, 3, 4] >>> _range2cols('A,C,Z:AB') [0, 2, 25, 26, 27]
Convert comma separated list of column names and ranges to indices.
[ "Convert", "comma", "separated", "list", "of", "column", "names", "and", "ranges", "to", "indices", "." ]
def _range2cols(areas: str) -> list[int]: """ Convert comma separated list of column names and ranges to indices. Parameters ---------- areas : str A string containing a sequence of column ranges (or areas). Returns ------- cols : list A list of 0-based column indices. Examples -------- >>> _range2cols('A:E') [0, 1, 2, 3, 4] >>> _range2cols('A,C,Z:AB') [0, 2, 25, 26, 27] """ cols: list[int] = [] for rng in areas.split(","): if ":" in rng: rngs = rng.split(":") cols.extend(range(_excel2num(rngs[0]), _excel2num(rngs[1]) + 1)) else: cols.append(_excel2num(rng)) return cols
[ "def", "_range2cols", "(", "areas", ":", "str", ")", "->", "list", "[", "int", "]", ":", "cols", ":", "list", "[", "int", "]", "=", "[", "]", "for", "rng", "in", "areas", ".", "split", "(", "\",\"", ")", ":", "if", "\":\"", "in", "rng", ":", ...
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/io/excel/_util.py#L131-L161
Symbo1/wsltools
0b6e536fc85c707a1c81f0296c4e91ca835396a1
wsltools/utils/faker/providers/ssn/fr_CH/__init__.py
python
Provider.vat_id
(self)
return 'CHE' + vat_id + str(_checksum(vat_id))
:return: Swiss UID number
:return: Swiss UID number
[ ":", "return", ":", "Swiss", "UID", "number" ]
def vat_id(self): """ :return: Swiss UID number """ def _checksum(digits): code = ['8', '6', '4', '2', '3', '5', '9', '7'] remainder = 11-(sum(map(lambda x, y: int(x) * int(y), code, digits)) % 11) if remainder == 10: return 0 elif remainder == 11: return 5 return remainder vat_id = self.bothify('########') return 'CHE' + vat_id + str(_checksum(vat_id))
[ "def", "vat_id", "(", "self", ")", ":", "def", "_checksum", "(", "digits", ")", ":", "code", "=", "[", "'8'", ",", "'6'", ",", "'4'", ",", "'2'", ",", "'3'", ",", "'5'", ",", "'9'", ",", "'7'", "]", "remainder", "=", "11", "-", "(", "sum", "(...
https://github.com/Symbo1/wsltools/blob/0b6e536fc85c707a1c81f0296c4e91ca835396a1/wsltools/utils/faker/providers/ssn/fr_CH/__init__.py#L36-L50
rstacruz/sparkup
d400a570bf64b0c216aa7c8e1795820b911a7404
TextMate/Sparkup.tmbundle/Support/sparkup.py
python
Parser.render
(self)
return output
Renders. Called by [[Router]].
Renders. Called by [[Router]].
[ "Renders", ".", "Called", "by", "[[", "Router", "]]", "." ]
def render(self): """Renders. Called by [[Router]]. """ # Get the initial render of the root node output = self.root.render() # Indent by whatever the input is indented with indent = re.findall("^[\r\n]*(\s*)", self.str)[0] output = indent + output.replace("\n", "\n" + indent) # Strip newline if not needed if self.options.has("no-last-newline") \ or self.prefix or self.suffix: output = re.sub(r'\n\s*$', '', output) # TextMate mode if self.options.has("textmate"): output = self._textmatify(output) return output
[ "def", "render", "(", "self", ")", ":", "# Get the initial render of the root node", "output", "=", "self", ".", "root", ".", "render", "(", ")", "# Indent by whatever the input is indented with", "indent", "=", "re", ".", "findall", "(", "\"^[\\r\\n]*(\\s*)\"", ",", ...
https://github.com/rstacruz/sparkup/blob/d400a570bf64b0c216aa7c8e1795820b911a7404/TextMate/Sparkup.tmbundle/Support/sparkup.py#L378-L399
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
datadog_checks_dev/datadog_checks/dev/tooling/dependencies.py
python
read_agent_dependencies
()
return dependencies, errors
[]
def read_agent_dependencies(): dependencies = create_dependency_data() errors = [] load_dependency_data(get_agent_requirements(), dependencies, errors) return dependencies, errors
[ "def", "read_agent_dependencies", "(", ")", ":", "dependencies", "=", "create_dependency_data", "(", ")", "errors", "=", "[", "]", "load_dependency_data", "(", "get_agent_requirements", "(", ")", ",", "dependencies", ",", "errors", ")", "return", "dependencies", "...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/datadog_checks_dev/datadog_checks/dev/tooling/dependencies.py#L114-L120
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
gui/appJar.py
python
gui.GET_DIMS
(container)
return dims
returns a dictionary of dimensions for the supplied container
returns a dictionary of dimensions for the supplied container
[ "returns", "a", "dictionary", "of", "dimensions", "for", "the", "supplied", "container" ]
def GET_DIMS(container): """ returns a dictionary of dimensions for the supplied container """ container.update() dims = {} # get the apps requested width & height dims["r_width"] = container.winfo_reqwidth() dims["r_height"] = container.winfo_reqheight() # get the current width & height dims["w_width"] = container.winfo_width() dims["w_height"] = container.winfo_height() # get the window's width & height dims["s_width"] = container.winfo_screenwidth() dims["s_height"] = container.winfo_screenheight() # determine best geom for OS # on MAC & LINUX, w_width/w_height always 1 unless user-set # on WIN, w_height is bigger then r_height - leaving empty space if gui.GET_PLATFORM() in [gui.MAC, gui.LINUX]: if dims["w_width"] != 1: dims["b_width"] = dims["w_width"] dims["b_height"] = dims["w_height"] else: dims["b_width"] = dims["r_width"] dims["b_height"] = dims["r_height"] else: dims["b_height"] = max(dims["r_height"], dims["w_height"]) dims["b_width"] = max(dims["r_width"], dims["w_width"]) # GUI's corner - widget's corner # widget's corner can be 0 on windows when size not set by user dims["outerFrameWidth"] = 0 if container.winfo_x() == 0 else container.winfo_rootx() - container.winfo_x() dims["titleBarHeight"] = 0 if container.winfo_rooty() == 0 else container.winfo_rooty() - container.winfo_y() # add it all together dims["actualWidth"] = dims["b_width"] + (dims["outerFrameWidth"] * 2) dims["actualHeight"] = dims["b_height"] + dims["titleBarHeight"] + dims["outerFrameWidth"] dims["x"] = (dims["s_width"] // 2) - (dims["actualWidth"] // 2) dims["y"] = (dims["s_height"] // 2) - (dims["actualHeight"] // 2) return dims
[ "def", "GET_DIMS", "(", "container", ")", ":", "container", ".", "update", "(", ")", "dims", "=", "{", "}", "# get the apps requested width & height", "dims", "[", "\"r_width\"", "]", "=", "container", ".", "winfo_reqwidth", "(", ")", "dims", "[", "\"r_height\...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/gui/appJar.py#L365-L407
YaoZeyuan/ZhihuHelp_archived
a0e4a7acd4512452022ce088fff2adc6f8d30195
src/container/book.py
python
Book.generate_question_page
(self, question)
return uri
:type question: src.container.task_result.Question :return: :rtype:
:type question: src.container.task_result.Question :return: :rtype:
[ ":", "type", "question", ":", "src", ".", "container", ".", "task_result", ".", "Question", ":", "return", ":", ":", "rtype", ":" ]
def generate_question_page(self, question): """ :type question: src.container.task_result.Question :return: :rtype: """ # 先输出answer的内容 answer_content = u'' for answer in question.answer_list: answer_content += Template.answer.format( **{ 'author_avatar_url': answer.author_avatar_url, 'author_name': answer.author_name, 'author_id': answer.author_id, 'author_headline': answer.author_headline, 'content': answer.content, 'comment_count': answer.comment_count, 'voteup_count': answer.voteup_count, 'updated_time': ExtraTools.format_date(u'%Y-%m-%d %H:%M:%S', answer.updated_time), } ) filename = self.get_random_html_file_name() content = Template.question.format( **{ 'title': question.question_info.title, 'description': question.question_info.detail, 'answer': answer_content } ) uri = Path.html_pool_path + '/' + filename buf_file = open(uri, 'w') buf_file.write(content) buf_file.close() return uri
[ "def", "generate_question_page", "(", "self", ",", "question", ")", ":", "# 先输出answer的内容", "answer_content", "=", "u''", "for", "answer", "in", "question", ".", "answer_list", ":", "answer_content", "+=", "Template", ".", "answer", ".", "format", "(", "*", "*"...
https://github.com/YaoZeyuan/ZhihuHelp_archived/blob/a0e4a7acd4512452022ce088fff2adc6f8d30195/src/container/book.py#L303-L338
mihaip/readerisdead
0e35cf26e88f27e0a07432182757c1ce230f6936
third_party/web/template.py
python
PythonTokenizer.__init__
(self, text)
[]
def __init__(self, text): self.text = text readline = iter([text]).next self.tokens = tokenize.generate_tokens(readline) self.index = 0
[ "def", "__init__", "(", "self", ",", "text", ")", ":", "self", ".", "text", "=", "text", "readline", "=", "iter", "(", "[", "text", "]", ")", ".", "next", "self", ".", "tokens", "=", "tokenize", ".", "generate_tokens", "(", "readline", ")", "self", ...
https://github.com/mihaip/readerisdead/blob/0e35cf26e88f27e0a07432182757c1ce230f6936/third_party/web/template.py#L473-L477
iagcl/watchmen
d329b357e6fde3ad91e972988b160a33c12afc2a
elasticsearch/roll_indexes/packages/requests/models.py
python
Response.next
(self)
return self._next
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
[ "Returns", "a", "PreparedRequest", "for", "the", "next", "request", "in", "a", "redirect", "chain", "if", "there", "is", "one", "." ]
def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "_next" ]
https://github.com/iagcl/watchmen/blob/d329b357e6fde3ad91e972988b160a33c12afc2a/elasticsearch/roll_indexes/packages/requests/models.py#L715-L717
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pexpect/expect.py
python
searcher_re.__init__
(self, patterns)
This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.
This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.
[ "This", "creates", "an", "instance", "that", "searches", "for", "patterns", "Where", "patterns", "may", "be", "a", "list", "or", "other", "sequence", "of", "compiled", "regular", "expressions", "or", "the", "EOF", "or", "TIMEOUT", "types", "." ]
def __init__(self, patterns): '''This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.''' self.eof_index = -1 self.timeout_index = -1 self._searches = [] for n, s in zip(list(range(len(patterns))), patterns): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._searches.append((n, s))
[ "def", "__init__", "(", "self", ",", "patterns", ")", ":", "self", ".", "eof_index", "=", "-", "1", "self", ".", "timeout_index", "=", "-", "1", "self", ".", "_searches", "=", "[", "]", "for", "n", ",", "s", "in", "zip", "(", "list", "(", "range"...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pexpect/expect.py#L239-L254
dumyy/handpose
ff79f80ebbfa0903fcc837e7150ec0ba61e21700
util/evaluation.py
python
Evaluation.maxJntError
(cls_obj, skel1, skel2)
return diff.max()
[]
def maxJntError(cls_obj, skel1, skel2): diff = skel1.reshape(-1,3)*50 - skel2.reshape(-1,3)*50 diff = alg.norm(diff, axis=1) if True:#globalConfig.dataset == 'NYU': l = [0,3,6,9,12,15,18,21,24,25,27,30,31,32] diff = diff[l] return diff.max()
[ "def", "maxJntError", "(", "cls_obj", ",", "skel1", ",", "skel2", ")", ":", "diff", "=", "skel1", ".", "reshape", "(", "-", "1", ",", "3", ")", "*", "50", "-", "skel2", ".", "reshape", "(", "-", "1", ",", "3", ")", "*", "50", "diff", "=", "al...
https://github.com/dumyy/handpose/blob/ff79f80ebbfa0903fcc837e7150ec0ba61e21700/util/evaluation.py#L10-L16
SoCo/SoCo
e83fef84d2645d05265dbd574598518655a9c125
soco/cache.py
python
TimedCache.delete
(self, *args, **kwargs)
Delete an item from the cache for this combination of args and kwargs.
Delete an item from the cache for this combination of args and kwargs.
[ "Delete", "an", "item", "from", "the", "cache", "for", "this", "combination", "of", "args", "and", "kwargs", "." ]
def delete(self, *args, **kwargs): """Delete an item from the cache for this combination of args and kwargs.""" cache_key = self.make_key(args, kwargs) with self._cache_lock: try: del self._cache[cache_key] except KeyError: pass
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "self", ".", "make_key", "(", "args", ",", "kwargs", ")", "with", "self", ".", "_cache_lock", ":", "try", ":", "del", "self", ".", "_cache", "[", ...
https://github.com/SoCo/SoCo/blob/e83fef84d2645d05265dbd574598518655a9c125/soco/cache.py#L168-L176
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/flask_lib/werkzeug/datastructures.py
python
_CacheControl._del_cache_value
(self, key)
Used internally by the accessor properties.
Used internally by the accessor properties.
[ "Used", "internally", "by", "the", "accessor", "properties", "." ]
def _del_cache_value(self, key): """Used internally by the accessor properties.""" if key in self: del self[key]
[ "def", "_del_cache_value", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ":", "del", "self", "[", "key", "]" ]
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/flask_lib/werkzeug/datastructures.py#L1936-L1939
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/driving.py
python
cosine
(w, A=1, phi=0, offset=0)
return partial(force, sequence=_advance(f))
Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values
Return a driver function that can advance a sequence of cosine values.
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "sequence", "of", "cosine", "values", "." ]
def cosine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values ''' from math import cos def f(i): return A * cos(w*i + phi) + offset return partial(force, sequence=_advance(f))
[ "def", "cosine", "(", "w", ",", "A", "=", "1", ",", "phi", "=", "0", ",", "offset", "=", "0", ")", ":", "from", "math", "import", "cos", "def", "f", "(", "i", ")", ":", "return", "A", "*", "cos", "(", "w", "*", "i", "+", "phi", ")", "+", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/driving.py#L96-L113
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/directv/media_player.py
python
DIRECTVMediaPlayer.media_position
(self)
return self._last_position
Position of current playing media in seconds.
Position of current playing media in seconds.
[ "Position", "of", "current", "playing", "media", "in", "seconds", "." ]
def media_position(self): """Position of current playing media in seconds.""" if self._is_standby: return None return self._last_position
[ "def", "media_position", "(", "self", ")", ":", "if", "self", ".", "_is_standby", ":", "return", "None", "return", "self", ".", "_last_position" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/directv/media_player.py#L185-L190
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/main.py
python
_show_version
(settings)
Show version with optional debugging details.
Show version with optional debugging details.
[ "Show", "version", "with", "optional", "debugging", "details", "." ]
def _show_version(settings): """Show version with optional debugging details.""" if settings.debug: stdio.stdout.write(u'%s %s\n%s\n' % (NAME, LONG_VERSION, COPYRIGHT)) stdio.stdout.write(debug.get_platform_info()) else: stdio.stdout.write(u'%s %s\n%s\n' % (NAME, VERSION, COPYRIGHT))
[ "def", "_show_version", "(", "settings", ")", ":", "if", "settings", ".", "debug", ":", "stdio", ".", "stdout", ".", "write", "(", "u'%s %s\\n%s\\n'", "%", "(", "NAME", ",", "LONG_VERSION", ",", "COPYRIGHT", ")", ")", "stdio", ".", "stdout", ".", "write"...
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/main.py#L74-L80
SigmaHQ/sigma
6f7d28b52a6468b2430e8d7dfefb79dc01e2f1af
tools/sigma/backends/ala.py
python
AzureAPIBackend.__init__
(self, *args, **kwargs)
Initialize field mappings
Initialize field mappings
[ "Initialize", "field", "mappings" ]
def __init__(self, *args, **kwargs): """Initialize field mappings""" super().__init__(*args, **kwargs) self.techniques = self._load_mitre_file("techniques")
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "techniques", "=", "self", ".", "_load_mitre_file", "(", "\"techni...
https://github.com/SigmaHQ/sigma/blob/6f7d28b52a6468b2430e8d7dfefb79dc01e2f1af/tools/sigma/backends/ala.py#L425-L428
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/integrals/rde.py
python
special_denom
(a, ba, bd, ca, cd, DE, case='auto')
return (A, B, C, h)
Special part of the denominator. case is one of {'exp', 'tan', 'primitive'} for the hyperexponential, hypertangent, and primitive cases, respectively. For the hyperexponential (resp. hypertangent) case, given a derivation D on k[t] and a in k[t], b, c, in k<t> with Dt/t in k (resp. Dt/(t**2 + 1) in k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp. gcd(a, t**2 + 1) == 1), return the quadruplet (A, B, C, 1/h) such that A, B, C, h in k[t] and for any solution q in k<t> of a*Dq + b*q == c, r = qh in k[t] satisfies A*Dr + B*r == C. For case == 'primitive', k<t> == k[t], so it returns (a, b, c, 1) in this case. This constitutes step 2 of the outline given in the rde.py docstring.
Special part of the denominator.
[ "Special", "part", "of", "the", "denominator", "." ]
def special_denom(a, ba, bd, ca, cd, DE, case='auto'): """ Special part of the denominator. case is one of {'exp', 'tan', 'primitive'} for the hyperexponential, hypertangent, and primitive cases, respectively. For the hyperexponential (resp. hypertangent) case, given a derivation D on k[t] and a in k[t], b, c, in k<t> with Dt/t in k (resp. Dt/(t**2 + 1) in k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp. gcd(a, t**2 + 1) == 1), return the quadruplet (A, B, C, 1/h) such that A, B, C, h in k[t] and for any solution q in k<t> of a*Dq + b*q == c, r = qh in k[t] satisfies A*Dr + B*r == C. For case == 'primitive', k<t> == k[t], so it returns (a, b, c, 1) in this case. This constitutes step 2 of the outline given in the rde.py docstring. """ from sympy.integrals.prde import parametric_log_deriv # TODO: finish writing this and write tests if case == 'auto': case = DE.case if case == 'exp': p = Poly(DE.t, DE.t) elif case == 'tan': p = Poly(DE.t**2 + 1, DE.t) elif case in ['primitive', 'base']: B = ba.to_field().quo(bd) C = ca.to_field().quo(cd) return (a, B, C, Poly(1, DE.t)) else: raise ValueError("case must be one of {'exp', 'tan', 'primitive', " "'base'}, not %s." % case) nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t) nc = order_at(ca, p, DE.t) - order_at(cd, p, DE.t) n = min(0, nc - min(0, nb)) if not nb: # Possible cancellation. if case == 'exp': dcoeff = DE.d.quo(Poly(DE.t, DE.t)) with DecrementLevel(DE): # We are guaranteed to not have problems, # because case != 'base'. alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t) etaa, etad = frac_in(dcoeff, DE.t) A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE) if A is not None: Q, m, z = A if Q == 1: n = min(n, m) elif case == 'tan': dcoeff = DE.d.quo(Poly(DE.t**2+1, DE.t)) with DecrementLevel(DE): # We are guaranteed to not have problems, # because case != 'base'. alphaa, alphad = frac_in(im(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t) betaa, betad = frac_in(re(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t) etaa, etad = frac_in(dcoeff, DE.t) if recognize_log_derivative(2*betaa, betad, DE): A = parametric_log_deriv(alphaa*sqrt(-1)*betad+alphad*betaa, alphad*betad, etaa, etad, DE) if A is not None: Q, m, z = A if Q == 1: n = min(n, m) N = max(0, -nb, n - nc) pN = p**N pn = p**-n A = a*pN B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN C = (ca*pN*pn).quo(cd) h = pn # (a*p**N, (b + n*a*Dp/p)*p**N, c*p**(N - n), p**-n) return (A, B, C, h)
[ "def", "special_denom", "(", "a", ",", "ba", ",", "bd", ",", "ca", ",", "cd", ",", "DE", ",", "case", "=", "'auto'", ")", ":", "from", "sympy", ".", "integrals", ".", "prde", "import", "parametric_log_deriv", "# TODO: finish writing this and write tests", "i...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/integrals/rde.py#L175-L254
moloch--/RootTheBox
097272332b9f9b7e2df31ca0823ed10c7b66ac81
models/Flag.py
python
Flag._create_flag_static
(cls, box, name, raw_token, description, value)
return cls( box_id=box.id, name=name, token=raw_token, description=description, value=value, )
Check flag static specific parameters
Check flag static specific parameters
[ "Check", "flag", "static", "specific", "parameters" ]
def _create_flag_static(cls, box, name, raw_token, description, value): """ Check flag static specific parameters """ return cls( box_id=box.id, name=name, token=raw_token, description=description, value=value, )
[ "def", "_create_flag_static", "(", "cls", ",", "box", ",", "name", ",", "raw_token", ",", "description", ",", "value", ")", ":", "return", "cls", "(", "box_id", "=", "box", ".", "id", ",", "name", "=", "name", ",", "token", "=", "raw_token", ",", "de...
https://github.com/moloch--/RootTheBox/blob/097272332b9f9b7e2df31ca0823ed10c7b66ac81/models/Flag.py#L195-L203
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/tkinter/__init__.py
python
Spinbox.selection
(self, *args)
return self._getints( self.tk.call((self._w, 'selection') + args)) or ()
Internal function.
Internal function.
[ "Internal", "function", "." ]
def selection(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'selection') + args)) or ()
[ "def", "selection", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "_getints", "(", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'selection'", ")", "+", "args", ")", ")", "or", "(", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/tkinter/__init__.py#L3614-L3617
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cuda/libdevice.py
python
frcp_rd
(x)
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_rd.html :param x: Argument. :type x: float32 :rtype: float32
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_rd.html
[ "See", "https", ":", "//", "docs", ".", "nvidia", ".", "com", "/", "cuda", "/", "libdevice", "-", "users", "-", "guide", "/", "__nv_frcp_rd", ".", "html" ]
def frcp_rd(x): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_rd.html :param x: Argument. :type x: float32 :rtype: float32 """
[ "def", "frcp_rd", "(", "x", ")", ":" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/libdevice.py#L1711-L1718
picoCTF/picoCTF
ec33d05208b51b56760d8f72f4971ea70712bc3b
picoCTF-web/api/user.py
python
is_logged_in
()
return logged_in
Check if the user is currently logged in. Returns: True if the user is logged in, false otherwise.
Check if the user is currently logged in.
[ "Check", "if", "the", "user", "is", "currently", "logged", "in", "." ]
def is_logged_in(): """ Check if the user is currently logged in. Returns: True if the user is logged in, false otherwise. """ logged_in = "uid" in session if logged_in: user = api.user.get_user(uid=session["uid"]) if not user or (user.get("disabled", False) is True): logout() return False return logged_in
[ "def", "is_logged_in", "(", ")", ":", "logged_in", "=", "\"uid\"", "in", "session", "if", "logged_in", ":", "user", "=", "api", ".", "user", ".", "get_user", "(", "uid", "=", "session", "[", "\"uid\"", "]", ")", "if", "not", "user", "or", "(", "user"...
https://github.com/picoCTF/picoCTF/blob/ec33d05208b51b56760d8f72f4971ea70712bc3b/picoCTF-web/api/user.py#L535-L549
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_6.4/Crypto/Util/asn1.py
python
DerObjectId.decode
(self, derEle, noLeftOvers=0)
return p
[]
def decode(self, derEle, noLeftOvers=0): p = DerObject.decode(derEle, noLeftOvers) if not self.isType("OBJECT IDENTIFIER"): raise ValueError("Not a valid OBJECT IDENTIFIER.") return p
[ "def", "decode", "(", "self", ",", "derEle", ",", "noLeftOvers", "=", "0", ")", ":", "p", "=", "DerObject", ".", "decode", "(", "derEle", ",", "noLeftOvers", ")", "if", "not", "self", ".", "isType", "(", "\"OBJECT IDENTIFIER\"", ")", ":", "raise", "Val...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_6.4/Crypto/Util/asn1.py#L273-L277
deepinsight/insightface
c0b25f998a649f662c7136eb389abcacd7900e9d
detection/scrfd/mmdet/core/mask/structures.py
python
PolygonMasks.rotate
(self, out_shape, angle, center=None, scale=1.0, fill_val=0)
return rotated_masks
See :func:`BaseInstanceMasks.rotate`.
See :func:`BaseInstanceMasks.rotate`.
[ "See", ":", "func", ":", "BaseInstanceMasks", ".", "rotate", "." ]
def rotate(self, out_shape, angle, center=None, scale=1.0, fill_val=0): """See :func:`BaseInstanceMasks.rotate`.""" if len(self.masks) == 0: rotated_masks = PolygonMasks([], *out_shape) else: rotated_masks = [] rotate_matrix = cv2.getRotationMatrix2D(center, -angle, scale) for poly_per_obj in self.masks: rotated_poly = [] for p in poly_per_obj: p = p.copy() coords = np.stack([p[0::2], p[1::2]], axis=1) # [n, 2] # pad 1 to convert from format [x, y] to homogeneous # coordinates format [x, y, 1] coords = np.concatenate( (coords, np.ones((coords.shape[0], 1), coords.dtype)), axis=1) # [n, 3] rotated_coords = np.matmul( rotate_matrix[None, :, :], coords[:, :, None])[..., 0] # [n, 2, 1] -> [n, 2] rotated_coords[:, 0] = np.clip(rotated_coords[:, 0], 0, out_shape[1]) rotated_coords[:, 1] = np.clip(rotated_coords[:, 1], 0, out_shape[0]) rotated_poly.append(rotated_coords.reshape(-1)) rotated_masks.append(rotated_poly) rotated_masks = PolygonMasks(rotated_masks, *out_shape) return rotated_masks
[ "def", "rotate", "(", "self", ",", "out_shape", ",", "angle", ",", "center", "=", "None", ",", "scale", "=", "1.0", ",", "fill_val", "=", "0", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "rotated_masks", "=", "PolygonMask...
https://github.com/deepinsight/insightface/blob/c0b25f998a649f662c7136eb389abcacd7900e9d/detection/scrfd/mmdet/core/mask/structures.py#L724-L751
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/apis/rbac_authorization_v1alpha1_api.py
python
RbacAuthorizationV1alpha1Api.create_namespaced_role_binding_with_http_info
(self, namespace, body, **kwargs)
return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1alpha1RoleBinding', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
create a RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_namespaced_role_binding_with_http_info(namespace, body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1alpha1RoleBinding body: (required) :param str pretty: If 'true', then the output is pretty printed. :return: V1alpha1RoleBinding If the method is called asynchronously, returns the request thread.
create a RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_namespaced_role_binding_with_http_info(namespace, body, callback=callback_function)
[ "create", "a", "RoleBinding", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when", "receiv...
def create_namespaced_role_binding_with_http_info(self, namespace, body, **kwargs): """ create a RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_namespaced_role_binding_with_http_info(namespace, body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1alpha1RoleBinding body: (required) :param str pretty: If 'true', then the output is pretty printed. :return: V1alpha1RoleBinding If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'body', 'pretty'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_role_binding" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_role_binding`") # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_namespaced_role_binding`") collection_formats = {} resource_path = '/apis/rbac.authorization.k8s.io/v1alpha1/namespaces/{namespace}/rolebindings'.replace('{format}', 'json') path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = {} if 'pretty' in params: query_params['pretty'] = params['pretty'] header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api(resource_path, 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1alpha1RoleBinding', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "create_namespaced_role_binding_with_http_info", "(", "self", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "all_params", "=", "[", "'namespace'", ",", "'body'", ",", "'pretty'", "]", "all_params", ".", "append", "(", "'callback'", "...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/apis/rbac_authorization_v1alpha1_api.py#L404-L491
PaddlePaddle/PaddleHub
107ee7e1a49d15e9c94da3956475d88a53fc165f
paddlehub/compat/task/tokenization.py
python
BasicTokenizer._clean_text
(self, text: str)
return ''.join(output)
Performs invalid character removal and whitespace cleanup on text.
Performs invalid character removal and whitespace cleanup on text.
[ "Performs", "invalid", "character", "removal", "and", "whitespace", "cleanup", "on", "text", "." ]
def _clean_text(self, text: str) -> str: '''Performs invalid character removal and whitespace cleanup on text.''' output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xfffd or _is_control(char): continue if _is_whitespace(char): output.append(' ') else: output.append(char) return ''.join(output)
[ "def", "_clean_text", "(", "self", ",", "text", ":", "str", ")", "->", "str", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "cp", "==", "0", "or", "cp", "==", "0xfffd", "or", "_is_cont...
https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/paddlehub/compat/task/tokenization.py#L258-L269
sukeesh/Jarvis
2dc2a550b59ea86cca5dfb965661b6fc4cabd434
jarviscli/PluginManager.py
python
PluginManager.add_directory
(self, path)
Add directory to search path for plugins
Add directory to search path for plugins
[ "Add", "directory", "to", "search", "path", "for", "plugins" ]
def add_directory(self, path): """Add directory to search path for plugins""" self._backend.add_plugin_directories(path) self._cache = None
[ "def", "add_directory", "(", "self", ",", "path", ")", ":", "self", ".", "_backend", ".", "add_plugin_directories", "(", "path", ")", "self", ".", "_cache", "=", "None" ]
https://github.com/sukeesh/Jarvis/blob/2dc2a550b59ea86cca5dfb965661b6fc4cabd434/jarviscli/PluginManager.py#L46-L49
MhLiao/MaskTextSpotter
7109132ff0ffbe77832e4b067b174d70dcc37df4
evaluation/icdar2015/e2e/script.py
python
default_evaluation_params
()
return { 'IOU_CONSTRAINT' :0.5, 'AREA_PRECISION_CONSTRAINT' :0.5, 'WORD_SPOTTING' :False, 'MIN_LENGTH_CARE_WORD' :3, 'GT_SAMPLE_NAME_2_ID':'gt_img_([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID':'res_img_([0-9]+).txt', 'LTRB':False, #LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4) 'CRLF':False, # Lines are delimited by Windows CRLF format 'CONFIDENCES':False, #Detections must include confidence value. MAP and MAR will be calculated, 'SPECIAL_CHARACTERS':'!?.:,*"()·[]/\'', 'ONLY_REMOVE_FIRST_LAST_CHARACTER' : True }
default_evaluation_params: Default parameters to use for the validation and evaluation.
default_evaluation_params: Default parameters to use for the validation and evaluation.
[ "default_evaluation_params", ":", "Default", "parameters", "to", "use", "for", "the", "validation", "and", "evaluation", "." ]
def default_evaluation_params(): """ default_evaluation_params: Default parameters to use for the validation and evaluation. """ return { 'IOU_CONSTRAINT' :0.5, 'AREA_PRECISION_CONSTRAINT' :0.5, 'WORD_SPOTTING' :False, 'MIN_LENGTH_CARE_WORD' :3, 'GT_SAMPLE_NAME_2_ID':'gt_img_([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID':'res_img_([0-9]+).txt', 'LTRB':False, #LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4) 'CRLF':False, # Lines are delimited by Windows CRLF format 'CONFIDENCES':False, #Detections must include confidence value. MAP and MAR will be calculated, 'SPECIAL_CHARACTERS':'!?.:,*"()·[]/\'', 'ONLY_REMOVE_FIRST_LAST_CHARACTER' : True }
[ "def", "default_evaluation_params", "(", ")", ":", "return", "{", "'IOU_CONSTRAINT'", ":", "0.5", ",", "'AREA_PRECISION_CONSTRAINT'", ":", "0.5", ",", "'WORD_SPOTTING'", ":", "False", ",", "'MIN_LENGTH_CARE_WORD'", ":", "3", ",", "'GT_SAMPLE_NAME_2_ID'", ":", "'gt_i...
https://github.com/MhLiao/MaskTextSpotter/blob/7109132ff0ffbe77832e4b067b174d70dcc37df4/evaluation/icdar2015/e2e/script.py#L18-L34
F-Secure/see
900472b8b3e45fbb414f3beba4df48e86eaa4b3a
see/context/resources/helpers.py
python
subelement
(element, xpath, tag, text, **kwargs)
return subelm
Searches element matching the *xpath* in *parent* and replaces it's *tag*, *text* and *kwargs* attributes. If the element in *xpath* is not found a new child element is created with *kwargs* attributes and added. Returns the found/created element.
Searches element matching the *xpath* in *parent* and replaces it's *tag*, *text* and *kwargs* attributes.
[ "Searches", "element", "matching", "the", "*", "xpath", "*", "in", "*", "parent", "*", "and", "replaces", "it", "s", "*", "tag", "*", "*", "text", "*", "and", "*", "kwargs", "*", "attributes", "." ]
def subelement(element, xpath, tag, text, **kwargs): """ Searches element matching the *xpath* in *parent* and replaces it's *tag*, *text* and *kwargs* attributes. If the element in *xpath* is not found a new child element is created with *kwargs* attributes and added. Returns the found/created element. """ subelm = element.find(xpath) if subelm is None: subelm = etree.SubElement(element, tag) else: subelm.tag = tag subelm.text = text for attr, value in kwargs.items(): subelm.set(attr, value) return subelm
[ "def", "subelement", "(", "element", ",", "xpath", ",", "tag", ",", "text", ",", "*", "*", "kwargs", ")", ":", "subelm", "=", "element", ".", "find", "(", "xpath", ")", "if", "subelm", "is", "None", ":", "subelm", "=", "etree", ".", "SubElement", "...
https://github.com/F-Secure/see/blob/900472b8b3e45fbb414f3beba4df48e86eaa4b3a/see/context/resources/helpers.py#L20-L41
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/tools/devappserver2/admin/memcache_viewer.py
python
MemcacheViewerRequestHandler.get
(self)
Show template and prepare stats and/or key+value to display/edit.
Show template and prepare stats and/or key+value to display/edit.
[ "Show", "template", "and", "prepare", "stats", "and", "/", "or", "key", "+", "value", "to", "display", "/", "edit", "." ]
def get(self): """Show template and prepare stats and/or key+value to display/edit.""" values = {'request': self.request, 'message': self.request.get('message')} edit = self.request.get('edit') key = self.request.get('key') if edit: # Show the form to edit/create the value. key = edit values['show_stats'] = False values['show_value'] = False values['show_valueform'] = True values['types'] = [typestr for _, _, typestr in self.TYPES] elif key: # A key was given, show it's value on the stats page. values['show_stats'] = True values['show_value'] = True values['show_valueform'] = False else: # Plain stats display + key lookup form. values['show_stats'] = True values['show_valueform'] = False values['show_value'] = False if key: values['key'] = key values['value'], values['type'] = self._get_memcache_value_and_type(key) values['key_exists'] = values['value'] is not None if values['type'] in ('pickled', 'error'): values['writable'] = False else: values['writable'] = True if values['show_stats']: memcache_stats = memcache.get_stats() if not memcache_stats: # No stats means no memcache usage. memcache_stats = {'hits': 0, 'misses': 0, 'byte_hits': 0, 'items': 0, 'bytes': 0, 'oldest_item_age': 0} values['stats'] = memcache_stats try: hitratio = memcache_stats['hits'] * 100 / (memcache_stats['hits'] + memcache_stats['misses']) except ZeroDivisionError: hitratio = 0 values['hitratio'] = hitratio # TODO: oldest_item_age should be formatted in a more useful # way. delta_t = datetime.timedelta(seconds=memcache_stats['oldest_item_age']) values['oldest_item_age'] = datetime.datetime.now() - delta_t self.response.write(self.render('memcache_viewer.html', values))
[ "def", "get", "(", "self", ")", ":", "values", "=", "{", "'request'", ":", "self", ".", "request", ",", "'message'", ":", "self", ".", "request", ".", "get", "(", "'message'", ")", "}", "edit", "=", "self", ".", "request", ".", "get", "(", "'edit'"...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/tools/devappserver2/admin/memcache_viewer.py#L118-L171
pyeventsourcing/eventsourcing
f5a36f434ab2631890092b6c7714b8fb8c94dc7c
eventsourcing/persistence.py
python
InfrastructureFactory.application_recorder
(self)
Constructs an application recorder.
Constructs an application recorder.
[ "Constructs", "an", "application", "recorder", "." ]
def application_recorder(self) -> ApplicationRecorder: """ Constructs an application recorder. """
[ "def", "application_recorder", "(", "self", ")", "->", "ApplicationRecorder", ":" ]
https://github.com/pyeventsourcing/eventsourcing/blob/f5a36f434ab2631890092b6c7714b8fb8c94dc7c/eventsourcing/persistence.py#L718-L721
pydicom/pydicom
935de3b4ac94a5f520f3c91b42220ff0f13bce54
pydicom/encoders/base.py
python
Encoder.name
(self)
return f"{self.UID.keyword}Encoder"
Return the name of the encoder as :class:`str`.
Return the name of the encoder as :class:`str`.
[ "Return", "the", "name", "of", "the", "encoder", "as", ":", "class", ":", "str", "." ]
def name(self) -> str: """Return the name of the encoder as :class:`str`.""" return f"{self.UID.keyword}Encoder"
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "f\"{self.UID.keyword}Encoder\"" ]
https://github.com/pydicom/pydicom/blob/935de3b4ac94a5f520f3c91b42220ff0f13bce54/pydicom/encoders/base.py#L504-L506
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/template/loaders/app_directories.py
python
Loader.load_template_source
(self, template_name, template_dirs=None)
[]
def load_template_source(self, template_name, template_dirs=None): for filepath in self.get_template_sources(template_name, template_dirs): try: with open(filepath, 'rb') as fp: return (fp.read().decode(settings.FILE_CHARSET), filepath) except IOError: pass raise TemplateDoesNotExist(template_name)
[ "def", "load_template_source", "(", "self", ",", "template_name", ",", "template_dirs", "=", "None", ")", ":", "for", "filepath", "in", "self", ".", "get_template_sources", "(", "template_name", ",", "template_dirs", ")", ":", "try", ":", "with", "open", "(", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/template/loaders/app_directories.py#L56-L63
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/bitbake/lib/toaster/bldcollector/views.py
python
eventfile
(request)
return HttpResponse("== Retval %d\n== STDOUT\n%s\n\n== STDERR\n%s" % (importer.returncode, out, err), content_type="text/plain;utf8")
Receives a file by POST, and runs toaster-eventreply on this file
Receives a file by POST, and runs toaster-eventreply on this file
[ "Receives", "a", "file", "by", "POST", "and", "runs", "toaster", "-", "eventreply", "on", "this", "file" ]
def eventfile(request): """ Receives a file by POST, and runs toaster-eventreply on this file """ if request.method != "POST": return HttpResponseBadRequest("This API only accepts POST requests. Post a file with:\n\ncurl -F eventlog=@bitbake_eventlog.json %s\n" % request.build_absolute_uri(reverse('eventfile')), content_type="text/plain;utf8") # write temporary file (handle, abstemppath) = tempfile.mkstemp(dir="/tmp/") with os.fdopen(handle, "w") as tmpfile: for chunk in request.FILES['eventlog'].chunks(): tmpfile.write(chunk) tmpfile.close() # compute the path to "bitbake/bin/toaster-eventreplay" from os.path import dirname as DN import_script = os.path.join(DN(DN(DN(DN(os.path.abspath(__file__))))), "bin/toaster-eventreplay") if not os.path.exists(import_script): raise Exception("script missing %s" % import_script) scriptenv = os.environ.copy() scriptenv["DATABASE_URL"] = toastermain.settings.getDATABASE_URL() # run the data loading process and return the results importer = subprocess.Popen([import_script, abstemppath], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=scriptenv) (out, err) = importer.communicate() if importer.returncode == 0: os.remove(abstemppath) return HttpResponse("== Retval %d\n== STDOUT\n%s\n\n== STDERR\n%s" % (importer.returncode, out, err), content_type="text/plain;utf8")
[ "def", "eventfile", "(", "request", ")", ":", "if", "request", ".", "method", "!=", "\"POST\"", ":", "return", "HttpResponseBadRequest", "(", "\"This API only accepts POST requests. Post a file with:\\n\\ncurl -F eventlog=@bitbake_eventlog.json %s\\n\"", "%", "request", ".", ...
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/bitbake/lib/toaster/bldcollector/views.py#L19-L44
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/awscli/help.py
python
PagingHelpRenderer.render
(self, contents)
Each implementation of HelpRenderer must implement this render method.
Each implementation of HelpRenderer must implement this render method.
[ "Each", "implementation", "of", "HelpRenderer", "must", "implement", "this", "render", "method", "." ]
def render(self, contents): """ Each implementation of HelpRenderer must implement this render method. """ converted_content = self._convert_doc_content(contents) self._send_output_to_pager(converted_content)
[ "def", "render", "(", "self", ",", "contents", ")", ":", "converted_content", "=", "self", ".", "_convert_doc_content", "(", "contents", ")", "self", ".", "_send_output_to_pager", "(", "converted_content", ")" ]
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/awscli/help.py#L79-L85
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/RetinaNet/keras-retinanet/keras_retinanet/preprocessing/open_images.py
python
OpenImagesGenerator.load_annotations
(self, image_index)
return boxes
[]
def load_annotations(self, image_index): image_annotations = self.annotations[self.id_to_image_id[image_index]] labels = image_annotations['boxes'] height, width = image_annotations['h'], image_annotations['w'] boxes = np.zeros((len(labels), 5)) for idx, ann in enumerate(labels): cls_id = ann['cls_id'] x1 = ann['x1'] * width x2 = ann['x2'] * width y1 = ann['y1'] * height y2 = ann['y2'] * height boxes[idx, 0] = x1 boxes[idx, 1] = y1 boxes[idx, 2] = x2 boxes[idx, 3] = y2 boxes[idx, 4] = cls_id return boxes
[ "def", "load_annotations", "(", "self", ",", "image_index", ")", ":", "image_annotations", "=", "self", ".", "annotations", "[", "self", ".", "id_to_image_id", "[", "image_index", "]", "]", "labels", "=", "image_annotations", "[", "'boxes'", "]", "height", ","...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/RetinaNet/keras-retinanet/keras_retinanet/preprocessing/open_images.py#L218-L238
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/common/validators.py
python
TypeOrderValidator._validate_custom_request
(self, certificate_meta)
Validate custom data request We cannot do any validation here because the request parameters are custom. Validation will be done by the plugin. We may choose to select the relevant plugin and call the supports() method to raise validation errors.
Validate custom data request
[ "Validate", "custom", "data", "request" ]
def _validate_custom_request(self, certificate_meta): """Validate custom data request We cannot do any validation here because the request parameters are custom. Validation will be done by the plugin. We may choose to select the relevant plugin and call the supports() method to raise validation errors. """ pass
[ "def", "_validate_custom_request", "(", "self", ",", "certificate_meta", ")", ":", "pass" ]
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/common/validators.py#L571-L579
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/base_shell.py
python
BaseShell.push
(self, line)
return self.compile(src)
Pushes a line onto the buffer and compiles the code in a way that enables multiline input.
Pushes a line onto the buffer and compiles the code in a way that enables multiline input.
[ "Pushes", "a", "line", "onto", "the", "buffer", "and", "compiles", "the", "code", "in", "a", "way", "that", "enables", "multiline", "input", "." ]
def push(self, line): """Pushes a line onto the buffer and compiles the code in a way that enables multiline input. """ self.buffer.append(line) if self.need_more_lines: return None, None src = "".join(self.buffer) src = transform_command(src) return self.compile(src)
[ "def", "push", "(", "self", ",", "line", ")", ":", "self", ".", "buffer", ".", "append", "(", "line", ")", "if", "self", ".", "need_more_lines", ":", "return", "None", ",", "None", "src", "=", "\"\"", ".", "join", "(", "self", ".", "buffer", ")", ...
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/base_shell.py#L445-L454
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
server/pulp/plugins/importer.py
python
Importer.remove_units
(self, repo, units, config)
Removes content units from the given repository. This method is intended to provide the importer with a chance to remove the units from the importer's working directory for the repository. This call will not result in the unit being deleted from Pulp itself. :param repo: metadata describing the repository :type repo: pulp.plugins.model.Repository :param units: list of objects describing the units to import in this call :type units: list :param config: plugin configuration :type config: pulp.plugins.config.PluginCallConfiguration
Removes content units from the given repository.
[ "Removes", "content", "units", "from", "the", "given", "repository", "." ]
def remove_units(self, repo, units, config): """ Removes content units from the given repository. This method is intended to provide the importer with a chance to remove the units from the importer's working directory for the repository. This call will not result in the unit being deleted from Pulp itself. :param repo: metadata describing the repository :type repo: pulp.plugins.model.Repository :param units: list of objects describing the units to import in this call :type units: list :param config: plugin configuration :type config: pulp.plugins.config.PluginCallConfiguration """ pass
[ "def", "remove_units", "(", "self", ",", "repo", ",", "units", ",", "config", ")", ":", "pass" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/server/pulp/plugins/importer.py#L292-L311
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/sem/drt.py
python
DrtAbstractVariableExpression.get_refs
(self, recursive=False)
return []
:see: AbstractExpression.get_refs()
:see: AbstractExpression.get_refs()
[ ":", "see", ":", "AbstractExpression", ".", "get_refs", "()" ]
def get_refs(self, recursive=False): """:see: AbstractExpression.get_refs()""" return []
[ "def", "get_refs", "(", "self", ",", "recursive", "=", "False", ")", ":", "return", "[", "]" ]
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/sem/drt.py#L366-L368
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/urllib3/connectionpool.py
python
HTTPConnectionPool._absolute_url
(self, path)
return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
[]
def _absolute_url(self, path): return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url
[ "def", "_absolute_url", "(", "self", ",", "path", ")", ":", "return", "Url", "(", "scheme", "=", "self", ".", "scheme", ",", "host", "=", "self", ".", "host", ",", "port", "=", "self", ".", "port", ",", "path", "=", "path", ")", ".", "url" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/urllib3/connectionpool.py#L407-L408
fedspendingtransparency/usaspending-api
b13bd5bcba0369ff8512f61a34745626c3969391
usaspending_api/agency/v2/views/agency_base.py
python
AgencyBase.validated_url_params
(self)
return self._validate_params(self.kwargs, list(self.kwargs))
Used by endpoints that need to validate URL parameters instead of or in addition to the query parameters. "additional_models" is used when a TinyShield models outside of the common ones above are needed.
Used by endpoints that need to validate URL parameters instead of or in addition to the query parameters. "additional_models" is used when a TinyShield models outside of the common ones above are needed.
[ "Used", "by", "endpoints", "that", "need", "to", "validate", "URL", "parameters", "instead", "of", "or", "in", "addition", "to", "the", "query", "parameters", ".", "additional_models", "is", "used", "when", "a", "TinyShield", "models", "outside", "of", "the", ...
def validated_url_params(self): """ Used by endpoints that need to validate URL parameters instead of or in addition to the query parameters. "additional_models" is used when a TinyShield models outside of the common ones above are needed. """ return self._validate_params(self.kwargs, list(self.kwargs))
[ "def", "validated_url_params", "(", "self", ")", ":", "return", "self", ".", "_validate_params", "(", "self", ".", "kwargs", ",", "list", "(", "self", ".", "kwargs", ")", ")" ]
https://github.com/fedspendingtransparency/usaspending-api/blob/b13bd5bcba0369ff8512f61a34745626c3969391/usaspending_api/agency/v2/views/agency_base.py#L94-L99
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
mac/pyobjc-core/Lib/objc/_convenience.py
python
nsset__length_hint__
(self)
return len(self)
[]
def nsset__length_hint__(self): return len(self)
[ "def", "nsset__length_hint__", "(", "self", ")", ":", "return", "len", "(", "self", ")" ]
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-core/Lib/objc/_convenience.py#L1416-L1417
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/native/cpu/aarch64.py
python
Aarch64Cpu._STRB_immediate
(cpu, reg_op, mem_op, mimm_op)
STRB (immediate). :param reg_op: source register. :param mem_op: memory. :param mimm_op: None or immediate.
STRB (immediate).
[ "STRB", "(", "immediate", ")", "." ]
def _STRB_immediate(cpu, reg_op, mem_op, mimm_op): """ STRB (immediate). :param reg_op: source register. :param mem_op: memory. :param mimm_op: None or immediate. """ cpu._ldr_str_immediate(reg_op, mem_op, mimm_op, ldr=False, size=8)
[ "def", "_STRB_immediate", "(", "cpu", ",", "reg_op", ",", "mem_op", ",", "mimm_op", ")", ":", "cpu", ".", "_ldr_str_immediate", "(", "reg_op", ",", "mem_op", ",", "mimm_op", ",", "ldr", "=", "False", ",", "size", "=", "8", ")" ]
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/native/cpu/aarch64.py#L4486-L4494
pythonql/pythonql
10ded9473eee8dc75630c2c67f06b6f86a0af305
pythonql/parser/PythonQLParser.py
python
Parser.p_integer
(self, p)
integer : DECIMAL_INTEGER | OCT_INTEGER | HEX_INTEGER | BIN_INTEGER
integer : DECIMAL_INTEGER | OCT_INTEGER | HEX_INTEGER | BIN_INTEGER
[ "integer", ":", "DECIMAL_INTEGER", "|", "OCT_INTEGER", "|", "HEX_INTEGER", "|", "BIN_INTEGER" ]
def p_integer(self, p): """integer : DECIMAL_INTEGER | OCT_INTEGER | HEX_INTEGER | BIN_INTEGER""" p[0] = make_node('integer', p)
[ "def", "p_integer", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "make_node", "(", "'integer'", ",", "p", ")" ]
https://github.com/pythonql/pythonql/blob/10ded9473eee8dc75630c2c67f06b6f86a0af305/pythonql/parser/PythonQLParser.py#L992-L997
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/mhlib.py
python
SubMessage.__init__
(self, f, n, fp)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, f, n, fp): """Constructor.""" Message.__init__(self, f, n, fp) if self.getmaintype() == 'multipart': self.body = Message.getbodyparts(self) else: self.body = Message.getbodytext(self) self.bodyencoded = Message.getbodytext(self, decode=0)
[ "def", "__init__", "(", "self", ",", "f", ",", "n", ",", "fp", ")", ":", "Message", ".", "__init__", "(", "self", ",", "f", ",", "n", ",", "fp", ")", "if", "self", ".", "getmaintype", "(", ")", "==", "'multipart'", ":", "self", ".", "body", "="...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/mhlib.py#L742-L749
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/ec2/elb/loadbalancer.py
python
LoadBalancer.__init__
(self, connection=None, name=None, endpoints=None)
:ivar boto.ec2.elb.ELBConnection connection: The connection this load balancer was instance was instantiated from. :ivar list listeners: A list of tuples in the form of ``(<Inbound port>, <Outbound port>, <Protocol>)`` :ivar boto.ec2.elb.healthcheck.HealthCheck health_check: The health check policy for this load balancer. :ivar boto.ec2.elb.policies.Policies policies: Cookie stickiness and other policies. :ivar str name: The name of the Load Balancer. :ivar str dns_name: The external DNS name for the balancer. :ivar str created_time: A date+time string showing when the load balancer was created. :ivar list instances: A list of :py:class:`boto.ec2.instanceinfo.InstanceInfo` instances, representing the EC2 instances this load balancer is distributing requests to. :ivar list availability_zones: The availability zones this balancer covers. :ivar str canonical_hosted_zone_name: Current CNAME for the balancer. :ivar str canonical_hosted_zone_name_id: The Route 53 hosted zone ID of this balancer. Needed when creating an Alias record in a Route 53 hosted zone. :ivar boto.ec2.elb.securitygroup.SecurityGroup source_security_group: The security group that you can use as part of your inbound rules for your load balancer back-end instances to disallow traffic from sources other than your load balancer. :ivar list subnets: A list of subnets this balancer is on. :ivar list security_groups: A list of additional security groups that have been applied. :ivar str vpc_id: The ID of the VPC that this ELB resides within. :ivar list backends: A list of :py:class:`boto.ec2.elb.loadbalancer.Backend back-end server descriptions.
:ivar boto.ec2.elb.ELBConnection connection: The connection this load balancer was instance was instantiated from. :ivar list listeners: A list of tuples in the form of ``(<Inbound port>, <Outbound port>, <Protocol>)`` :ivar boto.ec2.elb.healthcheck.HealthCheck health_check: The health check policy for this load balancer. :ivar boto.ec2.elb.policies.Policies policies: Cookie stickiness and other policies. :ivar str name: The name of the Load Balancer. :ivar str dns_name: The external DNS name for the balancer. :ivar str created_time: A date+time string showing when the load balancer was created. :ivar list instances: A list of :py:class:`boto.ec2.instanceinfo.InstanceInfo` instances, representing the EC2 instances this load balancer is distributing requests to. :ivar list availability_zones: The availability zones this balancer covers. :ivar str canonical_hosted_zone_name: Current CNAME for the balancer. :ivar str canonical_hosted_zone_name_id: The Route 53 hosted zone ID of this balancer. Needed when creating an Alias record in a Route 53 hosted zone. :ivar boto.ec2.elb.securitygroup.SecurityGroup source_security_group: The security group that you can use as part of your inbound rules for your load balancer back-end instances to disallow traffic from sources other than your load balancer. :ivar list subnets: A list of subnets this balancer is on. :ivar list security_groups: A list of additional security groups that have been applied. :ivar str vpc_id: The ID of the VPC that this ELB resides within. :ivar list backends: A list of :py:class:`boto.ec2.elb.loadbalancer.Backend back-end server descriptions.
[ ":", "ivar", "boto", ".", "ec2", ".", "elb", ".", "ELBConnection", "connection", ":", "The", "connection", "this", "load", "balancer", "was", "instance", "was", "instantiated", "from", ".", ":", "ivar", "list", "listeners", ":", "A", "list", "of", "tuples"...
def __init__(self, connection=None, name=None, endpoints=None): """ :ivar boto.ec2.elb.ELBConnection connection: The connection this load balancer was instance was instantiated from. :ivar list listeners: A list of tuples in the form of ``(<Inbound port>, <Outbound port>, <Protocol>)`` :ivar boto.ec2.elb.healthcheck.HealthCheck health_check: The health check policy for this load balancer. :ivar boto.ec2.elb.policies.Policies policies: Cookie stickiness and other policies. :ivar str name: The name of the Load Balancer. :ivar str dns_name: The external DNS name for the balancer. :ivar str created_time: A date+time string showing when the load balancer was created. :ivar list instances: A list of :py:class:`boto.ec2.instanceinfo.InstanceInfo` instances, representing the EC2 instances this load balancer is distributing requests to. :ivar list availability_zones: The availability zones this balancer covers. :ivar str canonical_hosted_zone_name: Current CNAME for the balancer. :ivar str canonical_hosted_zone_name_id: The Route 53 hosted zone ID of this balancer. Needed when creating an Alias record in a Route 53 hosted zone. :ivar boto.ec2.elb.securitygroup.SecurityGroup source_security_group: The security group that you can use as part of your inbound rules for your load balancer back-end instances to disallow traffic from sources other than your load balancer. :ivar list subnets: A list of subnets this balancer is on. :ivar list security_groups: A list of additional security groups that have been applied. :ivar str vpc_id: The ID of the VPC that this ELB resides within. :ivar list backends: A list of :py:class:`boto.ec2.elb.loadbalancer.Backend back-end server descriptions. """ self.connection = connection self.name = name self.listeners = None self.health_check = None self.policies = None self.dns_name = None self.created_time = None self.instances = None self.availability_zones = ListElement() self.canonical_hosted_zone_name = None self.canonical_hosted_zone_name_id = None self.source_security_group = None self.subnets = ListElement() self.security_groups = ListElement() self.vpc_id = None self.scheme = None self.backends = None self._attributes = None
[ "def", "__init__", "(", "self", ",", "connection", "=", "None", ",", "name", "=", "None", ",", "endpoints", "=", "None", ")", ":", "self", ".", "connection", "=", "connection", "self", ".", "name", "=", "name", "self", ".", "listeners", "=", "None", ...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/ec2/elb/loadbalancer.py#L77-L128
JDAI-CV/Partial-Person-ReID
fb94dbfbec1105bbc22a442702bc6e385427d416
fastreid/utils/precision_bn.py
python
update_bn_stats
(model, data_loader, num_iters: int = 200)
Recompute and update the batch norm stats to make them more precise. During training both BN stats and the weight are changing after every iteration, so the running average can not precisely reflect the actual stats of the current model. In this function, the BN stats are recomputed with fixed weights, to make the running average more precise. Specifically, it computes the true average of per-batch mean/variance instead of the running average. Args: model (nn.Module): the model whose bn stats will be recomputed. Note that: 1. This function will not alter the training mode of the given model. Users are responsible for setting the layers that needs precise-BN to training mode, prior to calling this function. 2. Be careful if your models contain other stateful layers in addition to BN, i.e. layers whose state can change in forward iterations. This function will alter their state. If you wish them unchanged, you need to either pass in a submodule without those layers, or backup the states. data_loader (iterator): an iterator. Produce data as inputs to the model. num_iters (int): number of iterations to compute the stats.
Recompute and update the batch norm stats to make them more precise. During training both BN stats and the weight are changing after every iteration, so the running average can not precisely reflect the actual stats of the current model. In this function, the BN stats are recomputed with fixed weights, to make the running average more precise. Specifically, it computes the true average of per-batch mean/variance instead of the running average. Args: model (nn.Module): the model whose bn stats will be recomputed. Note that: 1. This function will not alter the training mode of the given model. Users are responsible for setting the layers that needs precise-BN to training mode, prior to calling this function. 2. Be careful if your models contain other stateful layers in addition to BN, i.e. layers whose state can change in forward iterations. This function will alter their state. If you wish them unchanged, you need to either pass in a submodule without those layers, or backup the states. data_loader (iterator): an iterator. Produce data as inputs to the model. num_iters (int): number of iterations to compute the stats.
[ "Recompute", "and", "update", "the", "batch", "norm", "stats", "to", "make", "them", "more", "precise", ".", "During", "training", "both", "BN", "stats", "and", "the", "weight", "are", "changing", "after", "every", "iteration", "so", "the", "running", "avera...
def update_bn_stats(model, data_loader, num_iters: int = 200): """ Recompute and update the batch norm stats to make them more precise. During training both BN stats and the weight are changing after every iteration, so the running average can not precisely reflect the actual stats of the current model. In this function, the BN stats are recomputed with fixed weights, to make the running average more precise. Specifically, it computes the true average of per-batch mean/variance instead of the running average. Args: model (nn.Module): the model whose bn stats will be recomputed. Note that: 1. This function will not alter the training mode of the given model. Users are responsible for setting the layers that needs precise-BN to training mode, prior to calling this function. 2. Be careful if your models contain other stateful layers in addition to BN, i.e. layers whose state can change in forward iterations. This function will alter their state. If you wish them unchanged, you need to either pass in a submodule without those layers, or backup the states. data_loader (iterator): an iterator. Produce data as inputs to the model. num_iters (int): number of iterations to compute the stats. """ bn_layers = get_bn_modules(model) if len(bn_layers) == 0: return # In order to make the running stats only reflect the current batch, the # momentum is disabled. # bn.running_mean = (1 - momentum) * bn.running_mean + momentum * batch_mean # Setting the momentum to 1.0 to compute the stats without momentum. momentum_actual = [bn.momentum for bn in bn_layers] for bn in bn_layers: bn.momentum = 1.0 # Note that running_var actually means "running average of variance" running_mean = [torch.zeros_like(bn.running_mean) for bn in bn_layers] running_var = [torch.zeros_like(bn.running_var) for bn in bn_layers] for ind, inputs in enumerate(itertools.islice(data_loader, num_iters)): # Change targets to zero to avoid error in # circle(arcface) loss which will use targets in forward inputs['targets'].zero_() with torch.no_grad(): # No need to backward model(inputs) for i, bn in enumerate(bn_layers): # Accumulates the bn stats. running_mean[i] += (bn.running_mean - running_mean[i]) / (ind + 1) running_var[i] += (bn.running_var - running_var[i]) / (ind + 1) # We compute the "average of variance" across iterations. assert ind == num_iters - 1, ( "update_bn_stats is meant to run for {} iterations, " "but the dataloader stops at {} iterations.".format(num_iters, ind) ) for i, bn in enumerate(bn_layers): # Sets the precise bn stats. bn.running_mean = running_mean[i] bn.running_var = running_var[i] bn.momentum = momentum_actual[i]
[ "def", "update_bn_stats", "(", "model", ",", "data_loader", ",", "num_iters", ":", "int", "=", "200", ")", ":", "bn_layers", "=", "get_bn_modules", "(", "model", ")", "if", "len", "(", "bn_layers", ")", "==", "0", ":", "return", "# In order to make the runni...
https://github.com/JDAI-CV/Partial-Person-ReID/blob/fb94dbfbec1105bbc22a442702bc6e385427d416/fastreid/utils/precision_bn.py#L20-L79
elasticluster/elasticluster
6bfad91bd18375533a616ac88b89e2266bb5c8c6
elasticluster/providers/ec2_boto.py
python
BotoCloudProvider.stop_instance
(self, node)
Destroy a VM. :param Node node: A `Node`:class: instance
Destroy a VM.
[ "Destroy", "a", "VM", "." ]
def stop_instance(self, node): """ Destroy a VM. :param Node node: A `Node`:class: instance """ instance_id = node.instance_id instance = self._load_instance(instance_id) instance.terminate() del self._instances[instance_id]
[ "def", "stop_instance", "(", "self", ",", "node", ")", ":", "instance_id", "=", "node", ".", "instance_id", "instance", "=", "self", ".", "_load_instance", "(", "instance_id", ")", "instance", ".", "terminate", "(", ")", "del", "self", ".", "_instances", "...
https://github.com/elasticluster/elasticluster/blob/6bfad91bd18375533a616ac88b89e2266bb5c8c6/elasticluster/providers/ec2_boto.py#L358-L367
syuntoku14/fusion2urdf
79af25950b4de8801602ca16192a6c836bab7063
URDF_Exporter/utils/utils.py
python
copy_occs
(root)
duplicate all the components
duplicate all the components
[ "duplicate", "all", "the", "components" ]
def copy_occs(root): """ duplicate all the components """ def copy_body(allOccs, occs): """ copy the old occs to new component """ bodies = occs.bRepBodies transform = adsk.core.Matrix3D.create() # Create new components from occs # This support even when a component has some occses. new_occs = allOccs.addNewComponent(transform) # this create new occs if occs.component.name == 'base_link': occs.component.name = 'old_component' new_occs.component.name = 'base_link' else: new_occs.component.name = re.sub('[ :()]', '_', occs.name) new_occs = allOccs.item((allOccs.count-1)) for i in range(bodies.count): body = bodies.item(i) body.copyToComponent(new_occs) allOccs = root.occurrences oldOccs = [] coppy_list = [occs for occs in allOccs] for occs in coppy_list: if occs.bRepBodies.count > 0: copy_body(allOccs, occs) oldOccs.append(occs) for occs in oldOccs: occs.component.name = 'old_component'
[ "def", "copy_occs", "(", "root", ")", ":", "def", "copy_body", "(", "allOccs", ",", "occs", ")", ":", "\"\"\" \n copy the old occs to new component\n \"\"\"", "bodies", "=", "occs", ".", "bRepBodies", "transform", "=", "adsk", ".", "core", ".", "M...
https://github.com/syuntoku14/fusion2urdf/blob/79af25950b4de8801602ca16192a6c836bab7063/URDF_Exporter/utils/utils.py#L16-L51
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/returners/mysql.py
python
get_minions
()
Return a list of minions
Return a list of minions
[ "Return", "a", "list", "of", "minions" ]
def get_minions(): """ Return a list of minions """ with _get_serv(ret=None, commit=True) as cur: sql = """SELECT DISTINCT id FROM `salt_returns`""" cur.execute(sql) data = cur.fetchall() ret = [] for minion in data: ret.append(minion[0]) return ret
[ "def", "get_minions", "(", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "\"\"\"SELECT DISTINCT id\n FROM `salt_returns`\"\"\"", "cur", ".", "execute", "(", "sql", ")", "da...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/returners/mysql.py#L470-L484
obspy/obspy
0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f
obspy/io/arclink/inventory.py
python
validate_arclink_xml
(path_or_object)
return (True, ())
Checks if the given path is a valid arclink_xml file. Returns a tuple. The first item is a boolean describing if the validation was successful or not. The second item is a list of all found validation errors, if existent. :param path_or_object: File name or file like object. Can also be an etree element.
Checks if the given path is a valid arclink_xml file.
[ "Checks", "if", "the", "given", "path", "is", "a", "valid", "arclink_xml", "file", "." ]
def validate_arclink_xml(path_or_object): """ Checks if the given path is a valid arclink_xml file. Returns a tuple. The first item is a boolean describing if the validation was successful or not. The second item is a list of all found validation errors, if existent. :param path_or_object: File name or file like object. Can also be an etree element. """ # Get the schema location. schema_location = Path(inspect.getfile(inspect.currentframe())).parent schema_location = str(schema_location / "data" / "arclink_schema.xsd") xmlschema = etree.XMLSchema(etree.parse(schema_location)) if isinstance(path_or_object, etree._Element): xmldoc = path_or_object else: try: xmldoc = etree.parse(path_or_object) except etree.XMLSyntaxError: return (False, ("Not a XML file.",)) valid = xmlschema.validate(xmldoc) # Pretty error printing if the validation fails. if valid is not True: return (False, xmlschema.error_log) return (True, ())
[ "def", "validate_arclink_xml", "(", "path_or_object", ")", ":", "# Get the schema location.", "schema_location", "=", "Path", "(", "inspect", ".", "getfile", "(", "inspect", ".", "currentframe", "(", ")", ")", ")", ".", "parent", "schema_location", "=", "str", "...
https://github.com/obspy/obspy/blob/0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f/obspy/io/arclink/inventory.py#L84-L114
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/media_file_service/client.py
python
MediaFileServiceClient.__init__
( self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, MediaFileServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiate the media file service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.MediaFileServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason.
Instantiate the media file service client.
[ "Instantiate", "the", "media", "file", "service", "client", "." ]
def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, MediaFileServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the media file service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.MediaFileServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool( util.strtobool( os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") ) ) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc # type: ignore cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, MediaFileServiceTransport): # transport is a MediaFileServiceTransport instance. if credentials: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = MediaFileServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, )
[ "def", "__init__", "(", "self", ",", "*", ",", "credentials", ":", "Optional", "[", "ga_credentials", ".", "Credentials", "]", "=", "None", ",", "transport", ":", "Union", "[", "str", ",", "MediaFileServiceTransport", ",", "None", "]", "=", "None", ",", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/media_file_service/client.py#L236-L351
locuslab/deq
1fb7059d6d89bb26d16da80ab9489dcc73fc5472
DEQ-Sequence/models/deq_transformer.py
python
DEQTransformerLM.reset_length
(self, tgt_len, mem_len)
[]
def reset_length(self, tgt_len, mem_len): self.tgt_len = tgt_len self.mem_len = mem_len
[ "def", "reset_length", "(", "self", ",", "tgt_len", ",", "mem_len", ")", ":", "self", ".", "tgt_len", "=", "tgt_len", "self", ".", "mem_len", "=", "mem_len" ]
https://github.com/locuslab/deq/blob/1fb7059d6d89bb26d16da80ab9489dcc73fc5472/DEQ-Sequence/models/deq_transformer.py#L265-L267
waditu/tushare
093856995af0811d3ebbe8c179b8febf4ae706f0
tushare/stock/reference.py
python
margin_detail
(date='')
return df
沪深融券融券明细 Parameters --------------- date:string 日期 format:YYYY-MM-DD 或者 YYYYMMDD return DataFrame -------------- code: 证券代码 name: 证券名称 buy: 今日买入额 buy_total:融资余额 sell: 今日卖出量(股) sell_total: 融券余量(股) sell_amount: 融券余额 total: 融资融券余额(元) buy_repay: 本日融资偿还额(元) sell_repay: 本日融券偿还量
沪深融券融券明细 Parameters --------------- date:string 日期 format:YYYY-MM-DD 或者 YYYYMMDD return DataFrame -------------- code: 证券代码 name: 证券名称 buy: 今日买入额 buy_total:融资余额 sell: 今日卖出量(股) sell_total: 融券余量(股) sell_amount: 融券余额 total: 融资融券余额(元) buy_repay: 本日融资偿还额(元) sell_repay: 本日融券偿还量
[ "沪深融券融券明细", "Parameters", "---------------", "date", ":", "string", "日期", "format:YYYY", "-", "MM", "-", "DD", "或者", "YYYYMMDD", "return", "DataFrame", "--------------", "code", ":", "证券代码", "name", ":", "证券名称", "buy", ":", "今日买入额", "buy_total", ":", "融资余额", ...
def margin_detail(date=''): """ 沪深融券融券明细 Parameters --------------- date:string 日期 format:YYYY-MM-DD 或者 YYYYMMDD return DataFrame -------------- code: 证券代码 name: 证券名称 buy: 今日买入额 buy_total:融资余额 sell: 今日卖出量(股) sell_total: 融券余量(股) sell_amount: 融券余额 total: 融资融券余额(元) buy_repay: 本日融资偿还额(元) sell_repay: 本日融券偿还量 """ date = str(date).replace('-', '') df = pd.read_csv(ct.MG_URL%(ct.P_TYPE['http'], ct.DOMAINS['oss'], date[0:6], 'mx', date), dtype={'code': object}) return df
[ "def", "margin_detail", "(", "date", "=", "''", ")", ":", "date", "=", "str", "(", "date", ")", ".", "replace", "(", "'-'", ",", "''", ")", "df", "=", "pd", ".", "read_csv", "(", "ct", ".", "MG_URL", "%", "(", "ct", ".", "P_TYPE", "[", "'http'"...
https://github.com/waditu/tushare/blob/093856995af0811d3ebbe8c179b8febf4ae706f0/tushare/stock/reference.py#L902-L928
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/utils/vcs.py
python
is_vcs_repository
(path)
return get_vcs_root(path) is not None
Return True if path is a supported VCS repository
Return True if path is a supported VCS repository
[ "Return", "True", "if", "path", "is", "a", "supported", "VCS", "repository" ]
def is_vcs_repository(path): """Return True if path is a supported VCS repository""" return get_vcs_root(path) is not None
[ "def", "is_vcs_repository", "(", "path", ")", ":", "return", "get_vcs_root", "(", "path", ")", "is", "not", "None" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/utils/vcs.py#L73-L75
taers232c/GAMADV-XTD3
3097d6c24b7377037c746317908fcaff8404d88a
src/gam/gdata/gauth.py
python
AuthSubToken._upgrade_token
(self, http_body)
Replaces the token value with a session token from the auth server. Uses the response of a token upgrade request to modify this token. Uses auth_sub_string_from_body.
Replaces the token value with a session token from the auth server.
[ "Replaces", "the", "token", "value", "with", "a", "session", "token", "from", "the", "auth", "server", "." ]
def _upgrade_token(self, http_body): """Replaces the token value with a session token from the auth server. Uses the response of a token upgrade request to modify this token. Uses auth_sub_string_from_body. """ self.token_string = auth_sub_string_from_body(http_body)
[ "def", "_upgrade_token", "(", "self", ",", "http_body", ")", ":", "self", ".", "token_string", "=", "auth_sub_string_from_body", "(", "http_body", ")" ]
https://github.com/taers232c/GAMADV-XTD3/blob/3097d6c24b7377037c746317908fcaff8404d88a/src/gam/gdata/gauth.py#L409-L415
ceph/ceph-deploy
a16316fc4dd364135b11226df42d9df65c0c60a2
ceph_deploy/gatherkeys.py
python
gatherkeys_missing
(args, distro, rlogger, keypath, keytype, dest_dir)
return True
Get or create the keyring from the mon using the mon keyring by keytype and copy to dest_dir
Get or create the keyring from the mon using the mon keyring by keytype and copy to dest_dir
[ "Get", "or", "create", "the", "keyring", "from", "the", "mon", "using", "the", "mon", "keyring", "by", "keytype", "and", "copy", "to", "dest_dir" ]
def gatherkeys_missing(args, distro, rlogger, keypath, keytype, dest_dir): """ Get or create the keyring from the mon using the mon keyring by keytype and copy to dest_dir """ args_prefix = [ '/usr/bin/ceph', '--connect-timeout=25', '--cluster={cluster}'.format( cluster=args.cluster), '--name', 'mon.', '--keyring={keypath}'.format( keypath=keypath), ] identity = keytype_identity(keytype) if identity is None: raise RuntimeError('Could not find identity for keytype:%s' % keytype) capabilites = keytype_capabilities(keytype) if capabilites is None: raise RuntimeError('Could not find capabilites for keytype:%s' % keytype) # First try getting the key if it already exists, to handle the case where # it exists but doesn't match the caps we would pass into get-or-create. # This is the same behvaior as in newer ceph-create-keys out, err, code = remoto.process.check( distro.conn, args_prefix + ['auth', 'get', identity] ) if code == errno.ENOENT: out, err, code = remoto.process.check( distro.conn, args_prefix + ['auth', 'get-or-create', identity] + capabilites ) if code != 0: rlogger.error( '"ceph auth get-or-create for keytype %s returned %s', keytype, code ) for line in err: rlogger.debug(line) return False keyring_name_local = keytype_path_to(args, keytype) keyring_path_local = os.path.join(dest_dir, keyring_name_local) with open(keyring_path_local, 'w') as f: for line in out: f.write(as_string(line) + '\n') return True
[ "def", "gatherkeys_missing", "(", "args", ",", "distro", ",", "rlogger", ",", "keypath", ",", "keytype", ",", "dest_dir", ")", ":", "args_prefix", "=", "[", "'/usr/bin/ceph'", ",", "'--connect-timeout=25'", ",", "'--cluster={cluster}'", ".", "format", "(", "clus...
https://github.com/ceph/ceph-deploy/blob/a16316fc4dd364135b11226df42d9df65c0c60a2/ceph_deploy/gatherkeys.py#L101-L148
grow/grow
97fc21730b6a674d5d33948d94968e79447ce433
grow/cache/podcache.py
python
PodCache.__init__
(self, dep_cache, obj_cache, routes_cache, pod)
[]
def __init__(self, dep_cache, obj_cache, routes_cache, pod): self._pod = pod self._collection_cache = collection_cache.CollectionCache() self._document_cache = document_cache.DocumentCache() self._file_cache = file_cache.FileCache() self._dependency_graph = dependency.DependencyGraph() self._dependency_graph.add_all(dep_cache) self._object_caches = {} self.create_object_cache( self.KEY_GLOBAL, write_to_file=False, can_reset=True) for key, item in obj_cache.items(): # If this is a string, it is written to a separate cache file. if isinstance(item, str): cache_value = {} if self._pod.file_exists(item): cache_value = self._pod.read_json(item) self.create_object_cache(key, **cache_value) else: self.create_object_cache(key, **item) self._routes_cache = grow_routes_cache.RoutesCache() self._routes_cache.from_data(routes_cache)
[ "def", "__init__", "(", "self", ",", "dep_cache", ",", "obj_cache", ",", "routes_cache", ",", "pod", ")", ":", "self", ".", "_pod", "=", "pod", "self", ".", "_collection_cache", "=", "collection_cache", ".", "CollectionCache", "(", ")", "self", ".", "_docu...
https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/cache/podcache.py#L37-L62
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.main/src/openmdao/main/importfactory.py
python
ImportFactory.create
(self, typ, version=None, server=None, res_desc=None, **ctor_args)
Tries to import the given named module and return a factory function from it. The factory function or constructor must have the same name as the module. The module must be importable in the current Python environment.
Tries to import the given named module and return a factory function from it. The factory function or constructor must have the same name as the module. The module must be importable in the current Python environment.
[ "Tries", "to", "import", "the", "given", "named", "module", "and", "return", "a", "factory", "function", "from", "it", ".", "The", "factory", "function", "or", "constructor", "must", "have", "the", "same", "name", "as", "the", "module", ".", "The", "module...
def create(self, typ, version=None, server=None, res_desc=None, **ctor_args): """Tries to import the given named module and return a factory function from it. The factory function or constructor must have the same name as the module. The module must be importable in the current Python environment. """ if server is not None or version is not None: return None if res_desc is not None and len(res_desc)>0: return None ctor = self._import(typ) if ctor is None: return None else: return ctor(**ctor_args)
[ "def", "create", "(", "self", ",", "typ", ",", "version", "=", "None", ",", "server", "=", "None", ",", "res_desc", "=", "None", ",", "*", "*", "ctor_args", ")", ":", "if", "server", "is", "not", "None", "or", "version", "is", "not", "None", ":", ...
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/importfactory.py#L22-L37
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/pyctp2/sbin/md.py
python
make_user
(ucfg,contract_manager,fpath='md')
return controller
[]
def make_user(ucfg,contract_manager,fpath='md'): mdagent = save_agent.SaveAgent(contract_manager,DATA_PATH) controller = ctl.Controller([mdagent]) tt = ctl.TimeTrigger(152000,controller.day_finalize) md_spi = cm.MdSpiDelegate(name=ucfg.name, broker_id=ucfg.broker_id, investor_id= ucfg.investor_id, passwd= ucfg.passwd, controller = controller, ) user = md_spi user.Create('%s/%s' % (INFO_PATH,fpath)) controller.add_listener(md_spi) controller.update_listened_contracts() user.RegisterFront(ucfg.port) #print('before init') user.Init() return controller
[ "def", "make_user", "(", "ucfg", ",", "contract_manager", ",", "fpath", "=", "'md'", ")", ":", "mdagent", "=", "save_agent", ".", "SaveAgent", "(", "contract_manager", ",", "DATA_PATH", ")", "controller", "=", "ctl", ".", "Controller", "(", "[", "mdagent", ...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp2/sbin/md.py#L21-L38
NifTK/NiftyNet
935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0
niftynet/layer/additive_upsample.py
python
AdditiveUpsampleLayer.layer_op
(self, input_tensor)
return output_tensor
If the input has the shape ``batch, X, Y,[ Z,] Channels``, the output will be ``batch, new_size_x, new_size_y,[ new_size_z,] channels/n_splits``. :param input_tensor: 2D/3D image tensor, with shape: ``batch, X, Y,[ Z,] Channels`` :return: linearly additively upsampled volumes
If the input has the shape ``batch, X, Y,[ Z,] Channels``, the output will be ``batch, new_size_x, new_size_y,[ new_size_z,] channels/n_splits``.
[ "If", "the", "input", "has", "the", "shape", "batch", "X", "Y", "[", "Z", "]", "Channels", "the", "output", "will", "be", "batch", "new_size_x", "new_size_y", "[", "new_size_z", "]", "channels", "/", "n_splits", "." ]
def layer_op(self, input_tensor): """ If the input has the shape ``batch, X, Y,[ Z,] Channels``, the output will be ``batch, new_size_x, new_size_y,[ new_size_z,] channels/n_splits``. :param input_tensor: 2D/3D image tensor, with shape: ``batch, X, Y,[ Z,] Channels`` :return: linearly additively upsampled volumes """ check_divisible_channels(input_tensor, self.n_splits) resizing_layer = ResizingLayer(self.new_size) split = tf.split(resizing_layer(input_tensor), self.n_splits, axis=-1) split_tensor = tf.stack(split, axis=-1) output_tensor = tf.reduce_sum(split_tensor, axis=-1) return output_tensor
[ "def", "layer_op", "(", "self", ",", "input_tensor", ")", ":", "check_divisible_channels", "(", "input_tensor", ",", "self", ".", "n_splits", ")", "resizing_layer", "=", "ResizingLayer", "(", "self", ".", "new_size", ")", "split", "=", "tf", ".", "split", "(...
https://github.com/NifTK/NiftyNet/blob/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/layer/additive_upsample.py#L41-L57
MartinThoma/algorithms
6199cfa3446e1056c7b4d75ca6e306e9e56fd95b
language-word-detection/bigram.py
python
serialize
(data, filename='data.json')
Store data in a file.
Store data in a file.
[ "Store", "data", "in", "a", "file", "." ]
def serialize(data, filename='data.json'): """Store data in a file.""" import json with open(filename, 'w') as f: json.dump(data, f)
[ "def", "serialize", "(", "data", ",", "filename", "=", "'data.json'", ")", ":", "import", "json", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ")" ]
https://github.com/MartinThoma/algorithms/blob/6199cfa3446e1056c7b4d75ca6e306e9e56fd95b/language-word-detection/bigram.py#L31-L35
PyTorchLightning/pytorch-lightning
5914fb748fb53d826ab337fc2484feab9883a104
pytorch_lightning/plugins/environments/lsf_environment.py
python
LSFEnvironment.world_size
(self)
return int(world_size)
The world size is read from the environment variable ``JSM_NAMESPACE_SIZE``.
The world size is read from the environment variable ``JSM_NAMESPACE_SIZE``.
[ "The", "world", "size", "is", "read", "from", "the", "environment", "variable", "JSM_NAMESPACE_SIZE", "." ]
def world_size(self) -> int: """The world size is read from the environment variable ``JSM_NAMESPACE_SIZE``.""" world_size = os.environ.get("JSM_NAMESPACE_SIZE") if world_size is None: raise ValueError( "Cannot determine world size. Environment variable `JSM_NAMESPACE_SIZE` not found." "Make sure you run your executable with `jsrun`." ) return int(world_size)
[ "def", "world_size", "(", "self", ")", "->", "int", ":", "world_size", "=", "os", ".", "environ", ".", "get", "(", "\"JSM_NAMESPACE_SIZE\"", ")", "if", "world_size", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot determine world size. Environment variabl...
https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/plugins/environments/lsf_environment.py#L91-L99
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol61361.py
python
decode_replay_message_events
(contents)
Decodes and yields each message event from the contents byte string.
Decodes and yields each message event from the contents byte string.
[ "Decodes", "and", "yields", "each", "message", "event", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_message_events(contents): """Decodes and yields each message event from the contents byte string.""" decoder = BitPackedDecoder(contents, typeinfos) for event in _decode_event_stream(decoder, message_eventid_typeid, message_event_types, decode_user_id=True): yield event
[ "def", "decode_replay_message_events", "(", "contents", ")", ":", "decoder", "=", "BitPackedDecoder", "(", "contents", ",", "typeinfos", ")", "for", "event", "in", "_decode_event_stream", "(", "decoder", ",", "message_eventid_typeid", ",", "message_event_types", ",", ...
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol61361.py#L413-L420
open-research/sumatra
2ff2a359e11712a7d17cf9346a0b676ab33e2074
sumatra/dependency_finder/neuron.py
python
find_xopened_files
(file_path)
return set(all_paths)
Find all files that are xopened, whether directly or indirectly, by a given Hoc file. Note that this only handles cases whether the path is given directly, not where it has been previously assigned to a strdef.
Find all files that are xopened, whether directly or indirectly, by a given Hoc file. Note that this only handles cases whether the path is given directly, not where it has been previously assigned to a strdef.
[ "Find", "all", "files", "that", "are", "xopened", "whether", "directly", "or", "indirectly", "by", "a", "given", "Hoc", "file", ".", "Note", "that", "this", "only", "handles", "cases", "whether", "the", "path", "is", "given", "directly", "not", "where", "i...
def find_xopened_files(file_path): """ Find all files that are xopened, whether directly or indirectly, by a given Hoc file. Note that this only handles cases whether the path is given directly, not where it has been previously assigned to a strdef. """ xopen_pattern = re.compile(r'xopen\("(?P<path>\w+\.*\w*)"\)') all_paths = [] def find(path, paths): current_dir = os.path.dirname(path) with open(path) as f: new_paths = xopen_pattern.findall(f.read()) # print "-", path, new_paths new_paths = [os.path.join(current_dir, path) for path in new_paths] paths.extend(new_paths) for path in new_paths: find(path, paths) find(os.path.abspath(file_path), all_paths) return set(all_paths)
[ "def", "find_xopened_files", "(", "file_path", ")", ":", "xopen_pattern", "=", "re", ".", "compile", "(", "r'xopen\\(\"(?P<path>\\w+\\.*\\w*)\"\\)'", ")", "all_paths", "=", "[", "]", "def", "find", "(", "path", ",", "paths", ")", ":", "current_dir", "=", "os",...
https://github.com/open-research/sumatra/blob/2ff2a359e11712a7d17cf9346a0b676ab33e2074/sumatra/dependency_finder/neuron.py#L54-L73
Skype4Py/Skype4Py
c48d83f7034109fe46315d45a066126002c6e0d4
Skype4Py/skype.py
python
SkypeEvents.GroupUsers
(self, Group, Count)
This event is caused by a change in a contact group members. :Parameters: Group : `Group` Group object. Count : int Number of group members. :note: This event is different from its Skype4COM equivalent in that the second parameter is number of users instead of `UserCollection` object. This object may be obtained using ``Group.Users`` property.
This event is caused by a change in a contact group members.
[ "This", "event", "is", "caused", "by", "a", "change", "in", "a", "contact", "group", "members", "." ]
def GroupUsers(self, Group, Count): """This event is caused by a change in a contact group members. :Parameters: Group : `Group` Group object. Count : int Number of group members. :note: This event is different from its Skype4COM equivalent in that the second parameter is number of users instead of `UserCollection` object. This object may be obtained using ``Group.Users`` property. """
[ "def", "GroupUsers", "(", "self", ",", "Group", ",", "Count", ")", ":" ]
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L1565-L1577
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pymongo/pool.py
python
SocketInfo.send_message
(self, message, max_doc_size)
Send a raw BSON message or raise ConnectionFailure. If a network exception is raised, the socket is closed.
Send a raw BSON message or raise ConnectionFailure.
[ "Send", "a", "raw", "BSON", "message", "or", "raise", "ConnectionFailure", "." ]
def send_message(self, message, max_doc_size): """Send a raw BSON message or raise ConnectionFailure. If a network exception is raised, the socket is closed. """ if (self.max_bson_size is not None and max_doc_size > self.max_bson_size): raise DocumentTooLarge( "BSON document too large (%d bytes) - the connected server " "supports BSON document sizes up to %d bytes." % (max_doc_size, self.max_bson_size)) try: self.sock.sendall(message) except BaseException as error: self._raise_connection_failure(error)
[ "def", "send_message", "(", "self", ",", "message", ",", "max_doc_size", ")", ":", "if", "(", "self", ".", "max_bson_size", "is", "not", "None", "and", "max_doc_size", ">", "self", ".", "max_bson_size", ")", ":", "raise", "DocumentTooLarge", "(", "\"BSON doc...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pymongo/pool.py#L620-L635
PyCQA/pylint
3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb
pylint/pyreverse/inspector.py
python
interfaces
(node, herited=True, handler_func=_iface_hdlr)
Return an iterator on interfaces implemented by the given class node.
Return an iterator on interfaces implemented by the given class node.
[ "Return", "an", "iterator", "on", "interfaces", "implemented", "by", "the", "given", "class", "node", "." ]
def interfaces(node, herited=True, handler_func=_iface_hdlr): """Return an iterator on interfaces implemented by the given class node.""" try: implements = astroid.bases.Instance(node).getattr("__implements__")[0] except astroid.exceptions.NotFoundError: return if not herited and implements.frame() is not node: return found = set() missing = False for iface in nodes.unpack_infer(implements): if iface is astroid.Uninferable: missing = True continue if iface not in found and handler_func(iface): found.add(iface) yield iface if missing: raise astroid.exceptions.InferenceError()
[ "def", "interfaces", "(", "node", ",", "herited", "=", "True", ",", "handler_func", "=", "_iface_hdlr", ")", ":", "try", ":", "implements", "=", "astroid", ".", "bases", ".", "Instance", "(", "node", ")", ".", "getattr", "(", "\"__implements__\"", ")", "...
https://github.com/PyCQA/pylint/blob/3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb/pylint/pyreverse/inspector.py#L46-L64
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/numpy-1.1.0/numpy/ma/core.py
python
MaskedArray._update_from
(self, obj)
return
Copies some attributes of obj to self.
Copies some attributes of obj to self.
[ "Copies", "some", "attributes", "of", "obj", "to", "self", "." ]
def _update_from(self, obj): """Copies some attributes of obj to self. """ if obj is not None and isinstance(obj,ndarray): _baseclass = type(obj) else: _baseclass = ndarray _basedict = getattr(obj,'_basedict',getattr(obj,'__dict__',{})) _dict = dict(_fill_value=getattr(obj, '_fill_value', None), _hardmask=getattr(obj, '_hardmask', False), _sharedmask=getattr(obj, '_sharedmask', False), _baseclass=getattr(obj,'_baseclass',_baseclass), _basedict=_basedict,) self.__dict__.update(_dict) self.__dict__.update(_basedict) return
[ "def", "_update_from", "(", "self", ",", "obj", ")", ":", "if", "obj", "is", "not", "None", "and", "isinstance", "(", "obj", ",", "ndarray", ")", ":", "_baseclass", "=", "type", "(", "obj", ")", "else", ":", "_baseclass", "=", "ndarray", "_basedict", ...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/numpy-1.1.0/numpy/ma/core.py#L1226-L1241
blampe/IbPy
cba912d2ecc669b0bf2980357ea7942e49c0825e
ib/ext/EWrapper.py
python
EWrapper.execDetails
(self, reqId, contract, execution)
generated source for method execDetails
generated source for method execDetails
[ "generated", "source", "for", "method", "execDetails" ]
def execDetails(self, reqId, contract, execution): """ generated source for method execDetails """
[ "def", "execDetails", "(", "self", ",", "reqId", ",", "contract", ",", "execution", ")", ":" ]
https://github.com/blampe/IbPy/blob/cba912d2ecc669b0bf2980357ea7942e49c0825e/ib/ext/EWrapper.py#L91-L92
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/forms/fields.py
python
DateTimeField.to_python
(self, value)
return from_current_timezone(result)
Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.
Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.
[ "Validates", "that", "the", "input", "can", "be", "converted", "to", "a", "datetime", ".", "Returns", "a", "Python", "datetime", ".", "datetime", "object", "." ]
def to_python(self, value): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone(value) if isinstance(value, datetime.date): result = datetime.datetime(value.year, value.month, value.day) return from_current_timezone(result) if isinstance(value, list): # Input comes from a SplitDateTimeWidget, for example. So, it's two # components: date and time. if len(value) != 2: raise ValidationError(self.error_messages['invalid'], code='invalid') if value[0] in self.empty_values and value[1] in self.empty_values: return None value = '%s %s' % tuple(value) result = super(DateTimeField, self).to_python(value) return from_current_timezone(result)
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "from_current_timezone", "(", "value",...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/forms/fields.py#L464-L485
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/sound/backend_pysound.py
python
SoundPySoundCard._setSndFromArray
(self, thisArray)
For pysoundcard all sounds are ultimately played as an array so other setSound methods are going to call this having created an arr
For pysoundcard all sounds are ultimately played as an array so other setSound methods are going to call this having created an arr
[ "For", "pysoundcard", "all", "sounds", "are", "ultimately", "played", "as", "an", "array", "so", "other", "setSound", "methods", "are", "going", "to", "call", "this", "having", "created", "an", "arr" ]
def _setSndFromArray(self, thisArray): """For pysoundcard all sounds are ultimately played as an array so other setSound methods are going to call this having created an arr """ self._callbacks = _PySoundCallbackClass(sndInstance=self) if defaultOutput is not None and type(defaultOutput) != int: devs = getDevices() if defaultOutput not in devs: raise ValueError("Attempted to set use device {!r} to " "a device that is not available".format(defaultOutput)) else: device = devs[defaultOutput]['id'] else: device = defaultOutput self._stream = soundcard.Stream(samplerate=self.sampleRate, device=device, blocksize=self.bufferSize, channels=1, callback=self._callbacks.fillBuffer) self._snd = self._stream chansIn, chansOut = self._stream.channels if chansOut > 1 and thisArray.ndim == 1: # make mono sound stereo self.sndArr = numpy.resize(thisArray, [2, len(thisArray)]).T else: self.sndArr = numpy.asarray(thisArray) self._nSamples = thisArray.shape[0] # set to run from the start: self.seek(0)
[ "def", "_setSndFromArray", "(", "self", ",", "thisArray", ")", ":", "self", ".", "_callbacks", "=", "_PySoundCallbackClass", "(", "sndInstance", "=", "self", ")", "if", "defaultOutput", "is", "not", "None", "and", "type", "(", "defaultOutput", ")", "!=", "in...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/sound/backend_pysound.py#L285-L313
VIDA-NYU/reprozip
67bbe8d2e22e0493ba0ccc78521729b49dd70a1d
reprozip/reprozip/tracer/trace.py
python
write_configuration
(directory, sort_packages, find_inputs_outputs, overwrite=False)
Writes the canonical YAML configuration file.
Writes the canonical YAML configuration file.
[ "Writes", "the", "canonical", "YAML", "configuration", "file", "." ]
def write_configuration(directory, sort_packages, find_inputs_outputs, overwrite=False): """Writes the canonical YAML configuration file. """ database = directory / 'trace.sqlite3' assert database.is_file() if PY3: # On PY3, connect() only accepts unicode conn = sqlite3.connect(str(database)) else: conn = sqlite3.connect(database.path) conn.row_factory = sqlite3.Row # Reads info from database files, inputs, outputs = get_files(conn) # Identifies which file comes from which package if sort_packages: files, packages = identify_packages(files) else: packages = [] # Writes configuration file config = directory / 'config.yml' distribution = [distro.id(), distro.version()] cur = conn.cursor() if overwrite or not config.exists(): runs = [] # This gets all the top-level processes (p.parent ISNULL) and the first # executed file for that process (sorting by ids, which are # chronological) executions = cur.execute( ''' SELECT e.name, e.argv, e.envp, e.workingdir, p.exitcode FROM processes p JOIN executed_files e ON e.id=( SELECT id FROM executed_files e2 WHERE e2.process=p.id ORDER BY e2.id LIMIT 1 ) WHERE p.parent ISNULL; ''') else: # Loads in previous config runs, oldpkgs, oldfiles = load_config(config, canonical=False, File=TracedFile) # Same query as previous block but only gets last process executions = cur.execute( ''' SELECT e.name, e.argv, e.envp, e.workingdir, p.exitcode FROM processes p JOIN executed_files e ON e.id=( SELECT id FROM executed_files e2 WHERE e2.process=p.id ORDER BY e2.id LIMIT 1 ) WHERE p.parent ISNULL ORDER BY p.id LIMIT 2147483647 OFFSET ?; ''', (len(runs),)) for r_name, r_argv, r_envp, r_workingdir, r_exitcode in executions: # Decodes command-line argv = r_argv.split('\0') if not argv[-1]: argv = argv[:-1] # Decodes environment envp = r_envp.split('\0') if not envp[-1]: envp = envp[:-1] environ = dict(v.split('=', 1) for v in envp) runs.append({'id': "run%d" % len(runs), 'binary': r_name, 'argv': argv, 'workingdir': unicode_(Path(r_workingdir)), 'architecture': platform.machine().lower(), 'distribution': distribution, 'hostname': platform.node(), 'system': [platform.system(), platform.release()], 'environ': environ, 'uid': os.getuid(), 'gid': os.getgid(), 'signal' if r_exitcode & 0x0100 else 'exitcode': r_exitcode & 0xFF}) cur.close() conn.close() if find_inputs_outputs: inputs_outputs = compile_inputs_outputs(runs, inputs, outputs) else: inputs_outputs = {} save_config(config, runs, packages, files, reprozip_version, inputs_outputs) print("Configuration file written in {0!s}".format(config)) print("Edit that file then run the packer -- " "use 'reprozip pack -h' for help")
[ "def", "write_configuration", "(", "directory", ",", "sort_packages", ",", "find_inputs_outputs", ",", "overwrite", "=", "False", ")", ":", "database", "=", "directory", "/", "'trace.sqlite3'", "assert", "database", ".", "is_file", "(", ")", "if", "PY3", ":", ...
https://github.com/VIDA-NYU/reprozip/blob/67bbe8d2e22e0493ba0ccc78521729b49dd70a1d/reprozip/reprozip/tracer/trace.py#L373-L477
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
InfNanRemoveLogitsProcessor.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L105-L106
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/scapy/scapy/crypto/cert.py
python
Cert.verifychain_from_capath
(self, capath, untrusted_file=None)
return cmdres.endswith("\nOK\n") or cmdres.endswith(": OK\n")
Does the same job as .verifychain_from_cafile() but using the list of anchors in capath directory. The directory should contain certificates files in PEM format with associated links as created using c_rehash utility (man c_rehash). As for .verifychain_from_cafile(), a list of untrusted certificates can be passed as a file (concatenation of the certificates in PEM format)
Does the same job as .verifychain_from_cafile() but using the list of anchors in capath directory. The directory should contain certificates files in PEM format with associated links as created using c_rehash utility (man c_rehash).
[ "Does", "the", "same", "job", "as", ".", "verifychain_from_cafile", "()", "but", "using", "the", "list", "of", "anchors", "in", "capath", "directory", ".", "The", "directory", "should", "contain", "certificates", "files", "in", "PEM", "format", "with", "associ...
def verifychain_from_capath(self, capath, untrusted_file=None): """ Does the same job as .verifychain_from_cafile() but using the list of anchors in capath directory. The directory should contain certificates files in PEM format with associated links as created using c_rehash utility (man c_rehash). As for .verifychain_from_cafile(), a list of untrusted certificates can be passed as a file (concatenation of the certificates in PEM format) """ cmd = ["openssl", "verify", "-CApath", capath] if untrusted_file: cmd += ["-untrusted", untrusted_file] try: pemcert = self.output(fmt="PEM") cmdres = self._apply_ossl_cmd(cmd, pemcert) except: return False return cmdres.endswith("\nOK\n") or cmdres.endswith(": OK\n")
[ "def", "verifychain_from_capath", "(", "self", ",", "capath", ",", "untrusted_file", "=", "None", ")", ":", "cmd", "=", "[", "\"openssl\"", ",", "\"verify\"", ",", "\"-CApath\"", ",", "capath", "]", "if", "untrusted_file", ":", "cmd", "+=", "[", "\"-untruste...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/scapy/scapy/crypto/cert.py#L2128-L2147
sixstars/starctf2018
c3eba167d84e7f89f704369c933703951a54f315
web-smart_contract/serve.py
python
get_balance_of_all
()
return calculate_balance(utxos), utxos, tail, contract
[]
def get_balance_of_all(): init() tail = find_blockchain_tail() utxos, contract = calculate_utxo(tail) return calculate_balance(utxos), utxos, tail, contract
[ "def", "get_balance_of_all", "(", ")", ":", "init", "(", ")", "tail", "=", "find_blockchain_tail", "(", ")", "utxos", ",", "contract", "=", "calculate_utxo", "(", "tail", ")", "return", "calculate_balance", "(", "utxos", ")", ",", "utxos", ",", "tail", ","...
https://github.com/sixstars/starctf2018/blob/c3eba167d84e7f89f704369c933703951a54f315/web-smart_contract/serve.py#L333-L337
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/apis/tenants_api.py
python
TenantsApi.get_user_group_with_http_info
(self, id, **kwargs)
return self.api_client.call_api('/tenants/user-groups/{id}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='UserGroupEntity', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
Gets a user group Note: This endpoint is subject to change as NiFi and it's REST API evolve. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_user_group_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: The user group id. (required) :return: UserGroupEntity If the method is called asynchronously, returns the request thread.
Gets a user group Note: This endpoint is subject to change as NiFi and it's REST API evolve. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_user_group_with_http_info(id, callback=callback_function)
[ "Gets", "a", "user", "group", "Note", ":", "This", "endpoint", "is", "subject", "to", "change", "as", "NiFi", "and", "it", "s", "REST", "API", "evolve", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", ...
def get_user_group_with_http_info(self, id, **kwargs): """ Gets a user group Note: This endpoint is subject to change as NiFi and it's REST API evolve. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_user_group_with_http_info(id, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str id: The user group id. (required) :return: UserGroupEntity If the method is called asynchronously, returns the request thread. """ all_params = ['id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_user_group" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params) or (params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_user_group`") collection_formats = {} path_params = {} if 'id' in params: path_params['id'] = params['id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['tokenAuth'] return self.api_client.call_api('/tenants/user-groups/{id}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='UserGroupEntity', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "get_user_group_with_http_info", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "all_params", "=", "[", "'id'", "]", "all_params", ".", "append", "(", "'callback'", ")", "all_params", ".", "append", "(", "'_return_http_data_only'", ")", "a...
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/apis/tenants_api.py#L387-L465
singularity/singularity
a8510bd3996715c7650655892c95039a0f8a29c1
singularity/code/graphics/widget.py
python
causes_redraw
(data_member)
return set_on_change(data_member, "needs_redraw")
Creates a data member that sets needs_redraw to True when changed.
Creates a data member that sets needs_redraw to True when changed.
[ "Creates", "a", "data", "member", "that", "sets", "needs_redraw", "to", "True", "when", "changed", "." ]
def causes_redraw(data_member): """Creates a data member that sets needs_redraw to True when changed.""" return set_on_change(data_member, "needs_redraw")
[ "def", "causes_redraw", "(", "data_member", ")", ":", "return", "set_on_change", "(", "data_member", ",", "\"needs_redraw\"", ")" ]
https://github.com/singularity/singularity/blob/a8510bd3996715c7650655892c95039a0f8a29c1/singularity/code/graphics/widget.py#L76-L78
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/3.0/vlc.py
python
libvlc_video_set_adjust_int
(p_mi, option, value)
return f(p_mi, option, value)
Set adjust option as integer. Options that take a different type value are ignored. Passing libvlc_adjust_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the adjust filter. @param p_mi: libvlc media player instance. @param option: adust option to set, values of L{VideoAdjustOption}. @param value: adjust option value. @version: LibVLC 1.1.1 and later.
Set adjust option as integer. Options that take a different type value are ignored. Passing libvlc_adjust_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the adjust filter.
[ "Set", "adjust", "option", "as", "integer", ".", "Options", "that", "take", "a", "different", "type", "value", "are", "ignored", ".", "Passing", "libvlc_adjust_enable", "as", "option", "value", "has", "the", "side", "effect", "of", "starting", "(", "arg", "!...
def libvlc_video_set_adjust_int(p_mi, option, value): '''Set adjust option as integer. Options that take a different type value are ignored. Passing libvlc_adjust_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the adjust filter. @param p_mi: libvlc media player instance. @param option: adust option to set, values of L{VideoAdjustOption}. @param value: adjust option value. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_set_adjust_int', None) or \ _Cfunction('libvlc_video_set_adjust_int', ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_int) return f(p_mi, option, value)
[ "def", "libvlc_video_set_adjust_int", "(", "p_mi", ",", "option", ",", "value", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_adjust_int'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_adjust_int'", ",", "(", "(", "1", ...
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/3.0/vlc.py#L7386-L7399
megvii-model/SinglePathOneShot
36eed6cf083497ffa9cfe7b8da25bb0b6ba5a452
src/Supernet/utils.py
python
get_parameters
(model)
return groups
[]
def get_parameters(model): group_no_weight_decay = [] group_weight_decay = [] for pname, p in model.named_parameters(): if pname.find('weight') >= 0 and len(p.size()) > 1: # print('include ', pname, p.size()) group_weight_decay.append(p) else: # print('not include ', pname, p.size()) group_no_weight_decay.append(p) assert len(list(model.parameters())) == len( group_weight_decay) + len(group_no_weight_decay) groups = [dict(params=group_weight_decay), dict( params=group_no_weight_decay, weight_decay=0.)] return groups
[ "def", "get_parameters", "(", "model", ")", ":", "group_no_weight_decay", "=", "[", "]", "group_weight_decay", "=", "[", "]", "for", "pname", ",", "p", "in", "model", ".", "named_parameters", "(", ")", ":", "if", "pname", ".", "find", "(", "'weight'", ")...
https://github.com/megvii-model/SinglePathOneShot/blob/36eed6cf083497ffa9cfe7b8da25bb0b6ba5a452/src/Supernet/utils.py#L81-L95
sentinel-hub/sentinelhub-py
d7ad283cf9d4bd4c8c1a8b169cdbe37c5bc8208a
sentinelhub/aws.py
python
AwsProduct.parse_tile_list
(tile_input)
return tile_list
Parses class input and verifies band names. :param tile_input: class input parameter `tile_list` :type tile_input: str or list(str) :return: parsed list of tiles :rtype: list(str) or None
Parses class input and verifies band names.
[ "Parses", "class", "input", "and", "verifies", "band", "names", "." ]
def parse_tile_list(tile_input): """ Parses class input and verifies band names. :param tile_input: class input parameter `tile_list` :type tile_input: str or list(str) :return: parsed list of tiles :rtype: list(str) or None """ if tile_input is None: return None if isinstance(tile_input, str): tile_list = tile_input.split(',') elif isinstance(tile_input, list): tile_list = tile_input.copy() else: raise ValueError('tile_list parameter must be a list of tile names') tile_list = [AwsTile.parse_tile_name(tile_name) for tile_name in tile_list] return tile_list
[ "def", "parse_tile_list", "(", "tile_input", ")", ":", "if", "tile_input", "is", "None", ":", "return", "None", "if", "isinstance", "(", "tile_input", ",", "str", ")", ":", "tile_list", "=", "tile_input", ".", "split", "(", "','", ")", "elif", "isinstance"...
https://github.com/sentinel-hub/sentinelhub-py/blob/d7ad283cf9d4bd4c8c1a8b169cdbe37c5bc8208a/sentinelhub/aws.py#L344-L361
frappe/frappe
b64cab6867dfd860f10ccaf41a4ec04bc890b583
frappe/core/doctype/docshare/docshare.py
python
on_doctype_update
()
Add index in `tabDocShare` for `(user, share_doctype)`
Add index in `tabDocShare` for `(user, share_doctype)`
[ "Add", "index", "in", "tabDocShare", "for", "(", "user", "share_doctype", ")" ]
def on_doctype_update(): """Add index in `tabDocShare` for `(user, share_doctype)`""" frappe.db.add_index("DocShare", ["user", "share_doctype"]) frappe.db.add_index("DocShare", ["share_doctype", "share_name"])
[ "def", "on_doctype_update", "(", ")", ":", "frappe", ".", "db", ".", "add_index", "(", "\"DocShare\"", ",", "[", "\"user\"", ",", "\"share_doctype\"", "]", ")", "frappe", ".", "db", ".", "add_index", "(", "\"DocShare\"", ",", "[", "\"share_doctype\"", ",", ...
https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/core/doctype/docshare/docshare.py#L65-L68
mthbernardes/ARTLAS
e5fdd8d6b01fb36adada8a79687597053b6b8332
artlas_aws_cli.py
python
ARTLAS.owasp
(self, path)
[]
def owasp(self, path): for filtro in self.rules['filters']['filter']: if filtro['id'] in self.white_rules: continue try: if re.search(filtro['rule'], path): return filtro except: continue
[ "def", "owasp", "(", "self", ",", "path", ")", ":", "for", "filtro", "in", "self", ".", "rules", "[", "'filters'", "]", "[", "'filter'", "]", ":", "if", "filtro", "[", "'id'", "]", "in", "self", ".", "white_rules", ":", "continue", "try", ":", "if"...
https://github.com/mthbernardes/ARTLAS/blob/e5fdd8d6b01fb36adada8a79687597053b6b8332/artlas_aws_cli.py#L105-L113
enthought/mayavi
2103a273568b8f0bd62328801aafbd6252543ae8
tvtk/pyface/scene_model.py
python
SceneModel._update_view
(self, x, y, z, vx, vy, vz)
Used internally to set the view.
Used internally to set the view.
[ "Used", "internally", "to", "set", "the", "view", "." ]
def _update_view(self, x, y, z, vx, vy, vz): """Used internally to set the view.""" if self.scene_editor is not None: self.scene_editor._update_view(x, y, z, vx, vy, vz)
[ "def", "_update_view", "(", "self", ",", "x", ",", "y", ",", "z", ",", "vx", ",", "vy", ",", "vz", ")", ":", "if", "self", ".", "scene_editor", "is", "not", "None", ":", "self", ".", "scene_editor", ".", "_update_view", "(", "x", ",", "y", ",", ...
https://github.com/enthought/mayavi/blob/2103a273568b8f0bd62328801aafbd6252543ae8/tvtk/pyface/scene_model.py#L295-L298
NVIDIA/Megatron-LM
9a8b89acd8f6ba096860170d0e30ddc0bc2bacd4
megatron/model/realm_model.py
python
IREncoderBertModel.load_state_dict
(self, state_dict, strict=True)
Customized load.
Customized load.
[ "Customized", "load", "." ]
def load_state_dict(self, state_dict, strict=True): """Customized load.""" self.language_model.load_state_dict( state_dict[self._language_model_key], strict=strict) self.ict_head.load_state_dict( state_dict[self._ict_head_key], strict=strict)
[ "def", "load_state_dict", "(", "self", ",", "state_dict", ",", "strict", "=", "True", ")", ":", "self", ".", "language_model", ".", "load_state_dict", "(", "state_dict", "[", "self", ".", "_language_model_key", "]", ",", "strict", "=", "strict", ")", "self",...
https://github.com/NVIDIA/Megatron-LM/blob/9a8b89acd8f6ba096860170d0e30ddc0bc2bacd4/megatron/model/realm_model.py#L197-L202
minimaxir/person-blocker
82cc1bab629ff9faf610861bf94660d0131c38ec
model.py
python
compose_image_meta
(image_id, image_shape, window, active_class_ids)
return meta
Takes attributes of an image and puts them in one 1D array. image_id: An int ID of the image. Useful for debugging. image_shape: [height, width, channels] window: (y1, x1, y2, x2) in pixels. The area of the image where the real image is (excluding the padding) active_class_ids: List of class_ids available in the dataset from which the image came. Useful if training on images from multiple datasets where not all classes are present in all datasets.
Takes attributes of an image and puts them in one 1D array.
[ "Takes", "attributes", "of", "an", "image", "and", "puts", "them", "in", "one", "1D", "array", "." ]
def compose_image_meta(image_id, image_shape, window, active_class_ids): """Takes attributes of an image and puts them in one 1D array. image_id: An int ID of the image. Useful for debugging. image_shape: [height, width, channels] window: (y1, x1, y2, x2) in pixels. The area of the image where the real image is (excluding the padding) active_class_ids: List of class_ids available in the dataset from which the image came. Useful if training on images from multiple datasets where not all classes are present in all datasets. """ meta = np.array( [image_id] + # size=1 list(image_shape) + # size=3 list(window) + # size=4 (y1, x1, y2, x2) in image cooredinates list(active_class_ids) # size=num_classes ) return meta
[ "def", "compose_image_meta", "(", "image_id", ",", "image_shape", ",", "window", ",", "active_class_ids", ")", ":", "meta", "=", "np", ".", "array", "(", "[", "image_id", "]", "+", "# size=1", "list", "(", "image_shape", ")", "+", "# size=3", "list", "(", ...
https://github.com/minimaxir/person-blocker/blob/82cc1bab629ff9faf610861bf94660d0131c38ec/model.py#L2491-L2508
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/tower-alfred-workflow/alp/fuzzy.py
python
order
(x, NoneIsLast=True, decreasing=False)
return ix
Returns the ordering of the elements of x. The list [ x[j] for j in order(x) ] is a sorted version of x. Missing values in x are indicated by None. If NoneIsLast is true, then missing values are ordered to be at the end. Otherwise, they are ordered at the beginning.
Returns the ordering of the elements of x. The list [ x[j] for j in order(x) ] is a sorted version of x.
[ "Returns", "the", "ordering", "of", "the", "elements", "of", "x", ".", "The", "list", "[", "x", "[", "j", "]", "for", "j", "in", "order", "(", "x", ")", "]", "is", "a", "sorted", "version", "of", "x", "." ]
def order(x, NoneIsLast=True, decreasing=False): """ Returns the ordering of the elements of x. The list [ x[j] for j in order(x) ] is a sorted version of x. Missing values in x are indicated by None. If NoneIsLast is true, then missing values are ordered to be at the end. Otherwise, they are ordered at the beginning. """ omitNone = False if NoneIsLast is None: NoneIsLast = True omitNone = True n = len(x) ix = range(n) if None not in x: ix.sort(reverse=decreasing, key=lambda j: x[j]) else: # Handle None values properly. def key(i, x=x): elem = x[i] # Valid values are True or False only. if decreasing == NoneIsLast: return not(elem is None), elem else: return elem is None, elem ix = range(n) ix.sort(key=key, reverse=decreasing) if omitNone: n = len(x) for i in range(n-1, -1, -1): if x[ix[i]] is None: n -= 1 return ix[:n] return ix
[ "def", "order", "(", "x", ",", "NoneIsLast", "=", "True", ",", "decreasing", "=", "False", ")", ":", "omitNone", "=", "False", "if", "NoneIsLast", "is", "None", ":", "NoneIsLast", "=", "True", "omitNone", "=", "True", "n", "=", "len", "(", "x", ")", ...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/tower-alfred-workflow/alp/fuzzy.py#L6-L42
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/more_itertools/more.py
python
peekable.__iter__
(self)
return self
[]
def __iter__(self): return self
[ "def", "__iter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/more_itertools/more.py#L297-L298
PythonJS/PythonJS
591a80afd8233fb715493591db2b68f1748558d9
pythonjs/lib/python2.7/codecs.py
python
StreamReaderWriter.next
(self)
return self.reader.next()
Return the next decoded line from the input stream.
Return the next decoded line from the input stream.
[ "Return", "the", "next", "decoded", "line", "from", "the", "input", "stream", "." ]
def next(self): """ Return the next decoded line from the input stream.""" return self.reader.next()
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "reader", ".", "next", "(", ")" ]
https://github.com/PythonJS/PythonJS/blob/591a80afd8233fb715493591db2b68f1748558d9/pythonjs/lib/python2.7/codecs.py#L681-L684
whipper-team/whipper
18a41b6c2880e577f9f1d7b1b6e7df0be7371378
whipper/extern/task/task.py
python
BaseMultiTask.stopped
(self, task)
Subclasses should chain up to me at the end of their implementation. They should fall through to chaining up if there is an exception.
Subclasses should chain up to me at the end of their implementation.
[ "Subclasses", "should", "chain", "up", "to", "me", "at", "the", "end", "of", "their", "implementation", "." ]
def stopped(self, task): # noqa: D401 """ Subclasses should chain up to me at the end of their implementation. They should fall through to chaining up if there is an exception. """ self.debug('BaseMultiTask.stopped: task %r (%d of %d)', task, self.tasks.index(task) + 1, len(self.tasks)) if task.exception: self.warning('BaseMultiTask.stopped: exception %r', task.exceptionMessage) self.exception = task.exception self.exceptionMessage = task.exceptionMessage self.stop() return if self._task == len(self.tasks): self.debug('BaseMultiTask.stopped: all tasks done') self.stop() return # pick another self.debug('BaseMultiTask.stopped: pick next task') self.schedule(0, self.next)
[ "def", "stopped", "(", "self", ",", "task", ")", ":", "# noqa: D401", "self", ".", "debug", "(", "'BaseMultiTask.stopped: task %r (%d of %d)'", ",", "task", ",", "self", ".", "tasks", ".", "index", "(", "task", ")", "+", "1", ",", "len", "(", "self", "."...
https://github.com/whipper-team/whipper/blob/18a41b6c2880e577f9f1d7b1b6e7df0be7371378/whipper/extern/task/task.py#L366-L389
dagwieers/mrepo
a55cbc737d8bade92070d38e4dbb9a24be4b477f
rhn/UserDictCase.py
python
UserDictCase.dict
(self)
return self.get_hash()
[]
def dict(self): return self.get_hash()
[ "def", "dict", "(", "self", ")", ":", "return", "self", ".", "get_hash", "(", ")" ]
https://github.com/dagwieers/mrepo/blob/a55cbc737d8bade92070d38e4dbb9a24be4b477f/rhn/UserDictCase.py#L61-L62
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/mimetypes.py
python
guess_all_extensions
(type, strict=True)
return _db.guess_all_extensions(type, strict)
Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
Guess the extensions for a file based on its MIME type.
[ "Guess", "the", "extensions", "for", "a", "file", "based", "on", "its", "MIME", "type", "." ]
def guess_all_extensions(type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_all_extensions(type, strict)
[ "def", "guess_all_extensions", "(", "type", ",", "strict", "=", "True", ")", ":", "if", "_db", "is", "None", ":", "init", "(", ")", "return", "_db", ".", "guess_all_extensions", "(", "type", ",", "strict", ")" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/mimetypes.py#L298-L313
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/simos/linux.py
python
SimLinux._read_gs_register_x86
(concrete_target)
return concrete_target.execute_shellcode(read_gs0_x64, exfiltration_reg)
Injects a small shellcode to leak the gs segment register address. In Linux x86 this address is pointed by gs[0] :param concrete_target: ConcreteTarget which will be used to get the gs register address :return: gs register address :rtype :str
Injects a small shellcode to leak the gs segment register address. In Linux x86 this address is pointed by gs[0] :param concrete_target: ConcreteTarget which will be used to get the gs register address :return: gs register address :rtype :str
[ "Injects", "a", "small", "shellcode", "to", "leak", "the", "gs", "segment", "register", "address", ".", "In", "Linux", "x86", "this", "address", "is", "pointed", "by", "gs", "[", "0", "]", ":", "param", "concrete_target", ":", "ConcreteTarget", "which", "w...
def _read_gs_register_x86(concrete_target): ''' Injects a small shellcode to leak the gs segment register address. In Linux x86 this address is pointed by gs[0] :param concrete_target: ConcreteTarget which will be used to get the gs register address :return: gs register address :rtype :str ''' # register used to read the value of the segment register exfiltration_reg = "eax" # instruction to inject for reading the value at segment value = offset read_gs0_x64 = b"\x65\xA1\x00\x00\x00\x00\x90\x90\x90\x90" # mov eax, gs:[0] return concrete_target.execute_shellcode(read_gs0_x64, exfiltration_reg)
[ "def", "_read_gs_register_x86", "(", "concrete_target", ")", ":", "# register used to read the value of the segment register", "exfiltration_reg", "=", "\"eax\"", "# instruction to inject for reading the value at segment value = offset", "read_gs0_x64", "=", "b\"\\x65\\xA1\\x00\\x00\\x00\\...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/simos/linux.py#L458-L469
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/cli/scheduler/__init__.py
python
init
()
return run
Return top level command handler.
Return top level command handler.
[ "Return", "top", "level", "command", "handler", "." ]
def init(): """Return top level command handler.""" @click.group(cls=cli.make_commands(__name__)) @click.option( '--cell', help='Treadmill cell', envvar='TREADMILL_CELL', callback=cli.handle_context_opt, expose_value=False, required=True ) @click.option( '--api-service-principal', required=False, envvar='TREADMILL_API_SERVICE_PRINCIPAL', callback=cli.handle_context_opt, help='API service principal for SPNEGO auth (default HTTP)', expose_value=False ) def run(): """Report scheduler state. """ return run
[ "def", "init", "(", ")", ":", "@", "click", ".", "group", "(", "cls", "=", "cli", ".", "make_commands", "(", "__name__", ")", ")", "@", "click", ".", "option", "(", "'--cell'", ",", "help", "=", "'Treadmill cell'", ",", "envvar", "=", "'TREADMILL_CELL'...
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/cli/scheduler/__init__.py#L72-L95
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/chemical.py
python
Chemical.isobaric_expansion
(self)
return phase_select_property(phase=self.phase, l=Chemical.isobaric_expansion_l, g=Chemical.isobaric_expansion_g, self=self)
r'''Isobaric (constant-pressure) expansion of the chemical at its current phase and temperature, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Examples -------- Radical change in value just above and below the critical temperature of water: >>> Chemical('water', T=647.1, P=22048320.0).isobaric_expansion 0.34074205839222449 >>> Chemical('water', T=647.2, P=22048320.0).isobaric_expansion 0.18143324022215077
r'''Isobaric (constant-pressure) expansion of the chemical at its current phase and temperature, in units of [1/K].
[ "r", "Isobaric", "(", "constant", "-", "pressure", ")", "expansion", "of", "the", "chemical", "at", "its", "current", "phase", "and", "temperature", "in", "units", "of", "[", "1", "/", "K", "]", "." ]
def isobaric_expansion(self): r'''Isobaric (constant-pressure) expansion of the chemical at its current phase and temperature, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Examples -------- Radical change in value just above and below the critical temperature of water: >>> Chemical('water', T=647.1, P=22048320.0).isobaric_expansion 0.34074205839222449 >>> Chemical('water', T=647.2, P=22048320.0).isobaric_expansion 0.18143324022215077 ''' return phase_select_property(phase=self.phase, l=Chemical.isobaric_expansion_l, g=Chemical.isobaric_expansion_g, self=self)
[ "def", "isobaric_expansion", "(", "self", ")", ":", "return", "phase_select_property", "(", "phase", "=", "self", ".", "phase", ",", "l", "=", "Chemical", ".", "isobaric_expansion_l", ",", "g", "=", "Chemical", ".", "isobaric_expansion_g", ",", "self", "=", ...
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/chemical.py#L2998-L3019
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/nltk/metrics/scores.py
python
log_likelihood
(reference, test)
return total_likelihood/len(reference)
Given a list of reference values and a corresponding list of test probability distributions, return the average log likelihood of the reference values, given the probability distributions. :param reference: A list of reference values :type reference: list :param test: A list of probability distributions over values to compare against the corresponding reference values. :type test: list(ProbDistI)
Given a list of reference values and a corresponding list of test probability distributions, return the average log likelihood of the reference values, given the probability distributions.
[ "Given", "a", "list", "of", "reference", "values", "and", "a", "corresponding", "list", "of", "test", "probability", "distributions", "return", "the", "average", "log", "likelihood", "of", "the", "reference", "values", "given", "the", "probability", "distributions...
def log_likelihood(reference, test): """ Given a list of reference values and a corresponding list of test probability distributions, return the average log likelihood of the reference values, given the probability distributions. :param reference: A list of reference values :type reference: list :param test: A list of probability distributions over values to compare against the corresponding reference values. :type test: list(ProbDistI) """ if len(reference) != len(test): raise ValueError("Lists must have the same length.") # Return the average value of dist.logprob(val). total_likelihood = sum(dist.logprob(val) for (val, dist) in izip(reference, test)) return total_likelihood/len(reference)
[ "def", "log_likelihood", "(", "reference", ",", "test", ")", ":", "if", "len", "(", "reference", ")", "!=", "len", "(", "test", ")", ":", "raise", "ValueError", "(", "\"Lists must have the same length.\"", ")", "# Return the average value of dist.logprob(val).", "to...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/nltk/metrics/scores.py#L117-L135