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
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/lib-tk/Tkinter.py
python
Wm.wm_overrideredirect
(self, boolean=None)
return self._getboolean(self.tk.call( 'wm', 'overrideredirect', self._w, boolean))
Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given.
Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given.
[ "Instruct", "the", "window", "manager", "to", "ignore", "this", "widget", "if", "BOOLEAN", "is", "given", "with", "1", ".", "Return", "the", "current", "value", "if", "None", "is", "given", "." ]
def wm_overrideredirect(self, boolean=None): """Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given.""" return self._getboolean(self.tk.call( 'wm', 'overrideredirect', self._w, boolean))
[ "def", "wm_overrideredirect", "(", "self", ",", "boolean", "=", "None", ")", ":", "return", "self", ".", "_getboolean", "(", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'overrideredirect'", ",", "self", ".", "_w", ",", "boolean", ")", ")" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/Tkinter.py#L1745-L1750
pik-copan/pyunicorn
b18316fc08ef34b434a1a4d69dfe3e57e24435ee
pyunicorn/core/spatial_network.py
python
SpatialNetwork.max_link_distance
(self)
return maximum_link_distance
Return maximum angular geodesic link distances. .. note:: Does not use directionality information. **Example:** >>> SpatialNetwork.SmallTestNetwork().max_link_distance() array([27.95085, 16.77051, 11.18034, 16.77051, 22.36068, 27.95085], dtype=float32) :rtype: 1D Numpy array [index] :return: the maximum link distance sequence.
Return maximum angular geodesic link distances.
[ "Return", "maximum", "angular", "geodesic", "link", "distances", "." ]
def max_link_distance(self): """ Return maximum angular geodesic link distances. .. note:: Does not use directionality information. **Example:** >>> SpatialNetwork.SmallTestNetwork().max_link_distance() array([27.95085, 16.77051, 11.18034, 16.77051, 22.36068, 27.95085], dtype=float32) :rtype: 1D Numpy array [index] :return: the maximum link distance sequence. """ if self.silence_level <= 1: print("Calculating maximum link distance...") A = self.undirected_adjacency().A D = self.grid.distance() maximum_link_distance = (D * A).max(axis=1) return maximum_link_distance
[ "def", "max_link_distance", "(", "self", ")", ":", "if", "self", ".", "silence_level", "<=", "1", ":", "print", "(", "\"Calculating maximum link distance...\"", ")", "A", "=", "self", ".", "undirected_adjacency", "(", ")", ".", "A", "D", "=", "self", ".", ...
https://github.com/pik-copan/pyunicorn/blob/b18316fc08ef34b434a1a4d69dfe3e57e24435ee/pyunicorn/core/spatial_network.py#L647-L670
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/difflib.py
python
Differ._qformat
(self, aline, bline, atags, btags)
r""" Format "?" output and deal with leading tabs. Example: >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n', ... ' ^ ^ ^ ', ' ^ ^ ^ ') >>> for line in results: print repr(line) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \tabcdefGhijkl\n' '? \t ^ ^ ^\n'
r""" Format "?" output and deal with leading tabs.
[ "r", "Format", "?", "output", "and", "deal", "with", "leading", "tabs", "." ]
def _qformat(self, aline, bline, atags, btags): r""" Format "?" output and deal with leading tabs. Example: >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n', ... ' ^ ^ ^ ', ' ^ ^ ^ ') >>> for line in results: print repr(line) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \tabcdefGhijkl\n' '? \t ^ ^ ^\n' """ # Can hurt, but will probably help most of the time. common = min(_count_leading(aline, "\t"), _count_leading(bline, "\t")) common = min(common, _count_leading(atags[:common], " ")) common = min(common, _count_leading(btags[:common], " ")) atags = atags[common:].rstrip() btags = btags[common:].rstrip() yield "- " + aline if atags: yield "? %s%s\n" % ("\t" * common, atags) yield "+ " + bline if btags: yield "? %s%s\n" % ("\t" * common, btags)
[ "def", "_qformat", "(", "self", ",", "aline", ",", "bline", ",", "atags", ",", "btags", ")", ":", "# Can hurt, but will probably help most of the time.", "common", "=", "min", "(", "_count_leading", "(", "aline", ",", "\"\\t\"", ")", ",", "_count_leading", "(", ...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/difflib.py#L1056-L1087
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pygments/lexers/clean.py
python
CleanLexer.store_indent
(lexer, match, ctx)
[]
def store_indent(lexer, match, ctx): ctx.indent, _ = CleanLexer.indent_len(match.group(0)) ctx.pos = match.end() yield match.start(), Text, match.group(0)
[ "def", "store_indent", "(", "lexer", ",", "match", ",", "ctx", ")", ":", "ctx", ".", "indent", ",", "_", "=", "CleanLexer", ".", "indent_len", "(", "match", ".", "group", "(", "0", ")", ")", "ctx", ".", "pos", "=", "match", ".", "end", "(", ")", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pygments/lexers/clean.py#L59-L62
brianwrf/hackUtils
168123350d93b040fa0c437c9d59faf8fa65d8e6
bs4/element.py
python
Tag.string
(self)
return child.string
Convenience property to get the single string within this tag. :Return: If this tag has a single string child, return value is that string. If this tag has no children, or more than one child, return value is None. If this tag has one child tag, return value is the 'string' attribute of the child tag, recursively.
Convenience property to get the single string within this tag.
[ "Convenience", "property", "to", "get", "the", "single", "string", "within", "this", "tag", "." ]
def string(self): """Convenience property to get the single string within this tag. :Return: If this tag has a single string child, return value is that string. If this tag has no children, or more than one child, return value is None. If this tag has one child tag, return value is the 'string' attribute of the child tag, recursively. """ if len(self.contents) != 1: return None child = self.contents[0] if isinstance(child, NavigableString): return child return child.string
[ "def", "string", "(", "self", ")", ":", "if", "len", "(", "self", ".", "contents", ")", "!=", "1", ":", "return", "None", "child", "=", "self", ".", "contents", "[", "0", "]", "if", "isinstance", "(", "child", ",", "NavigableString", ")", ":", "ret...
https://github.com/brianwrf/hackUtils/blob/168123350d93b040fa0c437c9d59faf8fa65d8e6/bs4/element.py#L800-L814
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/permutation.py
python
Permutations_nk.cardinality
(self)
return ZZ.zero()
EXAMPLES:: sage: Permutations(3,0).cardinality() 1 sage: Permutations(3,1).cardinality() 3 sage: Permutations(3,2).cardinality() 6 sage: Permutations(3,3).cardinality() 6 sage: Permutations(3,4).cardinality() 0
EXAMPLES::
[ "EXAMPLES", "::" ]
def cardinality(self) -> Integer: """ EXAMPLES:: sage: Permutations(3,0).cardinality() 1 sage: Permutations(3,1).cardinality() 3 sage: Permutations(3,2).cardinality() 6 sage: Permutations(3,3).cardinality() 6 sage: Permutations(3,4).cardinality() 0 """ if 0 <= self._k <= self.n: return factorial(self.n) // factorial(self.n - self._k) return ZZ.zero()
[ "def", "cardinality", "(", "self", ")", "->", "Integer", ":", "if", "0", "<=", "self", ".", "_k", "<=", "self", ".", "n", ":", "return", "factorial", "(", "self", ".", "n", ")", "//", "factorial", "(", "self", ".", "n", "-", "self", ".", "_k", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/permutation.py#L5530-L5547
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
markdown/markdown2pdf/reportlab/graphics/widgetbase.py
python
TwoFaces.draw
(self)
return shapes.Group(self.faceOne, self.faceTwo)
Just return a group
Just return a group
[ "Just", "return", "a", "group" ]
def draw(self): """Just return a group""" return shapes.Group(self.faceOne, self.faceTwo)
[ "def", "draw", "(", "self", ")", ":", "return", "shapes", ".", "Group", "(", "self", ".", "faceOne", ",", "self", ".", "faceTwo", ")" ]
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/markdown/markdown2pdf/reportlab/graphics/widgetbase.py#L431-L433
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_probe.py
python
V1Probe.success_threshold
(self, success_threshold)
Sets the success_threshold of this V1Probe. Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1. # noqa: E501 :param success_threshold: The success_threshold of this V1Probe. # noqa: E501 :type: int
Sets the success_threshold of this V1Probe.
[ "Sets", "the", "success_threshold", "of", "this", "V1Probe", "." ]
def success_threshold(self, success_threshold): """Sets the success_threshold of this V1Probe. Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1. # noqa: E501 :param success_threshold: The success_threshold of this V1Probe. # noqa: E501 :type: int """ self._success_threshold = success_threshold
[ "def", "success_threshold", "(", "self", ",", "success_threshold", ")", ":", "self", ".", "_success_threshold", "=", "success_threshold" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_probe.py#L213-L222
tomerfiliba/plumbum
20cdda5e8bbd9f83d64b154f6b4fcd28216c63e1
plumbum/path/base.py
python
Path.__div__
(self, other)
return self.join(other)
Joins two paths
Joins two paths
[ "Joins", "two", "paths" ]
def __div__(self, other): """Joins two paths""" return self.join(other)
[ "def", "__div__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "join", "(", "other", ")" ]
https://github.com/tomerfiliba/plumbum/blob/20cdda5e8bbd9f83d64b154f6b4fcd28216c63e1/plumbum/path/base.py#L34-L36
Abjad/abjad
d0646dfbe83db3dc5ab268f76a0950712b87b7fd
abjad/typedcollections.py
python
TypedFrozenset.__sub__
(self, argument)
return result
Subtracts ``argument`` from typed frozen set. Returns new typed frozen set.
Subtracts ``argument`` from typed frozen set.
[ "Subtracts", "argument", "from", "typed", "frozen", "set", "." ]
def __sub__(self, argument): """ Subtracts ``argument`` from typed frozen set. Returns new typed frozen set. """ argument = type(self)(argument) result = self._collection.__sub__(argument._collection) result = type(self)(result) return result
[ "def", "__sub__", "(", "self", ",", "argument", ")", ":", "argument", "=", "type", "(", "self", ")", "(", "argument", ")", "result", "=", "self", ".", "_collection", ".", "__sub__", "(", "argument", ".", "_collection", ")", "result", "=", "type", "(", ...
https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/typedcollections.py#L502-L511
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/nntplib.py
python
NNTP.artcmd
(self, line, file=None)
return resp, nr, id, list
Internal: process a HEAD, BODY or ARTICLE command.
Internal: process a HEAD, BODY or ARTICLE command.
[ "Internal", ":", "process", "a", "HEAD", "BODY", "or", "ARTICLE", "command", "." ]
def artcmd(self, line, file=None): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, list = self.longcmd(line, file) resp, nr, id = self.statparse(resp) return resp, nr, id, list
[ "def", "artcmd", "(", "self", ",", "line", ",", "file", "=", "None", ")", ":", "resp", ",", "list", "=", "self", ".", "longcmd", "(", "line", ",", "file", ")", "resp", ",", "nr", ",", "id", "=", "self", ".", "statparse", "(", "resp", ")", "retu...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/nntplib.py#L405-L409
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/pip/_vendor/packaging/specifiers.py
python
BaseSpecifier.__eq__
(self, other)
Returns a boolean representing whether or not the two Specifier like objects are equal.
Returns a boolean representing whether or not the two Specifier like objects are equal.
[ "Returns", "a", "boolean", "representing", "whether", "or", "not", "the", "two", "Specifier", "like", "objects", "are", "equal", "." ]
def __eq__(self, other): """ Returns a boolean representing whether or not the two Specifier like objects are equal. """
[ "def", "__eq__", "(", "self", ",", "other", ")", ":" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/_vendor/packaging/specifiers.py#L37-L41
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/runners/wine.py
python
wine.run_winetricks
(self, *args)
Run winetricks in the current context
Run winetricks in the current context
[ "Run", "winetricks", "in", "the", "current", "context" ]
def run_winetricks(self, *args): """Run winetricks in the current context""" self.prelaunch() winetricks( "", prefix=self.prefix_path, wine_path=self.get_executable(), config=self, env=self.get_env(os_env=True) )
[ "def", "run_winetricks", "(", "self", ",", "*", "args", ")", ":", "self", ".", "prelaunch", "(", ")", "winetricks", "(", "\"\"", ",", "prefix", "=", "self", ".", "prefix_path", ",", "wine_path", "=", "self", ".", "get_executable", "(", ")", ",", "confi...
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/runners/wine.py#L662-L667
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cwp/v20180228/models.py
python
BaselineEventLevelInfo.__init__
(self)
r""" :param EventLevel: 危害等级:1-低危;2-中危;3-高危;4-严重 注意:此字段可能返回 null,表示取不到有效值。 :type EventLevel: int :param EventCount: 漏洞数量 注意:此字段可能返回 null,表示取不到有效值。 :type EventCount: int
r""" :param EventLevel: 危害等级:1-低危;2-中危;3-高危;4-严重 注意:此字段可能返回 null,表示取不到有效值。 :type EventLevel: int :param EventCount: 漏洞数量 注意:此字段可能返回 null,表示取不到有效值。 :type EventCount: int
[ "r", ":", "param", "EventLevel", ":", "危害等级:1", "-", "低危;2", "-", "中危;3", "-", "高危;4", "-", "严重", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "EventLevel", ":", "int", ":", "param", "EventCount", ":", "漏洞数量", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "...
def __init__(self): r""" :param EventLevel: 危害等级:1-低危;2-中危;3-高危;4-严重 注意:此字段可能返回 null,表示取不到有效值。 :type EventLevel: int :param EventCount: 漏洞数量 注意:此字段可能返回 null,表示取不到有效值。 :type EventCount: int """ self.EventLevel = None self.EventCount = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "EventLevel", "=", "None", "self", ".", "EventCount", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cwp/v20180228/models.py#L2653-L2663
NVIDIA/OpenSeq2Seq
8681d381ed404fde516e2c1b823de5a213c59aba
scripts/calibrate_model.py
python
calibrate
(source, target)
return mean_start_shift, mean_end_shift
This function calculates the mean start and end shift needed for your model to get word to speech alignments
This function calculates the mean start and end shift needed for your model to get word to speech alignments
[ "This", "function", "calculates", "the", "mean", "start", "and", "end", "shift", "needed", "for", "your", "model", "to", "get", "word", "to", "speech", "alignments" ]
def calibrate(source, target): """This function calculates the mean start and end shift needed for your model to get word to speech alignments """ print("calibrating {}".format(source)) start_shift = [] end_shift = [] dump = pickle.load(open(source, "rb")) results = dump["logits"] vocab = dump["vocab"] step_size = dump["step_size"] blank_idx = len(vocab) with open(target, "r") as read_file: target = json.load(read_file) for wave_file in results: transcript, start, end = ctc_greedy_decoder(results[wave_file], vocab, step_size, blank_idx, 0, 0) words = transcript.split(" ") k = 0 print(words) alignments = [] for new_word in words: alignments.append({"word": new_word, "start": start[k], "end": end[k]}) k += 1 if len(target[wave_file]["words"]) == len(words): for i, new_word in enumerate(target[wave_file]["words"]): if new_word["case"] == "success" and \ new_word["alignedWord"] == alignments[i]["word"]: start_shift.append(new_word["start"] - alignments[i]["start"]) end_shift.append(new_word["end"] - alignments[i]["end"]) mean_start_shift = np.mean(start_shift) mean_end_shift = np.mean(end_shift) return mean_start_shift, mean_end_shift
[ "def", "calibrate", "(", "source", ",", "target", ")", ":", "print", "(", "\"calibrating {}\"", ".", "format", "(", "source", ")", ")", "start_shift", "=", "[", "]", "end_shift", "=", "[", "]", "dump", "=", "pickle", ".", "load", "(", "open", "(", "s...
https://github.com/NVIDIA/OpenSeq2Seq/blob/8681d381ed404fde516e2c1b823de5a213c59aba/scripts/calibrate_model.py#L83-L116
knownsec/VxPwn
6555f49675f0317d4a48568a89d0ec4332658402
sulley/sulley/sessions.py
python
session.fuzz
(self, this_node=None, path=[])
Call this routine to get the ball rolling. No arguments are necessary as they are both utilized internally during the recursive traversal of the session graph. @type this_node: request (node) @param this_node: (Optional, def=None) Current node that is being fuzzed. @type path: List @param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed.
Call this routine to get the ball rolling. No arguments are necessary as they are both utilized internally during the recursive traversal of the session graph.
[ "Call", "this", "routine", "to", "get", "the", "ball", "rolling", ".", "No", "arguments", "are", "necessary", "as", "they", "are", "both", "utilized", "internally", "during", "the", "recursive", "traversal", "of", "the", "session", "graph", "." ]
def fuzz (self, this_node=None, path=[]): ''' Call this routine to get the ball rolling. No arguments are necessary as they are both utilized internally during the recursive traversal of the session graph. @type this_node: request (node) @param this_node: (Optional, def=None) Current node that is being fuzzed. @type path: List @param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed. ''' # if no node is specified, then we start from the root node and initialize the session. if not this_node: # we can't fuzz if we don't have at least one target and one request. if not self.targets: raise sex.SullyRuntimeError("NO TARGETS SPECIFIED IN SESSION") if not self.edges_from(self.root.id): raise sex.SullyRuntimeError("NO REQUESTS SPECIFIED IN SESSION") this_node = self.root try: self.server_init() except: return # TODO: complete parallel fuzzing, will likely have to thread out each target target = self.targets[0] # step through every edge from the current node. for edge in self.edges_from(this_node.id): # the destination node is the one actually being fuzzed. self.fuzz_node = self.nodes[edge.dst] num_mutations = self.fuzz_node.num_mutations() # keep track of the path as we fuzz through it, don't count the root node. # we keep track of edges as opposed to nodes because if there is more then one path through a set of # given nodes we don't want any ambiguity. path.append(edge) current_path = " -> ".join([self.nodes[e.src].name for e in path[1:]]) current_path += " -> %s" % self.fuzz_node.name self.logger.info("current fuzz path: %s" % current_path) self.logger.info("fuzzed %d of %d total cases" % (self.total_mutant_index, self.total_num_mutations)) done_with_fuzz_node = False crash_count = 0 # loop through all possible mutations of the fuzz node. while not done_with_fuzz_node: # if we need to pause, do so. self.pause() # if we have exhausted the mutations of the fuzz node, break out of the while(1). # note: when mutate() returns False, the node has been reverted to the default (valid) state. if not self.fuzz_node.mutate(): self.logger.error("all possible mutations for current fuzz node exhausted") done_with_fuzz_node = True continue # make a record in the session that a mutation was made. self.total_mutant_index += 1 # if we've hit the restart interval, restart the target. if self.restart_interval and self.total_mutant_index % self.restart_interval == 0: self.logger.error("restart interval of %d reached" % self.restart_interval) self.restart_target(target) # exception error handling routine, print log message and restart target. def error_handler (e, msg, target, sock=None): if sock: sock.close() msg += "\nException caught: %s" % repr(e) msg += "\nRestarting target and trying again" self.logger.critical(msg) self.restart_target(target) # if we don't need to skip the current test case. if self.total_mutant_index > self.skip: self.logger.info("fuzzing %d of %d" % (self.fuzz_node.mutant_index, num_mutations)) # attempt to complete a fuzz transmission. keep trying until we are successful, whenever a failure # occurs, restart the target. while 1: # instruct the debugger/sniffer that we are about to send a new fuzz. if target.procmon: try: target.procmon.pre_send(self.total_mutant_index) except Exception, e: error_handler(e, "failed on procmon.pre_send()", target) continue if target.netmon: try: target.netmon.pre_send(self.total_mutant_index) except Exception, e: error_handler(e, "failed on netmon.pre_send()", target) continue try: # establish a connection to the target. sock = socket.socket(socket.AF_INET, self.proto) except Exception, e: error_handler(e, "failed creating socket", target) continue if self.bind: try: sock.bind(self.bind) except Exception, e: error_handler(e, "failed binding on socket", target, sock) continue try: sock.settimeout(self.timeout) # Connect is needed only for TCP stream if self.proto == socket.SOCK_STREAM: sock.connect((target.host, target.port)) except Exception, e: error_handler(e, "failed connecting on socket", target, sock) continue # if SSL is requested, then enable it. if self.ssl: try: ssl = socket.ssl(sock) sock = httplib.FakeSocket(sock, ssl) except Exception, e: error_handler(e, "failed ssl setup", target, sock) continue # if the user registered a pre-send function, pass it the sock and let it do the deed. try: self.pre_send(sock) except Exception, e: error_handler(e, "pre_send() failed", target, sock) continue # send out valid requests for each node in the current path up to the node we are fuzzing. try: for e in path[:-1]: node = self.nodes[e.dst] self.transmit(sock, node, e, target) except Exception, e: error_handler(e, "failed transmitting a node up the path", target, sock) continue # now send the current node we are fuzzing. try: self.transmit(sock, self.fuzz_node, edge, target) except Exception, e: error_handler(e, "failed transmitting fuzz node", target, sock) continue # if we reach this point the send was successful for break out of the while(1). break # if the user registered a post-send function, pass it the sock and let it do the deed. # we do this outside the try/except loop because if our fuzz causes a crash then the post_send() # will likely fail and we don't want to sit in an endless loop. try: self.post_send(sock) except Exception, e: error_handler(e, "post_send() failed", target, sock) # done with the socket. sock.close() # delay in between test cases. self.logger.info("sleeping for %f seconds" % self.sleep_time) time.sleep(self.sleep_time) # poll the PED-RPC endpoints (netmon, procmon etc...) for the target. self.poll_pedrpc(target) # serialize the current session state to disk. self.export_file() # recursively fuzz the remainder of the nodes in the session graph. self.fuzz(self.fuzz_node, path) # finished with the last node on the path, pop it off the path stack. if path: path.pop() # loop to keep the main thread running and be able to receive signals if self.signal_module: # wait for a signal only if fuzzing is finished (this function is recursive) # if fuzzing is not finished, web interface thread will catch it if self.total_mutant_index == self.total_num_mutations: import signal try: while True: signal.pause() except AttributeError: # signal.pause() is missing for Windows; wait 1ms and loop instead while True: time.sleep(0.001)
[ "def", "fuzz", "(", "self", ",", "this_node", "=", "None", ",", "path", "=", "[", "]", ")", ":", "# if no node is specified, then we start from the root node and initialize the session.", "if", "not", "this_node", ":", "# we can't fuzz if we don't have at least one target and...
https://github.com/knownsec/VxPwn/blob/6555f49675f0317d4a48568a89d0ec4332658402/sulley/sulley/sessions.py#L361-L560
slimkrazy/python-google-places
1ddb7aa35983e845ede912f8cc415b115ef4d8be
googleplaces/__init__.py
python
_validate_response
(url, response)
Validates that the response from Google was successful.
Validates that the response from Google was successful.
[ "Validates", "that", "the", "response", "from", "Google", "was", "successful", "." ]
def _validate_response(url, response): """Validates that the response from Google was successful.""" if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK, GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]: error_detail = ('Request to URL %s failed with response code: %s' % (url, response['status'])) raise GooglePlacesError(error_detail)
[ "def", "_validate_response", "(", "url", ",", "response", ")", ":", "if", "response", "[", "'status'", "]", "not", "in", "[", "GooglePlaces", ".", "RESPONSE_STATUS_OK", ",", "GooglePlaces", ".", "RESPONSE_STATUS_ZERO_RESULTS", "]", ":", "error_detail", "=", "(",...
https://github.com/slimkrazy/python-google-places/blob/1ddb7aa35983e845ede912f8cc415b115ef4d8be/googleplaces/__init__.py#L169-L175
gxcuizy/Python
72167d12439a615a8fd4b935eae1fb6516ed4e69
英雄联盟皮肤爬图/get_lol_skin.py
python
GetLolSkin.download_skin
(self, skin_id, skin_name)
下载皮肤图片
下载皮肤图片
[ "下载皮肤图片" ]
def download_skin(self, skin_id, skin_name): """下载皮肤图片""" # 下载图片 img_url = self.skin_url + skin_id + '.jpg' request = requests.get(img_url) if request.status_code == 200: print('downloading……%s' % skin_name) img_path = os.path.join(self.skin_folder, skin_name) with open(img_path, 'wb') as img: img.write(request.content) else: print('img error!')
[ "def", "download_skin", "(", "self", ",", "skin_id", ",", "skin_name", ")", ":", "# 下载图片", "img_url", "=", "self", ".", "skin_url", "+", "skin_id", "+", "'.jpg'", "request", "=", "requests", ".", "get", "(", "img_url", ")", "if", "request", ".", "status_...
https://github.com/gxcuizy/Python/blob/72167d12439a615a8fd4b935eae1fb6516ed4e69/英雄联盟皮肤爬图/get_lol_skin.py#L72-L83
sa7mon/S3Scanner
dd81646a3c3691d09a54883a853cd57f61d61c85
S3Scanner/S3Bucket.py
python
S3Bucket.get_human_readable_permissions
(self)
return f"AuthUsers: [{', '.join(authUsersPermissions)}], AllUsers: [{', '.join(allUsersPermissions)}]"
Returns a human-readable string of allowed permissions for this bucket i.e. "AuthUsers: [Read | WriteACP], AllUsers: [FullControl]" :return: str: Human-readable permissions
Returns a human-readable string of allowed permissions for this bucket i.e. "AuthUsers: [Read | WriteACP], AllUsers: [FullControl]"
[ "Returns", "a", "human", "-", "readable", "string", "of", "allowed", "permissions", "for", "this", "bucket", "i", ".", "e", ".", "AuthUsers", ":", "[", "Read", "|", "WriteACP", "]", "AllUsers", ":", "[", "FullControl", "]" ]
def get_human_readable_permissions(self): """ Returns a human-readable string of allowed permissions for this bucket i.e. "AuthUsers: [Read | WriteACP], AllUsers: [FullControl]" :return: str: Human-readable permissions """ # Add AuthUsers permissions authUsersPermissions = [] if self.AuthUsersFullControl == Permission.ALLOWED: authUsersPermissions.append("FullControl") else: if self.AuthUsersRead == Permission.ALLOWED: authUsersPermissions.append("Read") if self.AuthUsersWrite == Permission.ALLOWED: authUsersPermissions.append("Write") if self.AuthUsersReadACP == Permission.ALLOWED: authUsersPermissions.append("ReadACP") if self.AuthUsersWriteACP == Permission.ALLOWED: authUsersPermissions.append("WriteACP") # Add AllUsers permissions allUsersPermissions = [] if self.AllUsersFullControl == Permission.ALLOWED: allUsersPermissions.append("FullControl") else: if self.AllUsersRead == Permission.ALLOWED: allUsersPermissions.append("Read") if self.AllUsersWrite == Permission.ALLOWED: allUsersPermissions.append("Write") if self.AllUsersReadACP == Permission.ALLOWED: allUsersPermissions.append("ReadACP") if self.AllUsersWriteACP == Permission.ALLOWED: allUsersPermissions.append("WriteACP") return f"AuthUsers: [{', '.join(authUsersPermissions)}], AllUsers: [{', '.join(allUsersPermissions)}]"
[ "def", "get_human_readable_permissions", "(", "self", ")", ":", "# Add AuthUsers permissions", "authUsersPermissions", "=", "[", "]", "if", "self", ".", "AuthUsersFullControl", "==", "Permission", ".", "ALLOWED", ":", "authUsersPermissions", ".", "append", "(", "\"Ful...
https://github.com/sa7mon/S3Scanner/blob/dd81646a3c3691d09a54883a853cd57f61d61c85/S3Scanner/S3Bucket.py#L129-L162
yoda-pa/yoda
e6b4325737b877488af4d1bf0b86eb1d98b88aed
modules/life.py
python
is_in_params
(params, query, article)
return query in article_filter
Get file path for today's tasks entry file :param params: :param query: :param article: :return:
Get file path for today's tasks entry file
[ "Get", "file", "path", "for", "today", "s", "tasks", "entry", "file" ]
def is_in_params(params, query, article): """ Get file path for today's tasks entry file :param params: :param query: :param article: :return: """ query = query.lower() article_filter = article[params] if type(article_filter) is list: article_filter = [item.lower() for item in article_filter] else: article_filter = article_filter.lower() return query in article_filter
[ "def", "is_in_params", "(", "params", ",", "query", ",", "article", ")", ":", "query", "=", "query", ".", "lower", "(", ")", "article_filter", "=", "article", "[", "params", "]", "if", "type", "(", "article_filter", ")", "is", "list", ":", "article_filte...
https://github.com/yoda-pa/yoda/blob/e6b4325737b877488af4d1bf0b86eb1d98b88aed/modules/life.py#L24-L41
brycedrennan/eulerian-magnification
8f7612f00efead03c154a173bed64fdc9f7f4112
eulerian_magnification/base.py
python
combine_pyramid_and_save
(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi')
Combine a gaussian video representation with the original and save to file
Combine a gaussian video representation with the original and save to file
[ "Combine", "a", "gaussian", "video", "representation", "with", "the", "original", "and", "save", "to", "file" ]
def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'): """Combine a gaussian video representation with the original and save to file""" width, height = get_frame_dimensions(orig_video[0]) fourcc = cv2.VideoWriter_fourcc(*'MJPG') print("Outputting to %s" % save_filename) writer = cv2.VideoWriter(save_filename, fourcc, fps, (width, height), 1) for x in range(0, g_video.shape[0]): img = np.ndarray(shape=g_video[x].shape, dtype='float') img[:] = g_video[x] for i in range(enlarge_multiple): img = cv2.pyrUp(img) img[:height, :width] = img[:height, :width] + orig_video[x] res = cv2.convertScaleAbs(img[:height, :width]) writer.write(res)
[ "def", "combine_pyramid_and_save", "(", "g_video", ",", "orig_video", ",", "enlarge_multiple", ",", "fps", ",", "save_filename", "=", "'media/output.avi'", ")", ":", "width", ",", "height", "=", "get_frame_dimensions", "(", "orig_video", "[", "0", "]", ")", "fou...
https://github.com/brycedrennan/eulerian-magnification/blob/8f7612f00efead03c154a173bed64fdc9f7f4112/eulerian_magnification/base.py#L108-L122
timothyb0912/pylogit
cffc9c523b5368966ef2481c7dc30f0a5d296de8
src/pylogit/base_multinomial_cm_v2.py
python
MNDC_Model.get_mappings_for_fit
(self, dense=False)
return create_long_form_mappings(self.data, self.obs_id_col, self.alt_id_col, choice_col=self.choice_col, nest_spec=self.nest_spec, mix_id_col=self.mixing_id_col, dense=dense)
Parameters ---------- dense : bool, optional. Dictates if sparse matrices will be returned or dense numpy arrays. Returns ------- mapping_dict : OrderedDict. Keys will be `["rows_to_obs", "rows_to_alts", "chosen_row_to_obs", "rows_to_nests"]`. The value for `rows_to_obs` will map the rows of the `long_form` to the unique observations (on the columns) in their order of appearance. The value for `rows_to_alts` will map the rows of the `long_form` to the unique alternatives which are possible in the dataset (on the columns), in sorted order--not order of appearance. The value for `chosen_row_to_obs`, if not None, will map the rows of the `long_form` that contain the chosen alternatives to the specific observations those rows are associated with (denoted by the columns). The value of `rows_to_nests`, if not None, will map the rows of the `long_form` to the nest (denoted by the column) that contains the row's alternative. If `dense==True`, the returned values will be dense numpy arrays. Otherwise, the returned values will be scipy sparse arrays.
Parameters ---------- dense : bool, optional. Dictates if sparse matrices will be returned or dense numpy arrays.
[ "Parameters", "----------", "dense", ":", "bool", "optional", ".", "Dictates", "if", "sparse", "matrices", "will", "be", "returned", "or", "dense", "numpy", "arrays", "." ]
def get_mappings_for_fit(self, dense=False): """ Parameters ---------- dense : bool, optional. Dictates if sparse matrices will be returned or dense numpy arrays. Returns ------- mapping_dict : OrderedDict. Keys will be `["rows_to_obs", "rows_to_alts", "chosen_row_to_obs", "rows_to_nests"]`. The value for `rows_to_obs` will map the rows of the `long_form` to the unique observations (on the columns) in their order of appearance. The value for `rows_to_alts` will map the rows of the `long_form` to the unique alternatives which are possible in the dataset (on the columns), in sorted order--not order of appearance. The value for `chosen_row_to_obs`, if not None, will map the rows of the `long_form` that contain the chosen alternatives to the specific observations those rows are associated with (denoted by the columns). The value of `rows_to_nests`, if not None, will map the rows of the `long_form` to the nest (denoted by the column) that contains the row's alternative. If `dense==True`, the returned values will be dense numpy arrays. Otherwise, the returned values will be scipy sparse arrays. """ return create_long_form_mappings(self.data, self.obs_id_col, self.alt_id_col, choice_col=self.choice_col, nest_spec=self.nest_spec, mix_id_col=self.mixing_id_col, dense=dense)
[ "def", "get_mappings_for_fit", "(", "self", ",", "dense", "=", "False", ")", ":", "return", "create_long_form_mappings", "(", "self", ".", "data", ",", "self", ".", "obs_id_col", ",", "self", ".", "alt_id_col", ",", "choice_col", "=", "self", ".", "choice_co...
https://github.com/timothyb0912/pylogit/blob/cffc9c523b5368966ef2481c7dc30f0a5d296de8/src/pylogit/base_multinomial_cm_v2.py#L920-L951
lmb-freiburg/demon
bf871aa796342bc12693ef584ab49eb58bcb96b3
python/depthmotionnet/dataset_tools/helpers.py
python
safe_crop_image
(image, box, fill_value)
crops an image and adds a border if necessary image: PIL.Image box: 4 tuple (x0,y0,x1,y1) tuple fill_value: color value, scalar or tuple Returns the cropped image
crops an image and adds a border if necessary image: PIL.Image
[ "crops", "an", "image", "and", "adds", "a", "border", "if", "necessary", "image", ":", "PIL", ".", "Image" ]
def safe_crop_image(image, box, fill_value): """crops an image and adds a border if necessary image: PIL.Image box: 4 tuple (x0,y0,x1,y1) tuple fill_value: color value, scalar or tuple Returns the cropped image """ x0, y0, x1, y1 = box if x0 >=0 and y0 >= 0 and x1 < image.width and y1 < image.height: return image.crop(box) else: crop_width = x1-x0 crop_height = y1-y0 tmp = Image.new(image.mode, (crop_width, crop_height), fill_value) safe_box = ( max(0,min(x0,image.width-1)), max(0,min(y0,image.height-1)), max(0,min(x1,image.width)), max(0,min(y1,image.height)), ) img_crop = image.crop(safe_box) x = -x0 if x0 < 0 else 0 y = -y0 if y0 < 0 else 0 tmp.paste(image, (x,y)) return tmp
[ "def", "safe_crop_image", "(", "image", ",", "box", ",", "fill_value", ")", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "box", "if", "x0", ">=", "0", "and", "y0", ">=", "0", "and", "x1", "<", "image", ".", "width", "and", "y1", "<", "image...
https://github.com/lmb-freiburg/demon/blob/bf871aa796342bc12693ef584ab49eb58bcb96b3/python/depthmotionnet/dataset_tools/helpers.py#L74-L103
polaris-gslb/polaris-gslb
73c0b121f802bc6a3221a6d41f97d27e40f7f651
polaris_health/protocols/tcp.py
python
TCPSocket.recv
(self)
return received
Read response ONCE from connected self._sock up to RECV_BUFF_SIZE bytes returns: bytes() received
Read response ONCE from connected self._sock up to RECV_BUFF_SIZE bytes returns: bytes() received
[ "Read", "response", "ONCE", "from", "connected", "self", ".", "_sock", "up", "to", "RECV_BUFF_SIZE", "bytes", "returns", ":", "bytes", "()", "received" ]
def recv(self): """Read response ONCE from connected self._sock up to RECV_BUFF_SIZE bytes returns: bytes() received """ start_time = time.monotonic() try: received = self._sock.recv(RECV_BUFF_SIZE) except OSError as e: self._sock.close() raise ProtocolError('{} {} during socket.recv()' .format(e.__class__.__name__, e)) self._decrease_timeout(time.monotonic() - start_time) return received
[ "def", "recv", "(", "self", ")", ":", "start_time", "=", "time", ".", "monotonic", "(", ")", "try", ":", "received", "=", "self", ".", "_sock", ".", "recv", "(", "RECV_BUFF_SIZE", ")", "except", "OSError", "as", "e", ":", "self", ".", "_sock", ".", ...
https://github.com/polaris-gslb/polaris-gslb/blob/73c0b121f802bc6a3221a6d41f97d27e40f7f651/polaris_health/protocols/tcp.py#L68-L84
yiranran/Audio-driven-TalkingFace-HeadPose
d062a00a46a5d0ebb4bf66751e7a9af92ee418e8
render-to-video/util/get_data.py
python
GetData._get_options
(r)
return options
[]
def _get_options(r): soup = BeautifulSoup(r.text, 'lxml') options = [h.text for h in soup.find_all('a', href=True) if h.text.endswith(('.zip', 'tar.gz'))] return options
[ "def", "_get_options", "(", "r", ")", ":", "soup", "=", "BeautifulSoup", "(", "r", ".", "text", ",", "'lxml'", ")", "options", "=", "[", "h", ".", "text", "for", "h", "in", "soup", ".", "find_all", "(", "'a'", ",", "href", "=", "True", ")", "if",...
https://github.com/yiranran/Audio-driven-TalkingFace-HeadPose/blob/d062a00a46a5d0ebb4bf66751e7a9af92ee418e8/render-to-video/util/get_data.py#L40-L44
timkpaine/pyEX
254acd2b0cf7cb7183100106f4ecc11d1860c46a
pyEX/premium/fraudfactors/__init__.py
python
nonTimelyFilingsFraudFactorsDF
(symbol="", **kwargs)
return _baseDF( id="PREMIUM_FRAUD_FACTORS_NON_TIMELY_FILINGS", symbol=symbol, **kwargs )
The data set records the date in which a firm files a Non-Timely notification with the SEC. Companies regulated by the SEC are required to file a Non-Timely notification when they are unable to file their annual or quarterly disclosures on time. In most cases, the inability to file annual/quarterly disclosures on time is a red-flag and thus a valuable signal for algorithmic strategies and fundamental investing alike. Data available from 1994 with coverage of about 18,000 equities https://iexcloud.io/docs/api/#non-timely-filings Args: symbol (str): symbol to use Supports all kwargs from `pyEX.timeseries.timeSeries`
The data set records the date in which a firm files a Non-Timely notification with the SEC. Companies regulated by the SEC are required to file a Non-Timely notification when they are unable to file their annual or quarterly disclosures on time. In most cases, the inability to file annual/quarterly disclosures on time is a red-flag and thus a valuable signal for algorithmic strategies and fundamental investing alike. Data available from 1994 with coverage of about 18,000 equities https://iexcloud.io/docs/api/#non-timely-filings
[ "The", "data", "set", "records", "the", "date", "in", "which", "a", "firm", "files", "a", "Non", "-", "Timely", "notification", "with", "the", "SEC", ".", "Companies", "regulated", "by", "the", "SEC", "are", "required", "to", "file", "a", "Non", "-", "...
def nonTimelyFilingsFraudFactorsDF(symbol="", **kwargs): """The data set records the date in which a firm files a Non-Timely notification with the SEC. Companies regulated by the SEC are required to file a Non-Timely notification when they are unable to file their annual or quarterly disclosures on time. In most cases, the inability to file annual/quarterly disclosures on time is a red-flag and thus a valuable signal for algorithmic strategies and fundamental investing alike. Data available from 1994 with coverage of about 18,000 equities https://iexcloud.io/docs/api/#non-timely-filings Args: symbol (str): symbol to use Supports all kwargs from `pyEX.timeseries.timeSeries` """ return _baseDF( id="PREMIUM_FRAUD_FACTORS_NON_TIMELY_FILINGS", symbol=symbol, **kwargs )
[ "def", "nonTimelyFilingsFraudFactorsDF", "(", "symbol", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "return", "_baseDF", "(", "id", "=", "\"PREMIUM_FRAUD_FACTORS_NON_TIMELY_FILINGS\"", ",", "symbol", "=", "symbol", ",", "*", "*", "kwargs", ")" ]
https://github.com/timkpaine/pyEX/blob/254acd2b0cf7cb7183100106f4ecc11d1860c46a/pyEX/premium/fraudfactors/__init__.py#L45-L57
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/cloud/clouds/clc.py
python
list_nodes_full
(call=None, for_output=True)
return servers
Return a list of the VMs that are on the provider
Return a list of the VMs that are on the provider
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "on", "the", "provider" ]
def list_nodes_full(call=None, for_output=True): """ Return a list of the VMs that are on the provider """ if call == "action": raise SaltCloudSystemExit( "The list_nodes_full function must be called with -f or --function." ) creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) servers_raw = clc.v1.Server.GetServers(location=None) servers_raw = salt.utils.json.dumps(servers_raw) servers = salt.utils.json.loads(servers_raw) return servers
[ "def", "list_nodes_full", "(", "call", "=", "None", ",", "for_output", "=", "True", ")", ":", "if", "call", "==", "\"action\"", ":", "raise", "SaltCloudSystemExit", "(", "\"The list_nodes_full function must be called with -f or --function.\"", ")", "creds", "=", "get_...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/clc.py#L167-L180
Nekmo/amazon-dash
ac2b2f98282ec08036e1671fe937dfda381a911f
amazon_dash/management.py
python
create_logger
(name, level=logging.INFO)
Create a Logger and set handler and formatter :param name: logger name :param level: logging level :return: None
Create a Logger and set handler and formatter
[ "Create", "a", "Logger", "and", "set", "handler", "and", "formatter" ]
def create_logger(name, level=logging.INFO): """Create a Logger and set handler and formatter :param name: logger name :param level: logging level :return: None """ # create logger logger = logging.getLogger(name) logger.setLevel(level) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(level) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)-7s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch)
[ "def", "create_logger", "(", "name", ",", "level", "=", "logging", ".", "INFO", ")", ":", "# create logger", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "logger", ".", "setLevel", "(", "level", ")", "# create console handler and set level to de...
https://github.com/Nekmo/amazon-dash/blob/ac2b2f98282ec08036e1671fe937dfda381a911f/amazon_dash/management.py#L24-L46
Xilinx/finn
d1cc9cf94f1c33354cc169c5a6517314d0e94e3b
src/finn/transformation/fpgadataflow/insert_iodma.py
python
InsertIODMA.__init__
(self, max_intfwidth=32)
[]
def __init__(self, max_intfwidth=32): super().__init__() assert ( 2 ** math.log2(max_intfwidth) == max_intfwidth ), "max_intfwidth must be a power of 2" self.max_intfwidth = max_intfwidth
[ "def", "__init__", "(", "self", ",", "max_intfwidth", "=", "32", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "assert", "(", "2", "**", "math", ".", "log2", "(", "max_intfwidth", ")", "==", "max_intfwidth", ")", ",", "\"max_intfwidth must be a...
https://github.com/Xilinx/finn/blob/d1cc9cf94f1c33354cc169c5a6517314d0e94e3b/src/finn/transformation/fpgadataflow/insert_iodma.py#L43-L48
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/pymongo/auth.py
python
_authenticate_gssapi
(username, sock_info, cmd_func)
Authenticate using GSSAPI.
Authenticate using GSSAPI.
[ "Authenticate", "using", "GSSAPI", "." ]
def _authenticate_gssapi(username, sock_info, cmd_func): """Authenticate using GSSAPI. """ try: # Starting here and continuing through the while loop below - establish # the security context. See RFC 4752, Section 3.1, first paragraph. result, ctx = kerberos.authGSSClientInit('mongodb@' + sock_info.host, kerberos.GSS_C_MUTUAL_FLAG) if result != kerberos.AUTH_GSS_COMPLETE: raise OperationFailure('Kerberos context failed to initialize.') try: # pykerberos uses a weird mix of exceptions and return values # to indicate errors. # 0 == continue, 1 == complete, -1 == error # Only authGSSClientStep can return 0. if kerberos.authGSSClientStep(ctx, '') != 0: raise OperationFailure('Unknown kerberos ' 'failure in step function.') # Start a SASL conversation with mongod/s # Note: pykerberos deals with base64 encoded byte strings. # Since mongo accepts base64 strings as the payload we don't # have to use bson.binary.Binary. payload = kerberos.authGSSClientResponse(ctx) cmd = SON([('saslStart', 1), ('mechanism', 'GSSAPI'), ('payload', payload), ('autoAuthorize', 1)]) response, _ = cmd_func(sock_info, '$external', cmd) # Limit how many times we loop to catch protocol / library issues for _ in xrange(10): result = kerberos.authGSSClientStep(ctx, str(response['payload'])) if result == -1: raise OperationFailure('Unknown kerberos ' 'failure in step function.') payload = kerberos.authGSSClientResponse(ctx) or '' cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', payload)]) response, _ = cmd_func(sock_info, '$external', cmd) if result == kerberos.AUTH_GSS_COMPLETE: break else: raise OperationFailure('Kerberos ' 'authentication failed to complete.') # Once the security context is established actually authenticate. # See RFC 4752, Section 3.1, last two paragraphs. if kerberos.authGSSClientUnwrap(ctx, str(response['payload'])) != 1: raise OperationFailure('Unknown kerberos ' 'failure during GSS_Unwrap step.') if kerberos.authGSSClientWrap(ctx, kerberos.authGSSClientResponse(ctx), username) != 1: raise OperationFailure('Unknown kerberos ' 'failure during GSS_Wrap step.') payload = kerberos.authGSSClientResponse(ctx) cmd = SON([('saslContinue', 1), ('conversationId', response['conversationId']), ('payload', payload)]) response, _ = cmd_func(sock_info, '$external', cmd) finally: kerberos.authGSSClientClean(ctx) except kerberos.KrbError, exc: raise OperationFailure(str(exc))
[ "def", "_authenticate_gssapi", "(", "username", ",", "sock_info", ",", "cmd_func", ")", ":", "try", ":", "# Starting here and continuing through the while loop below - establish", "# the security context. See RFC 4752, Section 3.1, first paragraph.", "result", ",", "ctx", "=", "k...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/pymongo/auth.py#L66-L141
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/在线机器平台/阿里云/tensorflow_mnist.py
python
read_image_batch
(file_queue, batch_size)
return image_batch, one_hot_labels
[]
def read_image_batch(file_queue, batch_size): img, label = read_image(file_queue) capacity = 3 * batch_size image_batch, label_batch = tf.train.batch([img, label], batch_size=batch_size, capacity=capacity, num_threads=10) one_hot_labels = tf.to_float(tf.one_hot(label_batch, 10, 1, 0)) return image_batch, one_hot_labels
[ "def", "read_image_batch", "(", "file_queue", ",", "batch_size", ")", ":", "img", ",", "label", "=", "read_image", "(", "file_queue", ")", "capacity", "=", "3", "*", "batch_size", "image_batch", ",", "label_batch", "=", "tf", ".", "train", ".", "batch", "(...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/在线机器平台/阿里云/tensorflow_mnist.py#L28-L33
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/kombu/utils/div.py
python
emergency_dump_state
(state, open_file=open, dump=None, stderr=None)
return persist
Dump message state to stdout or file.
Dump message state to stdout or file.
[ "Dump", "message", "state", "to", "stdout", "or", "file", "." ]
def emergency_dump_state(state, open_file=open, dump=None, stderr=None): """Dump message state to stdout or file.""" from pprint import pformat from tempfile import mktemp stderr = sys.stderr if stderr is None else stderr if dump is None: import pickle dump = pickle.dump persist = mktemp() print('EMERGENCY DUMP STATE TO FILE -> {0} <-'.format(persist), # noqa file=stderr) fh = open_file(persist, 'w') try: try: dump(state, fh, protocol=0) except Exception as exc: print( # noqa 'Cannot pickle state: {0!r}. Fallback to pformat.'.format(exc), file=stderr, ) fh.write(default_encode(pformat(state))) finally: fh.flush() fh.close() return persist
[ "def", "emergency_dump_state", "(", "state", ",", "open_file", "=", "open", ",", "dump", "=", "None", ",", "stderr", "=", "None", ")", ":", "from", "pprint", "import", "pformat", "from", "tempfile", "import", "mktemp", "stderr", "=", "sys", ".", "stderr", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/kombu/utils/div.py#L9-L34
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Uptycs/Integrations/Uptycs/Uptycs.py
python
uptycs_get_alert_rules
()
return restcall(http_method, api_call)
return list of alert rules
return list of alert rules
[ "return", "list", "of", "alert", "rules" ]
def uptycs_get_alert_rules(): """ return list of alert rules """ http_method = 'get' api_call = "/alertRules" limit = demisto.args().get('limit') if limit != -1 and limit is not None: api_call = ("%s?limit=%s" % (api_call, limit)) return restcall(http_method, api_call)
[ "def", "uptycs_get_alert_rules", "(", ")", ":", "http_method", "=", "'get'", "api_call", "=", "\"/alertRules\"", "limit", "=", "demisto", ".", "args", "(", ")", ".", "get", "(", "'limit'", ")", "if", "limit", "!=", "-", "1", "and", "limit", "is", "not", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Uptycs/Integrations/Uptycs/Uptycs.py#L550-L561
ChintanTrivedi/DeepGamingAI_FIFA
b79a5b670756056b7b6aedd2c5c84fd5f59d569e
utils/shape_utils.py
python
pad_tensor
(t, length)
return padded_t
Pads the input tensor with 0s along the first dimension up to the length. Args: t: the input tensor, assuming the rank is at least 1. length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after padding, assuming length <= t.shape[0]. Returns: padded_t: the padded tensor, whose first dimension is length. If the length is an integer, the first dimension of padded_t is set to length statically.
Pads the input tensor with 0s along the first dimension up to the length.
[ "Pads", "the", "input", "tensor", "with", "0s", "along", "the", "first", "dimension", "up", "to", "the", "length", "." ]
def pad_tensor(t, length): """Pads the input tensor with 0s along the first dimension up to the length. Args: t: the input tensor, assuming the rank is at least 1. length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after padding, assuming length <= t.shape[0]. Returns: padded_t: the padded tensor, whose first dimension is length. If the length is an integer, the first dimension of padded_t is set to length statically. """ t_rank = tf.rank(t) t_shape = tf.shape(t) t_d0 = t_shape[0] pad_d0 = tf.expand_dims(length - t_d0, 0) pad_shape = tf.cond( tf.greater(t_rank, 1), lambda: tf.concat([pad_d0, t_shape[1:]], 0), lambda: tf.expand_dims(length - t_d0, 0)) padded_t = tf.concat([t, tf.zeros(pad_shape, dtype=t.dtype)], 0) if not _is_tensor(length): padded_t = _set_dim_0(padded_t, length) return padded_t
[ "def", "pad_tensor", "(", "t", ",", "length", ")", ":", "t_rank", "=", "tf", ".", "rank", "(", "t", ")", "t_shape", "=", "tf", ".", "shape", "(", "t", ")", "t_d0", "=", "t_shape", "[", "0", "]", "pad_d0", "=", "tf", ".", "expand_dims", "(", "le...
https://github.com/ChintanTrivedi/DeepGamingAI_FIFA/blob/b79a5b670756056b7b6aedd2c5c84fd5f59d569e/utils/shape_utils.py#L49-L72
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/util.py
python
_get_external_data
(url)
return result
[]
def _get_external_data(url): result = {} try: # urlopen might fail if it runs into redirections, # because of Python issue #13696. Fixed in locators # using a custom redirect handler. resp = urlopen(url) headers = resp.info() ct = headers.get('Content-Type') if not ct.startswith('application/json'): logger.debug('Unexpected response for JSON request: %s', ct) else: reader = codecs.getreader('utf-8')(resp) #data = reader.read().decode('utf-8') #result = json.loads(data) result = json.load(reader) except Exception as e: logger.exception('Failed to get external data for %s: %s', url, e) return result
[ "def", "_get_external_data", "(", "url", ")", ":", "result", "=", "{", "}", "try", ":", "# urlopen might fail if it runs into redirections,", "# because of Python issue #13696. Fixed in locators", "# using a custom redirect handler.", "resp", "=", "urlopen", "(", "url", ")", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/util.py#L902-L920
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/venv/lib/python3.7/site.py
python
check_enableusersite
()
return True
Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. None: Disabled for security reasons False: Disabled by user (command line option) True: Safe and enabled
Check if user site directory is safe for inclusion
[ "Check", "if", "user", "site", "directory", "is", "safe", "for", "inclusion" ]
def check_enableusersite(): """Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. None: Disabled for security reasons False: Disabled by user (command line option) True: Safe and enabled """ if hasattr(sys, "flags") and getattr(sys.flags, "no_user_site", False): return False if hasattr(os, "getuid") and hasattr(os, "geteuid"): # check process uid == effective uid if os.geteuid() != os.getuid(): return None if hasattr(os, "getgid") and hasattr(os, "getegid"): # check process gid == effective gid if os.getegid() != os.getgid(): return None return True
[ "def", "check_enableusersite", "(", ")", ":", "if", "hasattr", "(", "sys", ",", "\"flags\"", ")", "and", "getattr", "(", "sys", ".", "flags", ",", "\"no_user_site\"", ",", "False", ")", ":", "return", "False", "if", "hasattr", "(", "os", ",", "\"getuid\"...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site.py#L284-L306
zestedesavoir/zds-site
2ba922223c859984a413cc6c108a8aa4023b113e
zds/utils/models.py
python
Comment.update_content
(self, text, on_error=None)
Updates the content of this comment. This method will render the new comment to HTML, store the rendered version, and store data to later analyze pings and spam. This method updates fields, but does not save the instance. :param text: The new comment content. :param on_error: A callable called if zmd returns an error, provided with a single argument: a list of user-friendly errors. See render_markdown.
Updates the content of this comment.
[ "Updates", "the", "content", "of", "this", "comment", "." ]
def update_content(self, text, on_error=None): """ Updates the content of this comment. This method will render the new comment to HTML, store the rendered version, and store data to later analyze pings and spam. This method updates fields, but does not save the instance. :param text: The new comment content. :param on_error: A callable called if zmd returns an error, provided with a single argument: a list of user-friendly errors. See render_markdown. """ # This attribute will be used by `_save_check_spam`, called after save (but not saved into the database). # We only update it if it does not already exist, so if this method is called multiple times, the oldest # version (i.e. the one currently in the database) is used for comparison. `_save_check_spam` will delete # the attribute, so if we re-save the same instance, this will be re-set. if not hasattr(self, "old_text"): self.old_text = self.text _, old_metadata, _ = render_markdown(self.text) html, new_metadata, _ = render_markdown(text, on_error=on_error) # These attributes will be used by `_save_compute_pings` to create notifications if needed. # For the same reason as `old_text`, we only update `old_metadata` if not already set. if not hasattr(self, "old_metadata"): self.old_metadata = old_metadata self.new_metadata = new_metadata self.text = text self.text_html = html
[ "def", "update_content", "(", "self", ",", "text", ",", "on_error", "=", "None", ")", ":", "# This attribute will be used by `_save_check_spam`, called after save (but not saved into the database).", "# We only update it if it does not already exist, so if this method is called multiple ti...
https://github.com/zestedesavoir/zds-site/blob/2ba922223c859984a413cc6c108a8aa4023b113e/zds/utils/models.py#L420-L451
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/common/parts/utils.py
python
_compute_softmax
(scores)
return probs
Compute softmax probability over raw logits.
Compute softmax probability over raw logits.
[ "Compute", "softmax", "probability", "over", "raw", "logits", "." ]
def _compute_softmax(scores): """Compute softmax probability over raw logits.""" if not scores: return [] max_score = None for score in scores: if max_score is None or score > max_score: max_score = score exp_scores = [] total_sum = 0.0 for score in scores: x = math.exp(score - max_score) exp_scores.append(x) total_sum += x probs = [] for score in exp_scores: probs.append(score / total_sum) return probs
[ "def", "_compute_softmax", "(", "scores", ")", ":", "if", "not", "scores", ":", "return", "[", "]", "max_score", "=", "None", "for", "score", "in", "scores", ":", "if", "max_score", "is", "None", "or", "score", ">", "max_score", ":", "max_score", "=", ...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/common/parts/utils.py#L37-L57
hack12306/12306-booking
726c830c2e771d5cd8e09772e7646e480dddb086
booking/query.py
python
query_left_tickets
(train_date, from_station, to_station, seat_types, train_names=None)
return result
信息查询-剩余车票 :param train_date :param from_station :param to_station :param seat_types :param train_names :return JSON 对象
信息查询-剩余车票 :param train_date :param from_station :param to_station :param seat_types :param train_names :return JSON 对象
[ "信息查询", "-", "剩余车票", ":", "param", "train_date", ":", "param", "from_station", ":", "param", "to_station", ":", "param", "seat_types", ":", "param", "train_names", ":", "return", "JSON", "对象" ]
def query_left_tickets(train_date, from_station, to_station, seat_types, train_names=None): """ 信息查询-剩余车票 :param train_date :param from_station :param to_station :param seat_types :param train_names :return JSON 对象 """ date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$') assert date_pattern.match(train_date), 'Invalid train_date param. %s' % train_date assert isinstance(seat_types, list), u'Invalid seat_types param. %s' % seat_types assert frozenset(seat_types) <= frozenset(dict(SEAT_TYPE_CODE_MAP).keys() ), u'Invalid seat_types param. %s' % seat_types train_info = {} trains = TrainInfoQueryAPI().info_query_left_tickets(train_date, from_station, to_station) train_info, select_seat_type = _select_train_and_seat_type(train_names, seat_types, trains) if not train_info or not select_seat_type: raise exceptions.BookingTrainNoLeftTicket('无票') _logger.debug('select train info. %s' % json.dumps(train_info, ensure_ascii=False)) result = { 'train_date': train_date, 'from_station': train_info['from_station'], 'to_station': train_info['to_station'], 'seat_type': select_seat_type, 'seat_type_code': dict(SEAT_TYPE_CODE_MAP)[select_seat_type], 'departure_time': train_info['departure_time'], 'arrival_time': train_info['arrival_time'], 'secret': train_info['secret'], 'train_name': train_info['train_name'], 'duration': train_info['duration'], 'train_num': train_info['train_num'] } return result
[ "def", "query_left_tickets", "(", "train_date", ",", "from_station", ",", "to_station", ",", "seat_types", ",", "train_names", "=", "None", ")", ":", "date_pattern", "=", "re", ".", "compile", "(", "r'^\\d{4}-\\d{2}-\\d{2}$'", ")", "assert", "date_pattern", ".", ...
https://github.com/hack12306/12306-booking/blob/726c830c2e771d5cd8e09772e7646e480dddb086/booking/query.py#L76-L116
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/tornado-6.0.1-py3.7-macosx-12.1-iPad6,7.egg/tornado/routing.py
python
RuleRouter.add_rules
(self, rules: _RuleList)
Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor).
Appends new rules to the router.
[ "Appends", "new", "rules", "to", "the", "router", "." ]
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): assert len(rule) in (2, 3, 4) if isinstance(rule[0], basestring_type): rule = Rule(PathMatches(rule[0]), *rule[1:]) else: rule = Rule(*rule) self.rules.append(self.process_rule(rule))
[ "def", "add_rules", "(", "self", ",", "rules", ":", "_RuleList", ")", "->", "None", ":", "for", "rule", "in", "rules", ":", "if", "isinstance", "(", "rule", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "len", "(", "rule", ")", "in", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/tornado-6.0.1-py3.7-macosx-12.1-iPad6,7.egg/tornado/routing.py#L334-L348
zhausong/zabbix-book
94ec20171d1ad3f690b2f2ee1f480e0bb1b763dd
tools/screen_create/zabbix_api.py
python
checkauth
(fn)
return ret
Decorator to check authentication of the decorated method
Decorator to check authentication of the decorated method
[ "Decorator", "to", "check", "authentication", "of", "the", "decorated", "method" ]
def checkauth(fn): """ Decorator to check authentication of the decorated method """ def ret(self, *args): self.__checkauth__() return fn(self, args) return ret
[ "def", "checkauth", "(", "fn", ")", ":", "def", "ret", "(", "self", ",", "*", "args", ")", ":", "self", ".", "__checkauth__", "(", ")", "return", "fn", "(", "self", ",", "args", ")", "return", "ret" ]
https://github.com/zhausong/zabbix-book/blob/94ec20171d1ad3f690b2f2ee1f480e0bb1b763dd/tools/screen_create/zabbix_api.py#L56-L61
bilelmoussaoui/Hardcode-Tray
8b264ca2386cabe595b027933a9c80c41adc1ea4
HardcodeTray/modules/applications/helpers/extract.py
python
ExtractApplication.extract
(self, icon_path)
Extract binary file.
Extract binary file.
[ "Extract", "binary", "file", "." ]
def extract(self, icon_path): """Extract binary file."""
[ "def", "extract", "(", "self", ",", "icon_path", ")", ":" ]
https://github.com/bilelmoussaoui/Hardcode-Tray/blob/8b264ca2386cabe595b027933a9c80c41adc1ea4/HardcodeTray/modules/applications/helpers/extract.py#L51-L52
asteroid-team/asteroid
fae2f7d1d4eb83da741818a5c375267fe8d98847
egs/avspeech/looking-to-listen/model.py
python
fast_icRM
(Y, crm, K=10, C=0.1)
return S
fast iCRM. Args: Y (torch.Tensor): mixed/noised stft. crm (torch.Tensor): DNN output of compressed crm. K (torch.Tensor): parameter to control the compression. C (torch.Tensor): parameter to control the compression. Returns: S (torch.Tensor): clean stft.
fast iCRM.
[ "fast", "iCRM", "." ]
def fast_icRM(Y, crm, K=10, C=0.1): """fast iCRM. Args: Y (torch.Tensor): mixed/noised stft. crm (torch.Tensor): DNN output of compressed crm. K (torch.Tensor): parameter to control the compression. C (torch.Tensor): parameter to control the compression. Returns: S (torch.Tensor): clean stft. """ M = cRM_tanh_recover(crm, K, C) S = torch.zeros(M.shape) S[:, 0, ...] = (M[:, 0, ...] * Y[:, 0, ...]) - (M[:, 1, ...] * Y[:, 1, ...]) S[:, 1, ...] = (M[:, 0, ...] * Y[:, 1, ...]) + (M[:, 1, ...] * Y[:, 0, ...]) return S
[ "def", "fast_icRM", "(", "Y", ",", "crm", ",", "K", "=", "10", ",", "C", "=", "0.1", ")", ":", "M", "=", "cRM_tanh_recover", "(", "crm", ",", "K", ",", "C", ")", "S", "=", "torch", ".", "zeros", "(", "M", ".", "shape", ")", "S", "[", ":", ...
https://github.com/asteroid-team/asteroid/blob/fae2f7d1d4eb83da741818a5c375267fe8d98847/egs/avspeech/looking-to-listen/model.py#L101-L118
researchmm/TracKit
510e240faf71b4a225d6f18bcf49b3eebf8b436e
lib/utils/utils.py
python
remove_prefix
(state_dict, prefix)
return {f(key): value for key, value in state_dict.items()}
Old style model is stored with all names of parameters share common prefix 'module.'
Old style model is stored with all names of parameters share common prefix 'module.'
[ "Old", "style", "model", "is", "stored", "with", "all", "names", "of", "parameters", "share", "common", "prefix", "module", "." ]
def remove_prefix(state_dict, prefix): ''' Old style model is stored with all names of parameters share common prefix 'module.' ''' print('remove prefix \'{}\''.format(prefix)) f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x return {f(key): value for key, value in state_dict.items()}
[ "def", "remove_prefix", "(", "state_dict", ",", "prefix", ")", ":", "print", "(", "'remove prefix \\'{}\\''", ".", "format", "(", "prefix", ")", ")", "f", "=", "lambda", "x", ":", "x", ".", "split", "(", "prefix", ",", "1", ")", "[", "-", "1", "]", ...
https://github.com/researchmm/TracKit/blob/510e240faf71b4a225d6f18bcf49b3eebf8b436e/lib/utils/utils.py#L649-L655
ljean/modbus-tk
1159c71794071ae67f73f86fa14dd71c989b4859
modbus_tk/modbus_rtu.py
python
RtuMaster._do_open
(self)
Open the given serial port if not already opened
Open the given serial port if not already opened
[ "Open", "the", "given", "serial", "port", "if", "not", "already", "opened" ]
def _do_open(self): """Open the given serial port if not already opened""" if not self._serial.is_open: call_hooks("modbus_rtu.RtuMaster.before_open", (self, )) self._serial.open()
[ "def", "_do_open", "(", "self", ")", ":", "if", "not", "self", ".", "_serial", ".", "is_open", ":", "call_hooks", "(", "\"modbus_rtu.RtuMaster.before_open\"", ",", "(", "self", ",", ")", ")", "self", ".", "_serial", ".", "open", "(", ")" ]
https://github.com/ljean/modbus-tk/blob/1159c71794071ae67f73f86fa14dd71c989b4859/modbus_tk/modbus_rtu.py#L106-L110
m-labs/artiq
eaa1505c947c7987cdbd31c24056823c740e84e0
artiq/coredevice/phaser.py
python
Phaser.dac_write
(self, addr, data)
Write 16 bit to a DAC register. :param addr: Register address :param data: Register data to write
Write 16 bit to a DAC register.
[ "Write", "16", "bit", "to", "a", "DAC", "register", "." ]
def dac_write(self, addr, data): """Write 16 bit to a DAC register. :param addr: Register address :param data: Register data to write """ div = 34 # 100 ns min period t_xfer = self.core.seconds_to_mu((8 + 1)*div*4*ns) self.spi_cfg(select=PHASER_SEL_DAC, div=div, end=0) self.spi_write(addr) delay_mu(t_xfer) self.spi_write(data >> 8) delay_mu(t_xfer) self.spi_cfg(select=PHASER_SEL_DAC, div=div, end=1) self.spi_write(data) delay_mu(t_xfer)
[ "def", "dac_write", "(", "self", ",", "addr", ",", "data", ")", ":", "div", "=", "34", "# 100 ns min period", "t_xfer", "=", "self", ".", "core", ".", "seconds_to_mu", "(", "(", "8", "+", "1", ")", "*", "div", "*", "4", "*", "ns", ")", "self", "....
https://github.com/m-labs/artiq/blob/eaa1505c947c7987cdbd31c24056823c740e84e0/artiq/coredevice/phaser.py#L557-L572
quantumlib/Cirq
89f88b01d69222d3f1ec14d649b7b3a85ed9211f
cirq-google/cirq_google/engine/abstract_job.py
python
AbstractJob.results
(self)
Returns the job results, blocking until the job is complete.
Returns the job results, blocking until the job is complete.
[ "Returns", "the", "job", "results", "blocking", "until", "the", "job", "is", "complete", "." ]
def results(self) -> Sequence[cirq.Result]: """Returns the job results, blocking until the job is complete."""
[ "def", "results", "(", "self", ")", "->", "Sequence", "[", "cirq", ".", "Result", "]", ":" ]
https://github.com/quantumlib/Cirq/blob/89f88b01d69222d3f1ec14d649b7b3a85ed9211f/cirq-google/cirq_google/engine/abstract_job.py#L173-L174
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift_tools/monitoring/generic_metric_sender.py
python
GenericMetricSender.add_heartbeat
(self, add_heartbeat, host=None)
empty implementation overridden by derived classes
empty implementation overridden by derived classes
[ "empty", "implementation", "overridden", "by", "derived", "classes" ]
def add_heartbeat(self, add_heartbeat, host=None): """ empty implementation overridden by derived classes """ pass
[ "def", "add_heartbeat", "(", "self", ",", "add_heartbeat", ",", "host", "=", "None", ")", ":", "pass" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift_tools/monitoring/generic_metric_sender.py#L51-L53
nodejs/node-gyp
a2f298870692022302fa27a1d42363c4a72df407
gyp/pylib/gyp/generator/android.py
python
AndroidMkWriter.WriteTarget
( self, spec, configs, deps, link_deps, part_of_all, write_alias_target )
Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this target
Write Makefile code to produce the final target of the gyp spec.
[ "Write", "Makefile", "code", "to", "produce", "the", "final", "target", "of", "the", "gyp", "spec", "." ]
def WriteTarget( self, spec, configs, deps, link_deps, part_of_all, write_alias_target ): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this target """ self.WriteLn("### Rules for final target.") if self.type != "none": self.WriteTargetFlags(spec, configs, link_deps) settings = spec.get("aosp_build_settings", {}) if settings: self.WriteLn("### Set directly by aosp_build_settings.") for k, v in settings.items(): if isinstance(v, list): self.WriteList(v, k) else: self.WriteLn(f"{k} := {make.QuoteIfNecessary(v)}") self.WriteLn("") # Add to the set of targets which represent the gyp 'all' target. We use the # name 'gyp_all_modules' as the Android build system doesn't allow the use # of the Make target 'all' and because 'all_modules' is the equivalent of # the Make target 'all' on Android. if part_of_all and write_alias_target: self.WriteLn('# Add target alias to "gyp_all_modules" target.') self.WriteLn(".PHONY: gyp_all_modules") self.WriteLn("gyp_all_modules: %s" % self.android_module) self.WriteLn("") # Add an alias from the gyp target name to the Android module name. This # simplifies manual builds of the target, and is required by the test # framework. if self.target != self.android_module and write_alias_target: self.WriteLn("# Alias gyp target name.") self.WriteLn(".PHONY: %s" % self.target) self.WriteLn(f"{self.target}: {self.android_module}") self.WriteLn("") # Add the command to trigger build of the target type depending # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY # NOTE: This has to come last! modifier = "" if self.toolset == "host": modifier = "HOST_" if self.type == "static_library": self.WriteLn("include $(BUILD_%sSTATIC_LIBRARY)" % modifier) elif self.type == "shared_library": self.WriteLn("LOCAL_PRELINK_MODULE := false") self.WriteLn("include $(BUILD_%sSHARED_LIBRARY)" % modifier) elif self.type == "executable": self.WriteLn("LOCAL_CXX_STL := libc++_static") # Executables are for build and test purposes only, so they're installed # to a directory that doesn't get included in the system image. self.WriteLn("LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)") self.WriteLn("include $(BUILD_%sEXECUTABLE)" % modifier) else: self.WriteLn("LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp") self.WriteLn("LOCAL_UNINSTALLABLE_MODULE := true") if self.toolset == "target": self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)") else: self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_HOST_VAR_PREFIX)") self.WriteLn() self.WriteLn("include $(BUILD_SYSTEM)/base_rules.mk") self.WriteLn() self.WriteLn("$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)") self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"') self.WriteLn("\t$(hide) mkdir -p $(dir $@)") self.WriteLn("\t$(hide) touch $@") self.WriteLn() self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX :=")
[ "def", "WriteTarget", "(", "self", ",", "spec", ",", "configs", ",", "deps", ",", "link_deps", ",", "part_of_all", ",", "write_alias_target", ")", ":", "self", ".", "WriteLn", "(", "\"### Rules for final target.\"", ")", "if", "self", ".", "type", "!=", "\"n...
https://github.com/nodejs/node-gyp/blob/a2f298870692022302fa27a1d42363c4a72df407/gyp/pylib/gyp/generator/android.py#L888-L965
Azure/batch-shipyard
d6da749f9cd678037bd520bc074e40066ea35b56
convoy/settings.py
python
get_gluster_on_compute_volume
()
return _GLUSTER_ON_COMPUTE_VOLUME
Get gluster on compute volume mount suffix :rtype: str :return: gluster on compute volume mount
Get gluster on compute volume mount suffix :rtype: str :return: gluster on compute volume mount
[ "Get", "gluster", "on", "compute", "volume", "mount", "suffix", ":", "rtype", ":", "str", ":", "return", ":", "gluster", "on", "compute", "volume", "mount" ]
def get_gluster_on_compute_volume(): # type: (None) -> str """Get gluster on compute volume mount suffix :rtype: str :return: gluster on compute volume mount """ return _GLUSTER_ON_COMPUTE_VOLUME
[ "def", "get_gluster_on_compute_volume", "(", ")", ":", "# type: (None) -> str", "return", "_GLUSTER_ON_COMPUTE_VOLUME" ]
https://github.com/Azure/batch-shipyard/blob/d6da749f9cd678037bd520bc074e40066ea35b56/convoy/settings.py#L644-L650
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
BioSQL/BioSeqDatabase.py
python
Adaptor.autocommit
(self, y=True)
return self.dbutils.autocommit(self.conn, y)
Set the autocommit mode. True values enable; False value disable.
Set the autocommit mode. True values enable; False value disable.
[ "Set", "the", "autocommit", "mode", ".", "True", "values", "enable", ";", "False", "value", "disable", "." ]
def autocommit(self, y=True): """Set the autocommit mode. True values enable; False value disable.""" return self.dbutils.autocommit(self.conn, y)
[ "def", "autocommit", "(", "self", ",", "y", "=", "True", ")", ":", "return", "self", ".", "dbutils", ".", "autocommit", "(", "self", ".", "conn", ",", "y", ")" ]
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/BioSQL/BioSeqDatabase.py#L363-L365
nuxeo/FunkLoad
8a3a44c20398098d03197baeef27a4177858df1b
src/funkload/ReportRenderRst.py
python
RenderRst.renderDefinitions
(self)
Render field definition.
Render field definition.
[ "Render", "field", "definition", "." ]
def renderDefinitions(self): """Render field definition.""" self.append(rst_title("Definitions", 2)) self.append(LI + ' CUs: Concurrent users or number of concurrent threads' ' executing tests.') self.append(LI + ' Request: a single GET/POST/redirect/XML-RPC request.') self.append(LI + ' Page: a request with redirects and resource' ' links (image, css, js) for an HTML page.') self.append(LI + ' STPS: Successful tests per second.') self.append(LI + ' SPPS: Successful pages per second.') self.append(LI + ' RPS: Requests per second, successful or not.') self.append(LI + ' maxSPPS: Maximum SPPS during the cycle.') self.append(LI + ' maxRPS: Maximum RPS during the cycle.') self.append(LI + ' MIN: Minimum response time for a page or request.') self.append(LI + ' AVG: Average response time for a page or request.') self.append(LI + ' MAX: Maximmum response time for a page or request.') self.append(LI + ' P10: 10th percentile, response time where 10 percent' ' of pages or requests are delivered.') self.append(LI + ' MED: Median or 50th percentile, response time where half' ' of pages or requests are delivered.') self.append(LI + ' P90: 90th percentile, response time where 90 percent' ' of pages or requests are delivered.') self.append(LI + ' P95: 95th percentile, response time where 95 percent' ' of pages or requests are delivered.') self.append(LI + Apdex.description_para) self.append(LI + Apdex.rating_para) self.append('') self.append('Report generated with FunkLoad_ ' + get_version() + ', more information available on the ' '`FunkLoad site <http://funkload.nuxeo.org/#benching>`_.')
[ "def", "renderDefinitions", "(", "self", ")", ":", "self", ".", "append", "(", "rst_title", "(", "\"Definitions\"", ",", "2", ")", ")", "self", ".", "append", "(", "LI", "+", "' CUs: Concurrent users or number of concurrent threads'", "' executing tests.'", ")", "...
https://github.com/nuxeo/FunkLoad/blob/8a3a44c20398098d03197baeef27a4177858df1b/src/funkload/ReportRenderRst.py#L565-L594
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/native/cpu/x86.py
python
X86Cpu.SETNBE
(cpu, dest)
Sets byte if not below or equal. :param cpu: current CPU. :param dest: destination operand.
Sets byte if not below or equal.
[ "Sets", "byte", "if", "not", "below", "or", "equal", "." ]
def SETNBE(cpu, dest): """ Sets byte if not below or equal. :param cpu: current CPU. :param dest: destination operand. """ dest.write( Operators.ITEBV(dest.size, Operators.AND(cpu.CF == False, cpu.ZF == False), 1, 0) )
[ "def", "SETNBE", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "AND", "(", "cpu", ".", "CF", "==", "False", ",", "cpu", ".", "ZF", "==", "False", ")", "...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/native/cpu/x86.py#L2913-L2922
carla-simulator/scenario_runner
f4d00d88eda4212a1e119515c96281a4be5c234e
srunner/tools/openscenario_parser.py
python
ParameterRef.is_parameter
(self)
return self._is_matching(pattern=r"[$][A-Za-z_][\w]*")
Returns: True when text is a parameter
Returns: True when text is a parameter
[ "Returns", ":", "True", "when", "text", "is", "a", "parameter" ]
def is_parameter(self) -> bool: """ Returns: True when text is a parameter """ return self._is_matching(pattern=r"[$][A-Za-z_][\w]*")
[ "def", "is_parameter", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_is_matching", "(", "pattern", "=", "r\"[$][A-Za-z_][\\w]*\"", ")" ]
https://github.com/carla-simulator/scenario_runner/blob/f4d00d88eda4212a1e119515c96281a4be5c234e/srunner/tools/openscenario_parser.py#L107-L111
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/contrib/gis/gdal/raster/band.py
python
GDALBand.nodata_value
(self, value)
Set the nodata value for this band.
Set the nodata value for this band.
[ "Set", "the", "nodata", "value", "for", "this", "band", "." ]
def nodata_value(self, value): """ Set the nodata value for this band. """ if value is None: if not capi.delete_band_nodata_value: raise ValueError('GDAL >= 2.1 required to delete nodata values.') capi.delete_band_nodata_value(self._ptr) elif not isinstance(value, (int, float)): raise ValueError('Nodata value must be numeric or None.') else: capi.set_band_nodata_value(self._ptr, value) self._flush()
[ "def", "nodata_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "if", "not", "capi", ".", "delete_band_nodata_value", ":", "raise", "ValueError", "(", "'GDAL >= 2.1 required to delete nodata values.'", ")", "capi", ".", "delete_band_n...
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/contrib/gis/gdal/raster/band.py#L150-L162
awslabs/aws-security-automation
d659c1752c5b7af59acad7c2bc540cd210040cdb
EC2 Auto Clean Room Forensics/Lambda-Functions/generateSupportTicket.py
python
lambda_handler
(event, context)
return event
[]
def lambda_handler(event, context): # TODO Implement ITSM Connectivity to log an incident in ITSM system # Python Sample to connect to ServiceNow #Need to install requests package for python # #easy_install requests # import requests # # # Set the request parameters # url = 'https://instance.service-now.com/api/now/table/incident' # # # Eg. User name="admin", Password="admin" for this code sample. # user = 'admin' # pwd = 'admin' # # # Set proper headers # headers = {"Content-Type":"application/xml","Accept":"application/xml"} # # # Do the HTTP request # response = requests.post(url, auth=(user, pwd), headers=headers ,data="<request><entry><short_description>Unable to connect to office wifi</short_description><assignment_group>287ebd7da9fe198100f92cc8d1d2154e</assignment_group><urgency>2</urgency><impact>2</impact></entry></request>") # # # Check for HTTP codes other than 200 # if response.status_code != 200: # print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json()) # exit() # # # Decode the JSON response into a dictionary and use the data # data = response.json() # print(data) return event
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "# TODO Implement ITSM Connectivity to log an incident in ITSM system", "# Python Sample to connect to ServiceNow", "#Need to install requests package for python", "# #easy_install requests", "# import requests", "#", "# # ...
https://github.com/awslabs/aws-security-automation/blob/d659c1752c5b7af59acad7c2bc540cd210040cdb/EC2 Auto Clean Room Forensics/Lambda-Functions/generateSupportTicket.py#L23-L54
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/bs4/builder/__init__.py
python
TreeBuilderRegistry.lookup
(self, *features)
return None
[]
def lookup(self, *features): if len(self.builders) == 0: # There are no builders at all. return None if len(features) == 0: # They didn't ask for any features. Give them the most # recently registered builder. return self.builders[0] # Go down the list of features in order, and eliminate any builders # that don't match every feature. features = list(features) features.reverse() candidates = None candidate_set = None while len(features) > 0: feature = features.pop() we_have_the_feature = self.builders_for_feature.get(feature, []) if len(we_have_the_feature) > 0: if candidates is None: candidates = we_have_the_feature candidate_set = set(candidates) else: # Eliminate any candidates that don't have this feature. candidate_set = candidate_set.intersection( set(we_have_the_feature)) # The only valid candidates are the ones in candidate_set. # Go through the original list of candidates and pick the first one # that's in candidate_set. if candidate_set is None: return None for candidate in candidates: if candidate in candidate_set: return candidate return None
[ "def", "lookup", "(", "self", ",", "*", "features", ")", ":", "if", "len", "(", "self", ".", "builders", ")", "==", "0", ":", "# There are no builders at all.", "return", "None", "if", "len", "(", "features", ")", "==", "0", ":", "# They didn't ask for any...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/bs4/builder/__init__.py#L42-L78
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
MegatronBertModel.forward
(self, *args, **kwargs)
[]
def forward(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "forward", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L3398-L3399
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/controllers/core_helpers/status.py
python
CoreStatus.get_grep_eta
(self)
return self.calculate_eta(self.get_grep_input_speed(), self.get_grep_output_speed(), self.get_grep_qsize(), GREP, adjustment=adjustment)
[]
def get_grep_eta(self): adjustment = self.get_grep_adjustment_ratio() return self.calculate_eta(self.get_grep_input_speed(), self.get_grep_output_speed(), self.get_grep_qsize(), GREP, adjustment=adjustment)
[ "def", "get_grep_eta", "(", "self", ")", ":", "adjustment", "=", "self", ".", "get_grep_adjustment_ratio", "(", ")", "return", "self", ".", "calculate_eta", "(", "self", ".", "get_grep_input_speed", "(", ")", ",", "self", ".", "get_grep_output_speed", "(", ")"...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/controllers/core_helpers/status.py#L293-L300
Cue/scales
0aced26eb050ceb98ee9d5d6cdca8db448666986
src/greplin/scales/samplestats.py
python
UniformSample.__init__
(self)
Create an empty sample.
Create an empty sample.
[ "Create", "an", "empty", "sample", "." ]
def __init__(self): """Create an empty sample.""" super(UniformSample, self).__init__() self.sample = [0.0] * 1028 self.count = 0
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "UniformSample", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "sample", "=", "[", "0.0", "]", "*", "1028", "self", ".", "count", "=", "0" ]
https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L205-L210
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/markdown/markdown/extensions/footnotes.py
python
FootnoteExtension.makeFootnoteId
(self, id)
Return footnote link id.
Return footnote link id.
[ "Return", "footnote", "link", "id", "." ]
def makeFootnoteId(self, id): """ Return footnote link id. """ if self.getConfig("UNIQUE_IDS"): return 'fn:%d-%s' % (self.unique_prefix, id) else: return 'fn:%s' % id
[ "def", "makeFootnoteId", "(", "self", ",", "id", ")", ":", "if", "self", ".", "getConfig", "(", "\"UNIQUE_IDS\"", ")", ":", "return", "'fn:%d-%s'", "%", "(", "self", ".", "unique_prefix", ",", "id", ")", "else", ":", "return", "'fn:%s'", "%", "id" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/markdown/markdown/extensions/footnotes.py#L100-L105
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/table_column.py
python
TableColumn.get_edit_height
(self, object)
return self.edit_height
Returns the height of the column cell's row while it is being edited.
Returns the height of the column cell's row while it is being edited.
[ "Returns", "the", "height", "of", "the", "column", "cell", "s", "row", "while", "it", "is", "being", "edited", "." ]
def get_edit_height(self, object): """Returns the height of the column cell's row while it is being edited. """ return self.edit_height
[ "def", "get_edit_height", "(", "self", ",", "object", ")", ":", "return", "self", ".", "edit_height" ]
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/table_column.py#L170-L174
Runbook/runbook
7b68622f75ef09f654046f0394540025f3ee7445
src/actions/actions/rackspace-reboot/__init__.py
python
action
(**kwargs)
This method is called to action a reaction
This method is called to action a reaction
[ "This", "method", "is", "called", "to", "action", "a", "reaction" ]
def action(**kwargs): ''' This method is called to action a reaction ''' redata = kwargs['redata'] jdata = kwargs['jdata'] logger = kwargs['logger'] run = True # Check for Trigger if redata['trigger'] > jdata['failcount']: run = False # Check for lastrun checktime = time.time() - float(redata['lastrun']) if checktime < redata['frequency']: run = False if redata['data']['call_on'] not in jdata['check']['status']: run = False if run: return call_action(redata, jdata, logger) else: return None
[ "def", "action", "(", "*", "*", "kwargs", ")", ":", "redata", "=", "kwargs", "[", "'redata'", "]", "jdata", "=", "kwargs", "[", "'jdata'", "]", "logger", "=", "kwargs", "[", "'logger'", "]", "run", "=", "True", "# Check for Trigger", "if", "redata", "[...
https://github.com/Runbook/runbook/blob/7b68622f75ef09f654046f0394540025f3ee7445/src/actions/actions/rackspace-reboot/__init__.py#L13-L34
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/podding/migration/home_sync.py
python
CrossPodHomeSync._remoteHome
(self, txn)
Create a synthetic external home object that maps to the actual remote home.
Create a synthetic external home object that maps to the actual remote home.
[ "Create", "a", "synthetic", "external", "home", "object", "that", "maps", "to", "the", "actual", "remote", "home", "." ]
def _remoteHome(self, txn): """ Create a synthetic external home object that maps to the actual remote home. """ from txdav.caldav.datastore.sql_external import CalendarHomeExternal resourceID = yield txn.store().conduit.send_home_resource_id(txn, self.record, migrating=True) home = CalendarHomeExternal.makeSyntheticExternalHome(txn, self.record.uid, resourceID) if resourceID is not None else None if self.disabledRemote: home._migratingHome = True returnValue(home)
[ "def", "_remoteHome", "(", "self", ",", "txn", ")", ":", "from", "txdav", ".", "caldav", ".", "datastore", ".", "sql_external", "import", "CalendarHomeExternal", "resourceID", "=", "yield", "txn", ".", "store", "(", ")", ".", "conduit", ".", "send_home_resou...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/podding/migration/home_sync.py#L367-L377
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/cloud/clouds/linode.py
python
LinodeAPI.create
(self, vm_)
create implementation
create implementation
[ "create", "implementation" ]
def create(self, vm_): """create implementation"""
[ "def", "create", "(", "self", ",", "vm_", ")", ":" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/linode.py#L427-L428
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modform_hecketriangle/hecke_triangle_groups.py
python
HeckeTriangleGroup.U
(self)
return self.T() * self.S()
r""" Return an alternative generator of ``self`` instead of ``T``. ``U`` stabilizes ``rho`` and has order ``2*self.n()``. If ``n=infinity`` then ``U`` is parabolic and has infinite order, it then fixes the cusp ``[-1]``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.hecke_triangle_groups import HeckeTriangleGroup sage: HeckeTriangleGroup(3).U() [ 1 -1] [ 1 0] sage: HeckeTriangleGroup(3).U()^3 == -HeckeTriangleGroup(3).I() True sage: HeckeTriangleGroup(3).U()^6 == HeckeTriangleGroup(3).I() True sage: HeckeTriangleGroup(10).U() [lam -1] [ 1 0] sage: HeckeTriangleGroup(10).U()^10 == -HeckeTriangleGroup(10).I() True sage: HeckeTriangleGroup(10).U()^20 == HeckeTriangleGroup(10).I() True sage: HeckeTriangleGroup(10).U().parent() Hecke triangle group for n = 10
r""" Return an alternative generator of ``self`` instead of ``T``. ``U`` stabilizes ``rho`` and has order ``2*self.n()``.
[ "r", "Return", "an", "alternative", "generator", "of", "self", "instead", "of", "T", ".", "U", "stabilizes", "rho", "and", "has", "order", "2", "*", "self", ".", "n", "()", "." ]
def U(self): r""" Return an alternative generator of ``self`` instead of ``T``. ``U`` stabilizes ``rho`` and has order ``2*self.n()``. If ``n=infinity`` then ``U`` is parabolic and has infinite order, it then fixes the cusp ``[-1]``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.hecke_triangle_groups import HeckeTriangleGroup sage: HeckeTriangleGroup(3).U() [ 1 -1] [ 1 0] sage: HeckeTriangleGroup(3).U()^3 == -HeckeTriangleGroup(3).I() True sage: HeckeTriangleGroup(3).U()^6 == HeckeTriangleGroup(3).I() True sage: HeckeTriangleGroup(10).U() [lam -1] [ 1 0] sage: HeckeTriangleGroup(10).U()^10 == -HeckeTriangleGroup(10).I() True sage: HeckeTriangleGroup(10).U()^20 == HeckeTriangleGroup(10).I() True sage: HeckeTriangleGroup(10).U().parent() Hecke triangle group for n = 10 """ return self.T() * self.S()
[ "def", "U", "(", "self", ")", ":", "return", "self", ".", "T", "(", ")", "*", "self", ".", "S", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform_hecketriangle/hecke_triangle_groups.py#L432-L461
raiden-network/raiden
76c68b426a6f81f173b9a2c09bd88a610502c38b
raiden/transfer/mediated_transfer/initiator.py
python
handle_block
( initiator_state: InitiatorTransferState, state_change: Block, channel_state: NettingChannelState, pseudo_random_generator: random.Random, )
Checks if the lock has expired, and if it has sends a remove expired lock and emits the failing events.
Checks if the lock has expired, and if it has sends a remove expired lock and emits the failing events.
[ "Checks", "if", "the", "lock", "has", "expired", "and", "if", "it", "has", "sends", "a", "remove", "expired", "lock", "and", "emits", "the", "failing", "events", "." ]
def handle_block( initiator_state: InitiatorTransferState, state_change: Block, channel_state: NettingChannelState, pseudo_random_generator: random.Random, ) -> TransitionResult[Optional[InitiatorTransferState]]: """Checks if the lock has expired, and if it has sends a remove expired lock and emits the failing events. """ secrethash = initiator_state.transfer.lock.secrethash locked_lock = channel_state.our_state.secrethashes_to_lockedlocks.get(secrethash) if not locked_lock: if channel_state.partner_state.secrethashes_to_lockedlocks.get(secrethash): return TransitionResult(initiator_state, []) else: # if lock is not in our or our partner's locked locks then the # task can go return TransitionResult(None, []) lock_expiration_threshold = BlockExpiration( locked_lock.expiration + DEFAULT_WAIT_BEFORE_LOCK_REMOVAL ) lock_has_expired = channel.is_lock_expired( end_state=channel_state.our_state, lock=locked_lock, block_number=state_change.block_number, lock_expiration_threshold=lock_expiration_threshold, ) events: List[Event] = [] if lock_has_expired and initiator_state.transfer_state != "transfer_expired": is_channel_open = channel.get_status(channel_state) == ChannelState.STATE_OPENED if is_channel_open: recipient_address = channel_state.partner_state.address recipient_metadata = get_address_metadata(recipient_address, [initiator_state.route]) expired_lock_events = channel.send_lock_expired( channel_state=channel_state, locked_lock=locked_lock, pseudo_random_generator=pseudo_random_generator, recipient_metadata=recipient_metadata, ) events.extend(expired_lock_events) if initiator_state.received_secret_request: reason = "lock expired, despite receiving secret request" else: reason = "lock expired" transfer_description = initiator_state.transfer_description payment_identifier = transfer_description.payment_identifier # TODO: When we introduce multiple transfers per payment this needs to be # reconsidered. As we would want to try other routes once a route # has failed, and a transfer failing does not mean the entire payment # would have to fail. # Related issue: https://github.com/raiden-network/raiden/issues/2329 payment_failed = EventPaymentSentFailed( token_network_registry_address=transfer_description.token_network_registry_address, token_network_address=transfer_description.token_network_address, identifier=payment_identifier, target=transfer_description.target, reason=reason, ) route_failed = EventRouteFailed( secrethash=secrethash, route=initiator_state.route.route, token_network_address=transfer_description.token_network_address, ) unlock_failed = EventUnlockFailed( identifier=payment_identifier, secrethash=initiator_state.transfer_description.secrethash, reason=reason, ) lock_exists = channel.lock_exists_in_either_channel_side( channel_state=channel_state, secrethash=secrethash ) initiator_state.transfer_state = "transfer_expired" return TransitionResult( # If the lock is either in our state or partner state we keep the # task around to wait for the LockExpired messages to sync. # Check https://github.com/raiden-network/raiden/issues/3183 initiator_state if lock_exists else None, events + [payment_failed, route_failed, unlock_failed], ) else: return TransitionResult(initiator_state, events)
[ "def", "handle_block", "(", "initiator_state", ":", "InitiatorTransferState", ",", "state_change", ":", "Block", ",", "channel_state", ":", "NettingChannelState", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", "TransitionResult", "[", ...
https://github.com/raiden-network/raiden/blob/76c68b426a6f81f173b9a2c09bd88a610502c38b/raiden/transfer/mediated_transfer/initiator.py#L140-L228
panchunguang/ccks_baidu_entity_link
f6eb5298620b460f2f1222a3b182d15c938c4ea2
code/ER_ner_bert_crf.py
python
train
()
NER模型训练,9折交叉验证,分贝用loss和f1保存模型,共18个 :return:
NER模型训练,9折交叉验证,分贝用loss和f1保存模型,共18个 :return:
[ "NER模型训练,9折交叉验证,分贝用loss和f1保存模型,共18个", ":", "return", ":" ]
def train(): ''' NER模型训练,9折交叉验证,分贝用loss和f1保存模型,共18个 :return: ''' train = get_input('data/input_train_ner.pkl') kfold = KFold(n_splits=9, shuffle=False) for i, (tra_index, val_index) in enumerate(kfold.split(train[0])): K.clear_session() input_train = [tra[tra_index] for tra in train] input_val = [tra[val_index] for tra in train] filepath_loss = "model/NER_bert_crf_loss.h5_"+str(i) filepath_f1 = "model/NER_bert_crf_f1.h5_"+str(i) evaluate = Evaluate((input_val[:-1], input_val[-1]), filepath_f1) checkpoint = ModelCheckpoint(filepath_loss, monitor='val_loss', verbose=2, save_best_only=True, mode='min') earlystopping = EarlyStopping(monitor='val_loss', min_delta=0.000001, patience=2, verbose=2, mode='auto') lrate = LearningRateScheduler(step_decay,verbose=2) callbacks = [checkpoint,evaluate,lrate,earlystopping] model = bert_model() print(model.summary()) logging.debug(str(i)*30) model = model.fit(input_train[:-1], input_train[-1], batch_size=arg.batch_size, epochs=arg.num_epochs, validation_data=(input_val[:-1], input_val[-1]), verbose=1, callbacks=callbacks) logging.debug(arg.__str__()) logging.debug(model.history) logging.debug(np.min(model.history['val_loss']))
[ "def", "train", "(", ")", ":", "train", "=", "get_input", "(", "'data/input_train_ner.pkl'", ")", "kfold", "=", "KFold", "(", "n_splits", "=", "9", ",", "shuffle", "=", "False", ")", "for", "i", ",", "(", "tra_index", ",", "val_index", ")", "in", "enum...
https://github.com/panchunguang/ccks_baidu_entity_link/blob/f6eb5298620b460f2f1222a3b182d15c938c4ea2/code/ER_ner_bert_crf.py#L100-L127
cheind/tf-matplotlib
c6904d3d2d306d9a479c24fbcb1f674a57dafd0e
tfmpl/create.py
python
create_figure
(*fig_args, **fig_kwargs)
return fig
Create a single figure. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs in their respective thread, avoid usage of pyplot where possible.
Create a single figure.
[ "Create", "a", "single", "figure", "." ]
def create_figure(*fig_args, **fig_kwargs): '''Create a single figure. Args and Kwargs are passed to `matplotlib.figure.Figure`. This routine is provided in order to avoid usage of pyplot which is stateful and not thread safe. As drawing routines in tf-matplotlib are called from py-funcs in their respective thread, avoid usage of pyplot where possible. ''' fig = Figure(*fig_args, **fig_kwargs) # Attach canvas FigureCanvas(fig) return fig
[ "def", "create_figure", "(", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", ":", "fig", "=", "Figure", "(", "*", "fig_args", ",", "*", "*", "fig_kwargs", ")", "# Attach canvas", "FigureCanvas", "(", "fig", ")", "return", "fig" ]
https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/create.py#L9-L23
Tencent/GAutomator
0ac9f849d1ca2c59760a91c5c94d3db375a380cd
GAutomatorIos/ga2/device/iOS/wda/__init__.py
python
Alert.click
(self, button_name)
return self.http.post('/alert/accept', data={"name": button_name})
Args: - button_name: the name of the button
Args: - button_name: the name of the button
[ "Args", ":", "-", "button_name", ":", "the", "name", "of", "the", "button" ]
def click(self, button_name): """ Args: - button_name: the name of the button """ # Actually, It has no difference POST to accept or dismiss return self.http.post('/alert/accept', data={"name": button_name})
[ "def", "click", "(", "self", ",", "button_name", ")", ":", "# Actually, It has no difference POST to accept or dismiss", "return", "self", ".", "http", ".", "post", "(", "'/alert/accept'", ",", "data", "=", "{", "\"name\"", ":", "button_name", "}", ")" ]
https://github.com/Tencent/GAutomator/blob/0ac9f849d1ca2c59760a91c5c94d3db375a380cd/GAutomatorIos/ga2/device/iOS/wda/__init__.py#L603-L609
santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning
97ff2ae3ba9f2d478e174444c4e0f5349f28c319
texar_repo/texar/data/data/mono_text_data.py
python
MonoTextData.embedding_init_value
(self)
return self._embedding.word_vecs
The `Tensor` containing the embedding value loaded from file. `None` if embedding is not specified.
The `Tensor` containing the embedding value loaded from file. `None` if embedding is not specified.
[ "The", "Tensor", "containing", "the", "embedding", "value", "loaded", "from", "file", ".", "None", "if", "embedding", "is", "not", "specified", "." ]
def embedding_init_value(self): """The `Tensor` containing the embedding value loaded from file. `None` if embedding is not specified. """ if self._embedding is None: return None return self._embedding.word_vecs
[ "def", "embedding_init_value", "(", "self", ")", ":", "if", "self", ".", "_embedding", "is", "None", ":", "return", "None", "return", "self", ".", "_embedding", ".", "word_vecs" ]
https://github.com/santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning/blob/97ff2ae3ba9f2d478e174444c4e0f5349f28c319/texar_repo/texar/data/data/mono_text_data.py#L570-L576
achillesrasquinha/pipupgrade
b78e06cbdc5bf4dde8e9568423f9341a91cd44e1
src/pipupgrade/commands/util/__init__.py
python
group_commands
(group, commands)
return group
Add command-paths to a click.Group
Add command-paths to a click.Group
[ "Add", "command", "-", "paths", "to", "a", "click", ".", "Group" ]
def group_commands(group, commands): """ Add command-paths to a click.Group """ commands = sequencify(commands, type_ = tuple) for command in commands: head, tail = command.rsplit(".", 1) tails = ("", tail, "command") for i, tail in enumerate(tails): try: path = "%s.%s" % (command, tail) command = import_handler(path) break except: if i == len(tails) - 1: raise group.add_command(command) return group
[ "def", "group_commands", "(", "group", ",", "commands", ")", ":", "commands", "=", "sequencify", "(", "commands", ",", "type_", "=", "tuple", ")", "for", "command", "in", "commands", ":", "head", ",", "tail", "=", "command", ".", "rsplit", "(", "\".\"", ...
https://github.com/achillesrasquinha/pipupgrade/blob/b78e06cbdc5bf4dde8e9568423f9341a91cd44e1/src/pipupgrade/commands/util/__init__.py#L8-L30
astropy/astroquery
11c9c83fa8e5f948822f8f73c854ec4b72043016
astroquery/esa/jwst/core.py
python
JwstClass.__get_proposal_id_condition
(self, *, value=None)
return condition
[]
def __get_proposal_id_condition(self, *, value=None): condition = "" if(value is not None): if(not isinstance(value, str)): raise ValueError("proposal_id must be string") else: condition = " AND proposal_id ILIKE '%"+value+"%' " return condition
[ "def", "__get_proposal_id_condition", "(", "self", ",", "*", ",", "value", "=", "None", ")", ":", "condition", "=", "\"\"", "if", "(", "value", "is", "not", "None", ")", ":", "if", "(", "not", "isinstance", "(", "value", ",", "str", ")", ")", ":", ...
https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/esa/jwst/core.py#L1186-L1194
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GL/EXT/EGL_image_storage.py
python
glInitEglImageStorageEXT
()
return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
Return boolean indicating whether this extension is available
[ "Return", "boolean", "indicating", "whether", "this", "extension", "is", "available" ]
def glInitEglImageStorageEXT(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
[ "def", "glInitEglImageStorageEXT", "(", ")", ":", "from", "OpenGL", "import", "extensions", "return", "extensions", ".", "hasGLExtension", "(", "_EXTENSION_NAME", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/EXT/EGL_image_storage.py#L39-L42
jamesls/python-keepassx
cf3c8f33b17b8eb6beaa1a8dd83ce1921dcde975
keepassx/db.py
python
Header.encryption_type
(self)
[]
def encryption_type(self): for name, value in self.ENCRYPTION_TYPES[1:]: if value & self.flags: return name
[ "def", "encryption_type", "(", "self", ")", ":", "for", "name", ",", "value", "in", "self", ".", "ENCRYPTION_TYPES", "[", "1", ":", "]", ":", "if", "value", "&", "self", ".", "flags", ":", "return", "name" ]
https://github.com/jamesls/python-keepassx/blob/cf3c8f33b17b8eb6beaa1a8dd83ce1921dcde975/keepassx/db.py#L137-L140
matousc89/padasip
b44c2815000dd4d1b855c49e469072e919df15cd
padasip/ann/mlp.py
python
Layer.__init__
(self, n_layer, n_input, activation_f, mu)
[]
def __init__(self, n_layer, n_input, activation_f, mu): sigma = n_input**(-0.5) if mu == "auto": self.mu = sigma else: self.mu = mu self.n_input = n_input self.w = np.random.normal(0, sigma, (n_layer, n_input+1)) self.x = np.ones(n_input+1) self.y = np.zeros(n_input+1) self.f = activation_f
[ "def", "__init__", "(", "self", ",", "n_layer", ",", "n_input", ",", "activation_f", ",", "mu", ")", ":", "sigma", "=", "n_input", "**", "(", "-", "0.5", ")", "if", "mu", "==", "\"auto\"", ":", "self", ".", "mu", "=", "sigma", "else", ":", "self", ...
https://github.com/matousc89/padasip/blob/b44c2815000dd4d1b855c49e469072e919df15cd/padasip/ann/mlp.py#L114-L124
cleverhans-lab/cleverhans
e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d
cleverhans/experimental/certification/utils.py
python
tf_lanczos_smallest_eigval
( vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.float32, )
return smallest_eigval, smallest_eigvec
Computes smallest eigenvector and eigenvalue using Lanczos in pure TF. This function computes smallest eigenvector and eigenvalue of the matrix which is implicitly specified by `vector_prod_fn`. `vector_prod_fn` is a function which takes `x` and returns a product of matrix in consideration and `x`. Computation is done using Lanczos algorithm, see https://en.wikipedia.org/wiki/Lanczos_algorithm#The_algorithm Args: vector_prod_fn: function which takes a vector as an input and returns matrix vector product. matrix_dim: dimentionality of the matrix. initial_vector: guess vector to start the algorithm with num_iter: user-defined number of iterations for the algorithm max_iter: maximum number of iterations. collapse_tol: tolerance to determine collapse of the Krylov subspace dtype: type of data Returns: tuple of (eigenvalue, eigenvector) of smallest eigenvalue and corresponding eigenvector.
Computes smallest eigenvector and eigenvalue using Lanczos in pure TF.
[ "Computes", "smallest", "eigenvector", "and", "eigenvalue", "using", "Lanczos", "in", "pure", "TF", "." ]
def tf_lanczos_smallest_eigval( vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.float32, ): """Computes smallest eigenvector and eigenvalue using Lanczos in pure TF. This function computes smallest eigenvector and eigenvalue of the matrix which is implicitly specified by `vector_prod_fn`. `vector_prod_fn` is a function which takes `x` and returns a product of matrix in consideration and `x`. Computation is done using Lanczos algorithm, see https://en.wikipedia.org/wiki/Lanczos_algorithm#The_algorithm Args: vector_prod_fn: function which takes a vector as an input and returns matrix vector product. matrix_dim: dimentionality of the matrix. initial_vector: guess vector to start the algorithm with num_iter: user-defined number of iterations for the algorithm max_iter: maximum number of iterations. collapse_tol: tolerance to determine collapse of the Krylov subspace dtype: type of data Returns: tuple of (eigenvalue, eigenvector) of smallest eigenvalue and corresponding eigenvector. """ # alpha will store diagonal elements alpha = tf.TensorArray(dtype, size=1, dynamic_size=True, element_shape=()) # beta will store off diagonal elements beta = tf.TensorArray(dtype, size=0, dynamic_size=True, element_shape=()) # q will store Krylov space basis q_vectors = tf.TensorArray( dtype, size=1, dynamic_size=True, element_shape=(matrix_dim, 1) ) # If start vector is all zeros, make it a random normal vector and run for max_iter if tf.norm(initial_vector) < collapse_tol: initial_vector = tf.random_normal(shape=(matrix_dim, 1), dtype=dtype) num_iter = max_iter w = initial_vector / tf.norm(initial_vector) # Iteration 0 of Lanczos q_vectors = q_vectors.write(0, w) w_ = vector_prod_fn(w) cur_alpha = tf.reduce_sum(w_ * w) alpha = alpha.write(0, cur_alpha) w_ = w_ - tf.scalar_mul(cur_alpha, w) w_prev = w w = w_ # Subsequent iterations of Lanczos for i in tf.range(1, num_iter): cur_beta = tf.norm(w) if cur_beta < collapse_tol: # return early if Krylov subspace collapsed break # cur_beta is larger than collapse_tol, # so division will return finite result. w = w / cur_beta w_ = vector_prod_fn(w) cur_alpha = tf.reduce_sum(w_ * w) q_vectors = q_vectors.write(i, w) alpha = alpha.write(i, cur_alpha) beta = beta.write(i - 1, cur_beta) w_ = w_ - tf.scalar_mul(cur_alpha, w) - tf.scalar_mul(cur_beta, w_prev) w_prev = w w = w_ alpha = alpha.stack() beta = beta.stack() q_vectors = tf.reshape(q_vectors.stack(), (-1, matrix_dim)) offdiag_submatrix = tf.linalg.diag(beta) tridiag_matrix = ( tf.linalg.diag(alpha) + tf.pad(offdiag_submatrix, [[0, 1], [1, 0]]) + tf.pad(offdiag_submatrix, [[1, 0], [0, 1]]) ) eigvals, eigvecs = tf.linalg.eigh(tridiag_matrix) smallest_eigval = eigvals[0] smallest_eigvec = tf.matmul(tf.reshape(eigvecs[:, 0], (1, -1)), q_vectors) smallest_eigvec = smallest_eigvec / tf.norm(smallest_eigvec) smallest_eigvec = tf.reshape(smallest_eigvec, (matrix_dim, 1)) return smallest_eigval, smallest_eigvec
[ "def", "tf_lanczos_smallest_eigval", "(", "vector_prod_fn", ",", "matrix_dim", ",", "initial_vector", ",", "num_iter", "=", "1000", ",", "max_iter", "=", "1000", ",", "collapse_tol", "=", "1e-9", ",", "dtype", "=", "tf", ".", "float32", ",", ")", ":", "# alp...
https://github.com/cleverhans-lab/cleverhans/blob/e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d/cleverhans/experimental/certification/utils.py#L228-L326
OpenZWave/python-openzwave
8be4c070294348f3fc268bc1d7ad2c535f352f5a
src-api/openzwave/controller.py
python
ZWaveController.begin_command_has_node_failed
(self, node_id)
return self._network.manager.beginControllerCommand(self.home_id, \ self.CMD_HASNODEFAILED, self.zwcallback, nodeId=node_id)
Check whether a node is in the controller's failed nodes list. :param node_id: Used only with the ReplaceFailedNode command, to specify the node that is going to be replaced. :type node_id: int :return: True if the command was accepted and has started. :rtype: bool
Check whether a node is in the controller's failed nodes list.
[ "Check", "whether", "a", "node", "is", "in", "the", "controller", "s", "failed", "nodes", "list", "." ]
def begin_command_has_node_failed(self, node_id): """ Check whether a node is in the controller's failed nodes list. :param node_id: Used only with the ReplaceFailedNode command, to specify the node that is going to be replaced. :type node_id: int :return: True if the command was accepted and has started. :rtype: bool """ return self._network.manager.beginControllerCommand(self.home_id, \ self.CMD_HASNODEFAILED, self.zwcallback, nodeId=node_id)
[ "def", "begin_command_has_node_failed", "(", "self", ",", "node_id", ")", ":", "return", "self", ".", "_network", ".", "manager", ".", "beginControllerCommand", "(", "self", ".", "home_id", ",", "self", ".", "CMD_HASNODEFAILED", ",", "self", ".", "zwcallback", ...
https://github.com/OpenZWave/python-openzwave/blob/8be4c070294348f3fc268bc1d7ad2c535f352f5a/src-api/openzwave/controller.py#L1185-L1196
mit-han-lab/once-for-all
4f6fce3652ee4553ea811d38f32f90ac8b1bc378
ofa/tutorial/evolution_finder.py
python
EvolutionFinder.crossover_sample
(self, sample1, sample2)
[]
def crossover_sample(self, sample1, sample2): constraint = self.efficiency_constraint while True: new_sample = copy.deepcopy(sample1) for key in new_sample.keys(): if not isinstance(new_sample[key], list): continue for i in range(len(new_sample[key])): new_sample[key][i] = random.choice([sample1[key][i], sample2[key][i]]) efficiency = self.efficiency_predictor.predict_efficiency(new_sample) if efficiency <= constraint: return new_sample, efficiency
[ "def", "crossover_sample", "(", "self", ",", "sample1", ",", "sample2", ")", ":", "constraint", "=", "self", ".", "efficiency_constraint", "while", "True", ":", "new_sample", "=", "copy", ".", "deepcopy", "(", "sample1", ")", "for", "key", "in", "new_sample"...
https://github.com/mit-han-lab/once-for-all/blob/4f6fce3652ee4553ea811d38f32f90ac8b1bc378/ofa/tutorial/evolution_finder.py#L137-L149
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/musicbrainzngs/musicbrainz.py
python
browse_artists
(recording=None, release=None, release_group=None, work=None, includes=[], limit=None, offset=None)
return _browse_impl("artist", includes, limit, offset, params)
Get all artists linked to a recording, a release or a release group. You need to give one MusicBrainz ID. *Available includes*: {includes}
Get all artists linked to a recording, a release or a release group. You need to give one MusicBrainz ID.
[ "Get", "all", "artists", "linked", "to", "a", "recording", "a", "release", "or", "a", "release", "group", ".", "You", "need", "to", "give", "one", "MusicBrainz", "ID", "." ]
def browse_artists(recording=None, release=None, release_group=None, work=None, includes=[], limit=None, offset=None): """Get all artists linked to a recording, a release or a release group. You need to give one MusicBrainz ID. *Available includes*: {includes}""" params = {"recording": recording, "release": release, "release-group": release_group, "work": work} return _browse_impl("artist", includes, limit, offset, params)
[ "def", "browse_artists", "(", "recording", "=", "None", ",", "release", "=", "None", ",", "release_group", "=", "None", ",", "work", "=", "None", ",", "includes", "=", "[", "]", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "params...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/musicbrainzngs/musicbrainz.py#L1082-L1092
arskom/spyne
88b8e278335f03c7e615b913d6dabc2b8141730e
spyne/util/six.py
python
add_metaclass
(metaclass)
return wrapper
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
[ "Class", "decorator", "for", "creating", "a", "class", "with", "a", "metaclass", "." ]
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) if hasattr(cls, '__qualname__'): orig_vars['__qualname__'] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "...
https://github.com/arskom/spyne/blob/88b8e278335f03c7e615b913d6dabc2b8141730e/spyne/util/six.py#L869-L884
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/jax/schedules.py
python
BaseSchedule.value
(self, count: JTensor)
Returns the value of schedule at step 'count'. Args: count: a scalar uint32 array. Returns: A float32 value of the schedule at step 'count' as a scalar array.
Returns the value of schedule at step 'count'.
[ "Returns", "the", "value", "of", "schedule", "at", "step", "count", "." ]
def value(self, count: JTensor) -> JTensor: # pylint:disable=invalid-name """Returns the value of schedule at step 'count'. Args: count: a scalar uint32 array. Returns: A float32 value of the schedule at step 'count' as a scalar array. """ raise NotImplementedError()
[ "def", "value", "(", "self", ",", "count", ":", "JTensor", ")", "->", "JTensor", ":", "# pylint:disable=invalid-name", "raise", "NotImplementedError", "(", ")" ]
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/jax/schedules.py#L45-L54
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/partition_tuple.py
python
RegularPartitionTuples_size.__iter__
(self)
r""" Iterate through the class of `\ell`-regular partition tuples of a fixed size. EXAMPLES:: sage: PartitionTuples(size=4, regular=2)[:10] [([4]), ([3, 1]), ([4], []), ([3, 1], []), ([3], [1]), ([2, 1], [1]), ([2], [2]), ([1], [3]), ([1], [2, 1]), ([], [4])]
r""" Iterate through the class of `\ell`-regular partition tuples of a fixed size.
[ "r", "Iterate", "through", "the", "class", "of", "\\", "ell", "-", "regular", "partition", "tuples", "of", "a", "fixed", "size", "." ]
def __iter__(self): r""" Iterate through the class of `\ell`-regular partition tuples of a fixed size. EXAMPLES:: sage: PartitionTuples(size=4, regular=2)[:10] [([4]), ([3, 1]), ([4], []), ([3, 1], []), ([3], [1]), ([2, 1], [1]), ([2], [2]), ([1], [3]), ([1], [2, 1]), ([], [4])] """ for level in PositiveIntegers(): for mu in RegularPartitionTuples_level_size(level, self._size, self._ell): yield self.element_class(self, list(mu))
[ "def", "__iter__", "(", "self", ")", ":", "for", "level", "in", "PositiveIntegers", "(", ")", ":", "for", "mu", "in", "RegularPartitionTuples_level_size", "(", "level", ",", "self", ".", "_size", ",", "self", ".", "_ell", ")", ":", "yield", "self", ".", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/partition_tuple.py#L2924-L2945
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
HierarchicalRL/hrl_rewards.py
python
reward_user_deepmoji
(conversations)
return rewards
Allocates reward based on deepmoji sentiment of user response
Allocates reward based on deepmoji sentiment of user response
[ "Allocates", "reward", "based", "on", "deepmoji", "sentiment", "of", "user", "response" ]
def reward_user_deepmoji(conversations): """Allocates reward based on deepmoji sentiment of user response""" # Init deepmoji just once if 'botmoji' not in globals(): print('Loading deepmoji') global botmoji botmoji = Botmoji() num_convs = len(conversations) episode_len = (len(conversations[0]) - 1) // 2 # Flattened user responses user_responses = [resp for conv in conversations for resp in conv[2::2]] # Run deepmoji reward_multiplier = _get_reward_multiplier() user_emojis = botmoji.encode_multiple(user_responses) rewards = np.dot(user_emojis, reward_multiplier) for i, resp in enumerate(user_responses): if '<unk>' in user_responses[i]: rewards[i] = -0.5 rewards = rewards.reshape(num_convs, episode_len) return rewards
[ "def", "reward_user_deepmoji", "(", "conversations", ")", ":", "# Init deepmoji just once", "if", "'botmoji'", "not", "in", "globals", "(", ")", ":", "print", "(", "'Loading deepmoji'", ")", "global", "botmoji", "botmoji", "=", "Botmoji", "(", ")", "num_convs", ...
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/HierarchicalRL/hrl_rewards.py#L204-L227
pysmt/pysmt
ade4dc2a825727615033a96d31c71e9f53ce4764
pysmt/typing.py
python
_IntType.__init__
(self)
[]
def __init__(self): decl = _TypeDecl("Int", 0) PySMTType.__init__(self, decl=decl, args=None)
[ "def", "__init__", "(", "self", ")", ":", "decl", "=", "_TypeDecl", "(", "\"Int\"", ",", "0", ")", "PySMTType", ".", "__init__", "(", "self", ",", "decl", "=", "decl", ",", "args", "=", "None", ")" ]
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/typing.py#L144-L146
pyGrowler/Growler
5492466d8828115bb04c665917d6aeb4f4323f44
growler/routing.py
python
Router.subrouters
(self)
Generator of sub-routers (middleware inheriting from Router) contained within this router.
Generator of sub-routers (middleware inheriting from Router) contained within this router.
[ "Generator", "of", "sub", "-", "routers", "(", "middleware", "inheriting", "from", "Router", ")", "contained", "within", "this", "router", "." ]
def subrouters(self): """ Generator of sub-routers (middleware inheriting from Router) contained within this router. """ yield from filter(lambda mw: isinstance(mw.func, Router), self.mw_list)
[ "def", "subrouters", "(", "self", ")", ":", "yield", "from", "filter", "(", "lambda", "mw", ":", "isinstance", "(", "mw", ".", "func", ",", "Router", ")", ",", "self", ".", "mw_list", ")" ]
https://github.com/pyGrowler/Growler/blob/5492466d8828115bb04c665917d6aeb4f4323f44/growler/routing.py#L488-L493
renemarc/home-assistant-config
775d60ad436cd0f432d2260e503b530920041165
custom_components/hacs/repositories/repository.py
python
HacsRepository.config_flow
(self)
return False
Return bool if integration has config_flow.
Return bool if integration has config_flow.
[ "Return", "bool", "if", "integration", "has", "config_flow", "." ]
def config_flow(self): """Return bool if integration has config_flow.""" if self.integration_manifest: if self.data.full_name == "hacs/integration": return False return self.integration_manifest.get("config_flow", False) return False
[ "def", "config_flow", "(", "self", ")", ":", "if", "self", ".", "integration_manifest", ":", "if", "self", ".", "data", ".", "full_name", "==", "\"hacs/integration\"", ":", "return", "False", "return", "self", ".", "integration_manifest", ".", "get", "(", "\...
https://github.com/renemarc/home-assistant-config/blob/775d60ad436cd0f432d2260e503b530920041165/custom_components/hacs/repositories/repository.py#L136-L142
theelous3/asks
5c58e2ad3ff8158bf6673475bfb6ee0f6817b2aa
asks/request_object.py
python
RequestProcessor._redirect
(self, response_obj)
return response_obj
Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect. Returns: Response: May or may not be the result of recursive calls due to redirects! Notes: If it does redirect, it calls the appropriate method with the redirect location, returning the response object. Furthermore, if there is a redirect, this function is recursive in a roundabout way, storing the previous response object in `.history_objects`.
Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect.
[ "Calls", "the", "_check_redirect", "method", "of", "the", "supplied", "response", "object", "in", "order", "to", "determine", "if", "the", "http", "status", "code", "indicates", "a", "redirect", "." ]
async def _redirect(self, response_obj): """ Calls the _check_redirect method of the supplied response object in order to determine if the http status code indicates a redirect. Returns: Response: May or may not be the result of recursive calls due to redirects! Notes: If it does redirect, it calls the appropriate method with the redirect location, returning the response object. Furthermore, if there is a redirect, this function is recursive in a roundabout way, storing the previous response object in `.history_objects`. """ redirect, force_get, location = False, None, None if 300 <= response_obj.status_code < 400: if response_obj.status_code == 303: self.data, self.json, self.files = None, None, None if response_obj.status_code in [301, 305]: # redirect / force GET / location redirect = True force_get = False else: redirect = True force_get = True location = response_obj.headers["Location"] if redirect: allow_redirect = True location = urljoin(self.uri, location.strip()) if self.auth is not None: if not self.auth_off_domain: allow_redirect = self._location_auth_protect(location) self.uri = location l_scheme, l_netloc, *_ = urlparse(location) if l_scheme != self.scheme or l_netloc != self.host: await self._get_new_sock() # follow redirect with correct http method type if force_get: self.history_objects.append(response_obj) self.method = "GET" else: self.history_objects.append(response_obj) self.max_redirects -= 1 try: if response_obj.headers["connection"].lower() == "close": await self._get_new_sock() except KeyError: pass if allow_redirect: _, response_obj = await self.make_request() return response_obj
[ "async", "def", "_redirect", "(", "self", ",", "response_obj", ")", ":", "redirect", ",", "force_get", ",", "location", "=", "False", ",", "None", ",", "None", "if", "300", "<=", "response_obj", ".", "status_code", "<", "400", ":", "if", "response_obj", ...
https://github.com/theelous3/asks/blob/5c58e2ad3ff8158bf6673475bfb6ee0f6817b2aa/asks/request_object.py#L335-L389
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/CNCCanvas.py
python
CNCCanvas.menuZoomOut
(self, event=None)
[]
def menuZoomOut(self, event=None): x = int(self.cget("width" ))//2 y = int(self.cget("height"))//2 self.zoomCanvas(x, y, 0.5)
[ "def", "menuZoomOut", "(", "self", ",", "event", "=", "None", ")", ":", "x", "=", "int", "(", "self", ".", "cget", "(", "\"width\"", ")", ")", "//", "2", "y", "=", "int", "(", "self", ".", "cget", "(", "\"height\"", ")", ")", "//", "2", "self",...
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/CNCCanvas.py#L996-L999
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
dragonfly/opt/opt_method_evaluator.py
python
OptMethodEvaluator.run_trial_iteration
(self)
Runs each method in self.methods once and stores the results to be saved.
Runs each method in self.methods once and stores the results to be saved.
[ "Runs", "each", "method", "in", "self", ".", "methods", "once", "and", "stores", "the", "results", "to", "be", "saved", "." ]
def run_trial_iteration(self): """ Runs each method in self.methods once and stores the results to be saved. """ curr_iter_results = Namespace() for data_type in self.data_to_be_saved: setattr(curr_iter_results, data_type, self._get_new_iter_results_array()) for data_type in self.data_to_be_saved_if_available: setattr(curr_iter_results, data_type, self._get_new_iter_results_array()) # Fetch pre-evaluation points. self.worker_manager.reset() prev_eval_qinfos = self._get_prev_eval_qinfos() if prev_eval_qinfos is not None: prev_eval_vals = [qinfo.val for qinfo in prev_eval_qinfos] self.reporter.writeln('Using %d pre-eval points with values. eval: %s (%0.4f).'%( \ len(prev_eval_qinfos), prev_eval_vals, max(prev_eval_vals))) else: self.reporter.writeln('Not using any pre-eval points.') # Will go through each method in this loop. for meth_iter in range(self.num_methods): curr_method = self.methods[meth_iter] curr_meth_options = self.method_options[curr_method] # Set prev_eval points and vals if prev_eval_qinfos is not None: curr_meth_options.prev_evaluations = Namespace(qinfos=prev_eval_qinfos) else: curr_meth_options.prev_evaluations = None # Reset worker manager self.worker_manager.reset() self.reporter.writeln( \ '\nResetting worker manager: worker_manager.experiment_designer:%s'%( \ str(self.worker_manager.experiment_designer))) # Call the method here. self._print_method_header(curr_method) history = self._optimise_with_method_on_func_caller(curr_method, self.func_caller, \ self.worker_manager, self.max_capital, curr_meth_options, self.reporter) # Now save results for current method for data_type in self.data_to_be_saved: data = getattr(history, data_type) data_pointer = getattr(curr_iter_results, data_type) data_pointer[meth_iter, 0] = data for data_type in self.data_to_be_saved_if_available: if hasattr(history, data_type): data = getattr(history, data_type) else: data = ['xx'] * len(history.query_points) data_pointer = getattr(curr_iter_results, data_type) data_pointer[meth_iter, 0] = data # Print out results comp_opt_val = history.curr_true_opt_vals[-1] num_evals = len(history.curr_true_opt_vals) self._print_method_result(curr_method, comp_opt_val, num_evals) # Save results of current iteration self.update_to_be_saved(curr_iter_results) self.save_pickle() self.save_results() # Save here self.update_to_be_saved(curr_iter_results) self.save_pickle()
[ "def", "run_trial_iteration", "(", "self", ")", ":", "curr_iter_results", "=", "Namespace", "(", ")", "for", "data_type", "in", "self", ".", "data_to_be_saved", ":", "setattr", "(", "curr_iter_results", ",", "data_type", ",", "self", ".", "_get_new_iter_results_ar...
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/dragonfly/opt/opt_method_evaluator.py#L157-L218
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/queue.py
python
_PySimpleQueue.put
(self, item, block=True, timeout=None)
Put the item on the queue. The optional 'block' and 'timeout' arguments are ignored, as this method never blocks. They are provided for compatibility with the Queue class.
Put the item on the queue.
[ "Put", "the", "item", "on", "the", "queue", "." ]
def put(self, item, block=True, timeout=None): '''Put the item on the queue. The optional 'block' and 'timeout' arguments are ignored, as this method never blocks. They are provided for compatibility with the Queue class. ''' self._queue.append(item) self._count.release()
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "_queue", ".", "append", "(", "item", ")", "self", ".", "_count", ".", "release", "(", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/queue.py#L272-L279
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pexpect/fdpexpect.py
python
fdspawn.terminate
(self, force=False)
Deprecated and invalid. Just raises an exception.
Deprecated and invalid. Just raises an exception.
[ "Deprecated", "and", "invalid", ".", "Just", "raises", "an", "exception", "." ]
def terminate (self, force=False): # pragma: no cover '''Deprecated and invalid. Just raises an exception.''' raise ExceptionPexpect('This method is not valid for file descriptors.')
[ "def", "terminate", "(", "self", ",", "force", "=", "False", ")", ":", "# pragma: no cover", "raise", "ExceptionPexpect", "(", "'This method is not valid for file descriptors.'", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pexpect/fdpexpect.py#L89-L91
chapmanb/bcbb
dbfb52711f0bfcc1d26c5a5b53c9ff4f50dc0027
distblast/scripts/homolog_seq_retrieval.py
python
_all_seqs
(ids, orgs, indexes)
Lazy generator of sequences from our indexes, with IDs properly set.
Lazy generator of sequences from our indexes, with IDs properly set.
[ "Lazy", "generator", "of", "sequences", "from", "our", "indexes", "with", "IDs", "properly", "set", "." ]
def _all_seqs(ids, orgs, indexes): """Lazy generator of sequences from our indexes, with IDs properly set. """ for i, cur_id in enumerate(ids): if cur_id: rec = indexes[i][cur_id] rec.id = cur_id rec.description = orgs[i] yield rec
[ "def", "_all_seqs", "(", "ids", ",", "orgs", ",", "indexes", ")", ":", "for", "i", ",", "cur_id", "in", "enumerate", "(", "ids", ")", ":", "if", "cur_id", ":", "rec", "=", "indexes", "[", "i", "]", "[", "cur_id", "]", "rec", ".", "id", "=", "cu...
https://github.com/chapmanb/bcbb/blob/dbfb52711f0bfcc1d26c5a5b53c9ff4f50dc0027/distblast/scripts/homolog_seq_retrieval.py#L52-L60
tushushu/imylu
33b0534981e59d81f225b246b608106a97af2a1f
imylu/tree/decision_tree.py
python
DecisionTree.predict
(self, data: ndarray, threshold=0.5)
return (prob >= threshold).astype(int)
Get the prediction of label. Arguments: data {ndarray} -- Testing data. Keyword Arguments: threshold {float} -- (default: {0.5}) Returns: ndarray -- Prediction of label.
Get the prediction of label.
[ "Get", "the", "prediction", "of", "label", "." ]
def predict(self, data: ndarray, threshold=0.5): """Get the prediction of label. Arguments: data {ndarray} -- Testing data. Keyword Arguments: threshold {float} -- (default: {0.5}) Returns: ndarray -- Prediction of label. """ prob = self.predict_prob(data) return (prob >= threshold).astype(int)
[ "def", "predict", "(", "self", ",", "data", ":", "ndarray", ",", "threshold", "=", "0.5", ")", ":", "prob", "=", "self", ".", "predict_prob", "(", "data", ")", "return", "(", "prob", ">=", "threshold", ")", ".", "astype", "(", "int", ")" ]
https://github.com/tushushu/imylu/blob/33b0534981e59d81f225b246b608106a97af2a1f/imylu/tree/decision_tree.py#L364-L378
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/werkzeug/_internal.py
python
_DictAccessorProperty.__init__
(self, name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)
[]
def __init__(self, name, default=None, load_func=None, dump_func=None, read_only=None, doc=None): self.name = name self.default = default self.load_func = load_func self.dump_func = dump_func if read_only is not None: self.read_only = read_only self.__doc__ = doc
[ "def", "__init__", "(", "self", ",", "name", ",", "default", "=", "None", ",", "load_func", "=", "None", ",", "dump_func", "=", "None", ",", "read_only", "=", "None", ",", "doc", "=", "None", ")", ":", "self", ".", "name", "=", "name", "self", ".",...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/werkzeug/_internal.py#L179-L187
Ridter/acefile
31f90219fb560364b6f5d27f512fccfae81d04f4
acefile.py
python
LZ77.dic_setsize
(self, dicsize)
Set the required dictionary size for the next LZ77 decompression run.
Set the required dictionary size for the next LZ77 decompression run.
[ "Set", "the", "required", "dictionary", "size", "for", "the", "next", "LZ77", "decompression", "run", "." ]
def dic_setsize(self, dicsize): """ Set the required dictionary size for the next LZ77 decompression run. """ self.__dictionary.set_size(dicsize)
[ "def", "dic_setsize", "(", "self", ",", "dicsize", ")", ":", "self", ".", "__dictionary", ".", "set_size", "(", "dicsize", ")" ]
https://github.com/Ridter/acefile/blob/31f90219fb560364b6f5d27f512fccfae81d04f4/acefile.py#L1515-L1519
mikecrittenden/zen-coding-gedit
49966219b1e9b7a1d0d8b4def6a32b6c386b8041
zencoding/stparser.py
python
_parse_abbreviations
(obj)
Parses all abbreviations inside dictionary @param obj: dict
Parses all abbreviations inside dictionary
[ "Parses", "all", "abbreviations", "inside", "dictionary" ]
def _parse_abbreviations(obj): """ Parses all abbreviations inside dictionary @param obj: dict """ for key, value in list(obj.items()): key = key.strip() if key[-1] == '+': # this is expando, leave 'value' as is obj[key] = _make_expando(key, value) else: m = re.search(re_tag, value) if m: obj[key] = _make_abbreviation(key, m.group(1), m.group(2), (m.group(3) == '/')) else: # assume it's reference to another abbreviation obj[key] = Entry(TYPE_REFERENCE, key, value)
[ "def", "_parse_abbreviations", "(", "obj", ")", ":", "for", "key", ",", "value", "in", "list", "(", "obj", ".", "items", "(", ")", ")", ":", "key", "=", "key", ".", "strip", "(", ")", "if", "key", "[", "-", "1", "]", "==", "'+'", ":", "#\t\t\tt...
https://github.com/mikecrittenden/zen-coding-gedit/blob/49966219b1e9b7a1d0d8b4def6a32b6c386b8041/zencoding/stparser.py#L77-L93
matthiask/plata
a743b8ef3838c1c2764620b18c394afc9708c4d5
plata/shop/views.py
python
Shop.reverse_url
(self, url_name, *args, **kwargs)
return reverse(url_name, *args, **kwargs)
Hook for customizing the reverse function
Hook for customizing the reverse function
[ "Hook", "for", "customizing", "the", "reverse", "function" ]
def reverse_url(self, url_name, *args, **kwargs): """ Hook for customizing the reverse function """ return reverse(url_name, *args, **kwargs)
[ "def", "reverse_url", "(", "self", ",", "url_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "reverse", "(", "url_name", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/matthiask/plata/blob/a743b8ef3838c1c2764620b18c394afc9708c4d5/plata/shop/views.py#L391-L395
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/studiomax/studiomaxscene.py
python
StudiomaxScene._createNativeLayerGroup
(self, name, nativeLayers=[])
return ''
\remarks implements the AbstractScene._createNativeLayerGroup method to create a new layer group in this scene based on the inputed name with the given layers \param name <str> \return <str> nativeLayerGroup || None
\remarks implements the AbstractScene._createNativeLayerGroup method to create a new layer group in this scene based on the inputed name with the given layers \param name <str> \return <str> nativeLayerGroup || None
[ "\\", "remarks", "implements", "the", "AbstractScene", ".", "_createNativeLayerGroup", "method", "to", "create", "a", "new", "layer", "group", "in", "this", "scene", "based", "on", "the", "inputed", "name", "with", "the", "given", "layers", "\\", "param", "nam...
def _createNativeLayerGroup(self, name, nativeLayers=[]): """ \remarks implements the AbstractScene._createNativeLayerGroup method to create a new layer group in this scene based on the inputed name with the given layers \param name <str> \return <str> nativeLayerGroup || None """ names = list(self.metaData().value('layerGroupNames')) states = list(self.metaData().value('layerGroupStates')) if (not name in names): names.append(str(name)) states.append(True) self.metaData().setValue('layerGroupNames', names) self.metaData().setValue('layerGroupStates', states) return name return ''
[ "def", "_createNativeLayerGroup", "(", "self", ",", "name", ",", "nativeLayers", "=", "[", "]", ")", ":", "names", "=", "list", "(", "self", ".", "metaData", "(", ")", ".", "value", "(", "'layerGroupNames'", ")", ")", "states", "=", "list", "(", "self"...
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/studiomax/studiomaxscene.py#L399-L413
nipy/nipype
cd4c34d935a43812d1756482fdc4034844e485b8
nipype/scripts/cli.py
python
crash
(crashfile, rerun, debug, ipydebug, dir)
Display Nipype crash files. For certain crash files, one can rerun a failed node in a temp directory. Examples:\n nipypecli crash crashfile.pklz\n nipypecli crash crashfile.pklz -r -i\n
Display Nipype crash files.
[ "Display", "Nipype", "crash", "files", "." ]
def crash(crashfile, rerun, debug, ipydebug, dir): """Display Nipype crash files. For certain crash files, one can rerun a failed node in a temp directory. Examples:\n nipypecli crash crashfile.pklz\n nipypecli crash crashfile.pklz -r -i\n """ from .crash_files import display_crash_file debug = "ipython" if ipydebug else debug if debug == "ipython": import sys from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB( mode="Verbose", color_scheme="Linux", call_pdb=1 ) display_crash_file(crashfile, rerun, debug, dir)
[ "def", "crash", "(", "crashfile", ",", "rerun", ",", "debug", ",", "ipydebug", ",", "dir", ")", ":", "from", ".", "crash_files", "import", "display_crash_file", "debug", "=", "\"ipython\"", "if", "ipydebug", "else", "debug", "if", "debug", "==", "\"ipython\"...
https://github.com/nipy/nipype/blob/cd4c34d935a43812d1756482fdc4034844e485b8/nipype/scripts/cli.py#L77-L96