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
sequence
function
stringlengths
18
4.83M
function_tokens
sequence
url
stringlengths
83
304
bastula/dicompyler
2643e0ee145cb7c699b3d36e3e4f07ac9dc7b1f2
dicompyler/main.py
python
MainFrame.OnPreferences
(self, evt)
Load and show the Preferences dialog box.
Load and show the Preferences dialog box.
[ "Load", "and", "show", "the", "Preferences", "dialog", "box", "." ]
def OnPreferences(self, evt): """Load and show the Preferences dialog box.""" self.prefmgr.Show()
[ "def", "OnPreferences", "(", "self", ",", "evt", ")", ":", "self", ".", "prefmgr", ".", "Show", "(", ")" ]
https://github.com/bastula/dicompyler/blob/2643e0ee145cb7c699b3d36e3e4f07ac9dc7b1f2/dicompyler/main.py#L846-L849
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/cards/params.py
python
PARAM.__init__
(self, key, values, comment='')
Creates a PARAM card Parameters ---------- key : str the name of the PARAM values : int/float/str/List varies depending on the type of PARAM comment : str; default='' a comment for the card
Creates a PARAM card
[ "Creates", "a", "PARAM", "card" ]
def __init__(self, key, values, comment=''): """ Creates a PARAM card Parameters ---------- key : str the name of the PARAM values : int/float/str/List varies depending on the type of PARAM comment : str; default='' a comment for the card """ if comment: self.comment = comment self.key = key if isinstance(values, list): pass elif isinstance(values, (integer_types, float_types, str)): values = [values] self.values = values if isinstance(self.values, tuple) or isinstance(self.values[0], (list, tuple)): raise TypeError((key, self.values))
[ "def", "__init__", "(", "self", ",", "key", ",", "values", ",", "comment", "=", "''", ")", ":", "if", "comment", ":", "self", ".", "comment", "=", "comment", "self", ".", "key", "=", "key", "if", "isinstance", "(", "values", ",", "list", ")", ":", "pass", "elif", "isinstance", "(", "values", ",", "(", "integer_types", ",", "float_types", ",", "str", ")", ")", ":", "values", "=", "[", "values", "]", "self", ".", "values", "=", "values", "if", "isinstance", "(", "self", ".", "values", ",", "tuple", ")", "or", "isinstance", "(", "self", ".", "values", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "(", "key", ",", "self", ".", "values", ")", ")" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/params.py#L314-L337
NordicSemiconductor/pc-nrfutil
d08e742128f2a3dac522601bc6b9f9b2b63952df
nordicsemi/lister/unix/unix_lister.py
python
create_id_string
(sno, PID, VID)
return "{}-{}-{}".format(sno, PID, VID)
[]
def create_id_string(sno, PID, VID): return "{}-{}-{}".format(sno, PID, VID)
[ "def", "create_id_string", "(", "sno", ",", "PID", ",", "VID", ")", ":", "return", "\"{}-{}-{}\"", ".", "format", "(", "sno", ",", "PID", ",", "VID", ")" ]
https://github.com/NordicSemiconductor/pc-nrfutil/blob/d08e742128f2a3dac522601bc6b9f9b2b63952df/nordicsemi/lister/unix/unix_lister.py#L46-L47
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/xml/sax/xmlreader.py
python
XMLReader.setFeature
(self, name, state)
Sets the state of a SAX2 feature.
Sets the state of a SAX2 feature.
[ "Sets", "the", "state", "of", "a", "SAX2", "feature", "." ]
def setFeature(self, name, state): "Sets the state of a SAX2 feature." raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
[ "def", "setFeature", "(", "self", ",", "name", ",", "state", ")", ":", "raise", "SAXNotRecognizedException", "(", "\"Feature '%s' not recognized\"", "%", "name", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/sax/xmlreader.py#L79-L81
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_core/views/__init__.py
python
MyResourcesView.dispatch
(self, *args, **kwargs)
return super(MyResourcesView, self).dispatch(*args, **kwargs)
[]
def dispatch(self, *args, **kwargs): return super(MyResourcesView, self).dispatch(*args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "MyResourcesView", ",", "self", ")", ".", "dispatch", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/views/__init__.py#L1948-L1949
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/celery/celery/task/base.py
python
PeriodicTask.remaining_estimate
(self, last_run_at)
return self.run_every.remaining_estimate(last_run_at)
Returns when the periodic task should run next as a timedelta.
Returns when the periodic task should run next as a timedelta.
[ "Returns", "when", "the", "periodic", "task", "should", "run", "next", "as", "a", "timedelta", "." ]
def remaining_estimate(self, last_run_at): """Returns when the periodic task should run next as a timedelta.""" return self.run_every.remaining_estimate(last_run_at)
[ "def", "remaining_estimate", "(", "self", ",", "last_run_at", ")", ":", "return", "self", ".", "run_every", ".", "remaining_estimate", "(", "last_run_at", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/celery/celery/task/base.py#L138-L140
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/api/state.py
python
watch_finished_history
(zkclient, cell_state)
Watch finished historical snapshots.
Watch finished historical snapshots.
[ "Watch", "finished", "historical", "snapshots", "." ]
def watch_finished_history(zkclient, cell_state): """Watch finished historical snapshots.""" loaded_snapshots = {} @zkclient.ChildrenWatch(z.FINISHED_HISTORY) @utils.exit_on_unhandled def _watch_finished_snapshots(snapshots): """Watch /finished.history nodes.""" start_time = time.time() updated_finished_history = cell_state.finished_history.copy() for db_node in sorted(set(loaded_snapshots) - set(snapshots)): _LOGGER.info('Unloading snapshot: %s', db_node) for instance in loaded_snapshots.pop(db_node): updated_finished_history.pop(instance, None) for db_node in sorted(set(snapshots) - set(loaded_snapshots)): _LOGGER.info('Loading snapshot: %s', db_node) loading_start_time = time.time() loaded_snapshots[db_node] = [] data, _stat = zkclient.get(z.path.finished_history(db_node)) with tempfile.NamedTemporaryFile(delete=False, mode='wb') as f: f.write(zlib.decompress(data)) try: conn = sqlite3.connect(f.name) cur = conn.cursor() sql = 'SELECT name, data FROM finished ORDER BY timestamp' for row in cur.execute(sql): instance, data = row if data: data = yaml.load(data) updated_finished_history[instance] = data loaded_snapshots[db_node].append(instance) conn.close() finally: os.unlink(f.name) _LOGGER.debug('Loading time: %s', time.time() - loading_start_time) cell_state.finished_history = updated_finished_history _LOGGER.debug( 'Loaded snapshots: %d, finished: %d, finished history: %d, ' 'time: %s', len(loaded_snapshots), len(cell_state.finished), len(cell_state.finished_history), time.time() - start_time ) return True _LOGGER.info('Loaded finished snapshots.')
[ "def", "watch_finished_history", "(", "zkclient", ",", "cell_state", ")", ":", "loaded_snapshots", "=", "{", "}", "@", "zkclient", ".", "ChildrenWatch", "(", "z", ".", "FINISHED_HISTORY", ")", "@", "utils", ".", "exit_on_unhandled", "def", "_watch_finished_snapshots", "(", "snapshots", ")", ":", "\"\"\"Watch /finished.history nodes.\"\"\"", "start_time", "=", "time", ".", "time", "(", ")", "updated_finished_history", "=", "cell_state", ".", "finished_history", ".", "copy", "(", ")", "for", "db_node", "in", "sorted", "(", "set", "(", "loaded_snapshots", ")", "-", "set", "(", "snapshots", ")", ")", ":", "_LOGGER", ".", "info", "(", "'Unloading snapshot: %s'", ",", "db_node", ")", "for", "instance", "in", "loaded_snapshots", ".", "pop", "(", "db_node", ")", ":", "updated_finished_history", ".", "pop", "(", "instance", ",", "None", ")", "for", "db_node", "in", "sorted", "(", "set", "(", "snapshots", ")", "-", "set", "(", "loaded_snapshots", ")", ")", ":", "_LOGGER", ".", "info", "(", "'Loading snapshot: %s'", ",", "db_node", ")", "loading_start_time", "=", "time", ".", "time", "(", ")", "loaded_snapshots", "[", "db_node", "]", "=", "[", "]", "data", ",", "_stat", "=", "zkclient", ".", "get", "(", "z", ".", "path", ".", "finished_history", "(", "db_node", ")", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ",", "mode", "=", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "zlib", ".", "decompress", "(", "data", ")", ")", "try", ":", "conn", "=", "sqlite3", ".", "connect", "(", "f", ".", "name", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'SELECT name, data FROM finished ORDER BY timestamp'", "for", "row", "in", "cur", ".", "execute", "(", "sql", ")", ":", "instance", ",", "data", "=", "row", "if", "data", ":", "data", "=", "yaml", ".", "load", "(", "data", ")", "updated_finished_history", "[", "instance", "]", "=", "data", "loaded_snapshots", "[", "db_node", "]", ".", "append", "(", "instance", ")", "conn", ".", "close", "(", ")", "finally", ":", "os", ".", "unlink", "(", "f", ".", "name", ")", "_LOGGER", ".", "debug", "(", "'Loading time: %s'", ",", "time", ".", "time", "(", ")", "-", "loading_start_time", ")", "cell_state", ".", "finished_history", "=", "updated_finished_history", "_LOGGER", ".", "debug", "(", "'Loaded snapshots: %d, finished: %d, finished history: %d, '", "'time: %s'", ",", "len", "(", "loaded_snapshots", ")", ",", "len", "(", "cell_state", ".", "finished", ")", ",", "len", "(", "cell_state", ".", "finished_history", ")", ",", "time", ".", "time", "(", ")", "-", "start_time", ")", "return", "True", "_LOGGER", ".", "info", "(", "'Loaded finished snapshots.'", ")" ]
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/api/state.py#L109-L160
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/physics/secondquant.py
python
simplify_index_permutations
(expr, permutation_operators)
return expr
Performs simplification by introducing PermutationOperators where appropriate. Explanation =========== Schematically: [abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij] permutation_operators is a list of PermutationOperators to consider. If permutation_operators=[P(ab),P(ij)] we will try to introduce the permutation operators P(ij) and P(ab) in the expression. If there are other possible simplifications, we ignore them. >>> from sympy import symbols, Function >>> from sympy.physics.secondquant import simplify_index_permutations >>> from sympy.physics.secondquant import PermutationOperator >>> p,q,r,s = symbols('p,q,r,s') >>> f = Function('f') >>> g = Function('g') >>> expr = f(p)*g(q) - f(q)*g(p); expr f(p)*g(q) - f(q)*g(p) >>> simplify_index_permutations(expr,[PermutationOperator(p,q)]) f(p)*g(q)*PermutationOperator(p, q) >>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)] >>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r) >>> simplify_index_permutations(expr,PermutList) f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s)
Performs simplification by introducing PermutationOperators where appropriate.
[ "Performs", "simplification", "by", "introducing", "PermutationOperators", "where", "appropriate", "." ]
def simplify_index_permutations(expr, permutation_operators): """ Performs simplification by introducing PermutationOperators where appropriate. Explanation =========== Schematically: [abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij] permutation_operators is a list of PermutationOperators to consider. If permutation_operators=[P(ab),P(ij)] we will try to introduce the permutation operators P(ij) and P(ab) in the expression. If there are other possible simplifications, we ignore them. >>> from sympy import symbols, Function >>> from sympy.physics.secondquant import simplify_index_permutations >>> from sympy.physics.secondquant import PermutationOperator >>> p,q,r,s = symbols('p,q,r,s') >>> f = Function('f') >>> g = Function('g') >>> expr = f(p)*g(q) - f(q)*g(p); expr f(p)*g(q) - f(q)*g(p) >>> simplify_index_permutations(expr,[PermutationOperator(p,q)]) f(p)*g(q)*PermutationOperator(p, q) >>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)] >>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r) >>> simplify_index_permutations(expr,PermutList) f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s) """ def _get_indices(expr, ind): """ Collects indices recursively in predictable order. """ result = [] for arg in expr.args: if arg in ind: result.append(arg) else: if arg.args: result.extend(_get_indices(arg, ind)) return result def _choose_one_to_keep(a, b, ind): # we keep the one where indices in ind are in order ind[0] < ind[1] return min(a, b, key=lambda x: default_sort_key(_get_indices(x, ind))) expr = expr.expand() if isinstance(expr, Add): terms = set(expr.args) for P in permutation_operators: new_terms = set() on_hold = set() while terms: term = terms.pop() permuted = P.get_permuted(term) if permuted in terms | on_hold: try: terms.remove(permuted) except KeyError: on_hold.remove(permuted) keep = _choose_one_to_keep(term, permuted, P.args) new_terms.add(P*keep) else: # Some terms must get a second chance because the permuted # term may already have canonical dummy ordering. Then # substitute_dummies() does nothing. However, the other # term, if it exists, will be able to match with us. permuted1 = permuted permuted = substitute_dummies(permuted) if permuted1 == permuted: on_hold.add(term) elif permuted in terms | on_hold: try: terms.remove(permuted) except KeyError: on_hold.remove(permuted) keep = _choose_one_to_keep(term, permuted, P.args) new_terms.add(P*keep) else: new_terms.add(term) terms = new_terms | on_hold return Add(*terms) return expr
[ "def", "simplify_index_permutations", "(", "expr", ",", "permutation_operators", ")", ":", "def", "_get_indices", "(", "expr", ",", "ind", ")", ":", "\"\"\"\n Collects indices recursively in predictable order.\n \"\"\"", "result", "=", "[", "]", "for", "arg", "in", "expr", ".", "args", ":", "if", "arg", "in", "ind", ":", "result", ".", "append", "(", "arg", ")", "else", ":", "if", "arg", ".", "args", ":", "result", ".", "extend", "(", "_get_indices", "(", "arg", ",", "ind", ")", ")", "return", "result", "def", "_choose_one_to_keep", "(", "a", ",", "b", ",", "ind", ")", ":", "# we keep the one where indices in ind are in order ind[0] < ind[1]", "return", "min", "(", "a", ",", "b", ",", "key", "=", "lambda", "x", ":", "default_sort_key", "(", "_get_indices", "(", "x", ",", "ind", ")", ")", ")", "expr", "=", "expr", ".", "expand", "(", ")", "if", "isinstance", "(", "expr", ",", "Add", ")", ":", "terms", "=", "set", "(", "expr", ".", "args", ")", "for", "P", "in", "permutation_operators", ":", "new_terms", "=", "set", "(", ")", "on_hold", "=", "set", "(", ")", "while", "terms", ":", "term", "=", "terms", ".", "pop", "(", ")", "permuted", "=", "P", ".", "get_permuted", "(", "term", ")", "if", "permuted", "in", "terms", "|", "on_hold", ":", "try", ":", "terms", ".", "remove", "(", "permuted", ")", "except", "KeyError", ":", "on_hold", ".", "remove", "(", "permuted", ")", "keep", "=", "_choose_one_to_keep", "(", "term", ",", "permuted", ",", "P", ".", "args", ")", "new_terms", ".", "add", "(", "P", "*", "keep", ")", "else", ":", "# Some terms must get a second chance because the permuted", "# term may already have canonical dummy ordering. Then", "# substitute_dummies() does nothing. However, the other", "# term, if it exists, will be able to match with us.", "permuted1", "=", "permuted", "permuted", "=", "substitute_dummies", "(", "permuted", ")", "if", "permuted1", "==", "permuted", ":", "on_hold", ".", "add", "(", "term", ")", "elif", "permuted", "in", "terms", "|", "on_hold", ":", "try", ":", "terms", ".", "remove", "(", "permuted", ")", "except", "KeyError", ":", "on_hold", ".", "remove", "(", "permuted", ")", "keep", "=", "_choose_one_to_keep", "(", "term", ",", "permuted", ",", "P", ".", "args", ")", "new_terms", ".", "add", "(", "P", "*", "keep", ")", "else", ":", "new_terms", ".", "add", "(", "term", ")", "terms", "=", "new_terms", "|", "on_hold", "return", "Add", "(", "*", "terms", ")", "return", "expr" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/physics/secondquant.py#L3046-L3136
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/lzma.py
python
LZMAFile._rewind
(self)
[]
def _rewind(self): self._fp.seek(0, 0) self._mode = _MODE_READ self._pos = 0 self._decompressor = LZMADecompressor(**self._init_args) self._buffer = b"" self._buffer_offset = 0
[ "def", "_rewind", "(", "self", ")", ":", "self", ".", "_fp", ".", "seek", "(", "0", ",", "0", ")", "self", ".", "_mode", "=", "_MODE_READ", "self", ".", "_pos", "=", "0", "self", ".", "_decompressor", "=", "LZMADecompressor", "(", "*", "*", "self", ".", "_init_args", ")", "self", ".", "_buffer", "=", "b\"\"", "self", ".", "_buffer_offset", "=", "0" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/lzma.py#L372-L378
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/intercircle.py
python
getInsetLoopsFromLoop
(inset, loop, thresholdRatio=0.9)
return insetLoops
Get the inset loops, which might overlap.
Get the inset loops, which might overlap.
[ "Get", "the", "inset", "loops", "which", "might", "overlap", "." ]
def getInsetLoopsFromLoop(inset, loop, thresholdRatio=0.9): "Get the inset loops, which might overlap." isInset = inset > 0 insetLoops = [] isLoopWiddershins = euclidean.isWiddershins(loop) arounds = getAroundsFromLoop( loop, inset, thresholdRatio ) for around in arounds: leftPoint = euclidean.getLeftPoint(around) shouldBeWithin = (isInset == isLoopWiddershins) if euclidean.isPointInsideLoop(loop, leftPoint) == shouldBeWithin: if isLoopWiddershins != euclidean.isWiddershins(around): around.reverse() insetLoops.append(around) return insetLoops
[ "def", "getInsetLoopsFromLoop", "(", "inset", ",", "loop", ",", "thresholdRatio", "=", "0.9", ")", ":", "isInset", "=", "inset", ">", "0", "insetLoops", "=", "[", "]", "isLoopWiddershins", "=", "euclidean", ".", "isWiddershins", "(", "loop", ")", "arounds", "=", "getAroundsFromLoop", "(", "loop", ",", "inset", ",", "thresholdRatio", ")", "for", "around", "in", "arounds", ":", "leftPoint", "=", "euclidean", ".", "getLeftPoint", "(", "around", ")", "shouldBeWithin", "=", "(", "isInset", "==", "isLoopWiddershins", ")", "if", "euclidean", ".", "isPointInsideLoop", "(", "loop", ",", "leftPoint", ")", "==", "shouldBeWithin", ":", "if", "isLoopWiddershins", "!=", "euclidean", ".", "isWiddershins", "(", "around", ")", ":", "around", ".", "reverse", "(", ")", "insetLoops", ".", "append", "(", "around", ")", "return", "insetLoops" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/intercircle.py#L273-L286
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/bdf_interface/write_mesh.py
python
WriteMesh._write_constraints
(self, bdf_file: Any, size: int=8, is_double: bool=False, is_long_ids: Optional[bool]=None)
Writes the constraint cards sorted by ID
Writes the constraint cards sorted by ID
[ "Writes", "the", "constraint", "cards", "sorted", "by", "ID" ]
def _write_constraints(self, bdf_file: Any, size: int=8, is_double: bool=False, is_long_ids: Optional[bool]=None) -> None: """Writes the constraint cards sorted by ID""" size, is_long_ids = self._write_mesh_long_ids_size(size, is_long_ids) if self.suport or self.suport1: bdf_file.write('$CONSTRAINTS\n') for suport in self.suport: bdf_file.write(suport.write_card(size, is_double)) for unused_suport_id, suport in sorted(self.suport1.items()): bdf_file.write(suport.write_card(size, is_double)) if self.spcs or self.spcadds or self.spcoffs: #bdf_file.write('$SPCs\n') #str_spc = str(self.spcObject) # old #if str_spc: #bdf_file.write(str_spc) #else: bdf_file.write('$SPCs\n') for (unused_id, spcadds) in sorted(self.spcadds.items()): for spcadd in spcadds: bdf_file.write(str(spcadd)) for (unused_id, spcs) in sorted(self.spcs.items()): for spc in spcs: bdf_file.write(str(spc)) for (unused_id, spcoffs) in sorted(self.spcoffs.items()): for spc in spcoffs: bdf_file.write(str(spc)) if self.mpcs or self.mpcadds: bdf_file.write('$MPCs\n') for (unused_id, mpcadds) in sorted(self.mpcadds.items()): for mpcadd in mpcadds: bdf_file.write(str(mpcadd)) for (unused_id, mpcs) in sorted(self.mpcs.items()): for mpc in mpcs: bdf_file.write(mpc.write_card(size, is_double))
[ "def", "_write_constraints", "(", "self", ",", "bdf_file", ":", "Any", ",", "size", ":", "int", "=", "8", ",", "is_double", ":", "bool", "=", "False", ",", "is_long_ids", ":", "Optional", "[", "bool", "]", "=", "None", ")", "->", "None", ":", "size", ",", "is_long_ids", "=", "self", ".", "_write_mesh_long_ids_size", "(", "size", ",", "is_long_ids", ")", "if", "self", ".", "suport", "or", "self", ".", "suport1", ":", "bdf_file", ".", "write", "(", "'$CONSTRAINTS\\n'", ")", "for", "suport", "in", "self", ".", "suport", ":", "bdf_file", ".", "write", "(", "suport", ".", "write_card", "(", "size", ",", "is_double", ")", ")", "for", "unused_suport_id", ",", "suport", "in", "sorted", "(", "self", ".", "suport1", ".", "items", "(", ")", ")", ":", "bdf_file", ".", "write", "(", "suport", ".", "write_card", "(", "size", ",", "is_double", ")", ")", "if", "self", ".", "spcs", "or", "self", ".", "spcadds", "or", "self", ".", "spcoffs", ":", "#bdf_file.write('$SPCs\\n')", "#str_spc = str(self.spcObject) # old", "#if str_spc:", "#bdf_file.write(str_spc)", "#else:", "bdf_file", ".", "write", "(", "'$SPCs\\n'", ")", "for", "(", "unused_id", ",", "spcadds", ")", "in", "sorted", "(", "self", ".", "spcadds", ".", "items", "(", ")", ")", ":", "for", "spcadd", "in", "spcadds", ":", "bdf_file", ".", "write", "(", "str", "(", "spcadd", ")", ")", "for", "(", "unused_id", ",", "spcs", ")", "in", "sorted", "(", "self", ".", "spcs", ".", "items", "(", ")", ")", ":", "for", "spc", "in", "spcs", ":", "bdf_file", ".", "write", "(", "str", "(", "spc", ")", ")", "for", "(", "unused_id", ",", "spcoffs", ")", "in", "sorted", "(", "self", ".", "spcoffs", ".", "items", "(", ")", ")", ":", "for", "spc", "in", "spcoffs", ":", "bdf_file", ".", "write", "(", "str", "(", "spc", ")", ")", "if", "self", ".", "mpcs", "or", "self", ".", "mpcadds", ":", "bdf_file", ".", "write", "(", "'$MPCs\\n'", ")", "for", "(", "unused_id", ",", "mpcadds", ")", "in", "sorted", "(", "self", ".", "mpcadds", ".", "items", "(", ")", ")", ":", "for", "mpcadd", "in", "mpcadds", ":", "bdf_file", ".", "write", "(", "str", "(", "mpcadd", ")", ")", "for", "(", "unused_id", ",", "mpcs", ")", "in", "sorted", "(", "self", ".", "mpcs", ".", "items", "(", ")", ")", ":", "for", "mpc", "in", "mpcs", ":", "bdf_file", ".", "write", "(", "mpc", ".", "write_card", "(", "size", ",", "is_double", ")", ")" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/bdf_interface/write_mesh.py#L493-L528
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/cards/optimization.py
python
DVMREL1.uncross_reference
(self)
Removes cross-reference links
Removes cross-reference links
[ "Removes", "cross", "-", "reference", "links" ]
def uncross_reference(self) -> None: """Removes cross-reference links""" self.mid = self.Mid() self.dvids = self.desvar_ids self.mid_ref = None self.dvids_ref = None
[ "def", "uncross_reference", "(", "self", ")", "->", "None", ":", "self", ".", "mid", "=", "self", ".", "Mid", "(", ")", "self", ".", "dvids", "=", "self", ".", "desvar_ids", "self", ".", "mid_ref", "=", "None", "self", ".", "dvids_ref", "=", "None" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/optimization.py#L4168-L4173
Parsely/pykafka
e7665bf36bfe521050fdcb017c68e92365bd89ed
pykafka/utils/__init__.py
python
deserialize_utf8
(value, partition_key)
return value, partition_key
A deserializer accepting bytes arguments and returning utf-8 strings Can be used as `pykafka.simpleconsumer.SimpleConsumer(deserializer=deserialize_utf8)`, or similarly in other consumer classes
A deserializer accepting bytes arguments and returning utf-8 strings
[ "A", "deserializer", "accepting", "bytes", "arguments", "and", "returning", "utf", "-", "8", "strings" ]
def deserialize_utf8(value, partition_key): """A deserializer accepting bytes arguments and returning utf-8 strings Can be used as `pykafka.simpleconsumer.SimpleConsumer(deserializer=deserialize_utf8)`, or similarly in other consumer classes """ # allow UnicodeError to be raised here if the decoding fails if value is not None: value = value.decode('utf-8') if partition_key is not None: partition_key = partition_key.decode('utf-8') return value, partition_key
[ "def", "deserialize_utf8", "(", "value", ",", "partition_key", ")", ":", "# allow UnicodeError to be raised here if the decoding fails", "if", "value", "is", "not", "None", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "if", "partition_key", "is", "not", "None", ":", "partition_key", "=", "partition_key", ".", "decode", "(", "'utf-8'", ")", "return", "value", ",", "partition_key" ]
https://github.com/Parsely/pykafka/blob/e7665bf36bfe521050fdcb017c68e92365bd89ed/pykafka/utils/__init__.py#L44-L55
IntelAI/models
1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c
models/language_translation/tensorflow/transformer_mlperf/training/bfloat16/transformer/utils/tokenizer.py
python
_save_vocab_file
(vocab_file, subtoken_list)
Save subtokens to file.
Save subtokens to file.
[ "Save", "subtokens", "to", "file", "." ]
def _save_vocab_file(vocab_file, subtoken_list): """Save subtokens to file.""" with tf.io.gfile.GFile(vocab_file, mode="w") as f: for subtoken in subtoken_list: f.write("'%s'\n" % _unicode_to_native(subtoken))
[ "def", "_save_vocab_file", "(", "vocab_file", ",", "subtoken_list", ")", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "vocab_file", ",", "mode", "=", "\"w\"", ")", "as", "f", ":", "for", "subtoken", "in", "subtoken_list", ":", "f", ".", "write", "(", "\"'%s'\\n\"", "%", "_unicode_to_native", "(", "subtoken", ")", ")" ]
https://github.com/IntelAI/models/blob/1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c/models/language_translation/tensorflow/transformer_mlperf/training/bfloat16/transformer/utils/tokenizer.py#L185-L189
apple/coremltools
141a83af482fcbdd5179807c9eaff9a7999c2c49
deps/protobuf/python/google/protobuf/internal/encoder.py
python
MapEncoder
(field_descriptor)
return EncodeField
Encoder for extensions of MessageSet. Maps always have a wire format like this: message MapEntry { key_type key = 1; value_type value = 2; } repeated MapEntry map = N;
Encoder for extensions of MessageSet.
[ "Encoder", "for", "extensions", "of", "MessageSet", "." ]
def MapEncoder(field_descriptor): """Encoder for extensions of MessageSet. Maps always have a wire format like this: message MapEntry { key_type key = 1; value_type value = 2; } repeated MapEntry map = N; """ # Can't look at field_descriptor.message_type._concrete_class because it may # not have been initialized yet. message_type = field_descriptor.message_type encode_message = MessageEncoder(field_descriptor.number, False, False) def EncodeField(write, value): for key in value: entry_msg = message_type._concrete_class(key=key, value=value[key]) encode_message(write, entry_msg) return EncodeField
[ "def", "MapEncoder", "(", "field_descriptor", ")", ":", "# Can't look at field_descriptor.message_type._concrete_class because it may", "# not have been initialized yet.", "message_type", "=", "field_descriptor", ".", "message_type", "encode_message", "=", "MessageEncoder", "(", "field_descriptor", ".", "number", ",", "False", ",", "False", ")", "def", "EncodeField", "(", "write", ",", "value", ")", ":", "for", "key", "in", "value", ":", "entry_msg", "=", "message_type", ".", "_concrete_class", "(", "key", "=", "key", ",", "value", "=", "value", "[", "key", "]", ")", "encode_message", "(", "write", ",", "entry_msg", ")", "return", "EncodeField" ]
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/deps/protobuf/python/google/protobuf/internal/encoder.py#L806-L826
nathanlopez/Stitch
8e22e91c94237959c02d521aab58dc7e3d994cea
Application/stitch_winshell.py
python
st_winshell.help_keylogger
(self)
[]
def help_keylogger(self): st_help_keylogger()
[ "def", "help_keylogger", "(", "self", ")", ":", "st_help_keylogger", "(", ")" ]
https://github.com/nathanlopez/Stitch/blob/8e22e91c94237959c02d521aab58dc7e3d994cea/Application/stitch_winshell.py#L292-L292
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/nexml/_nexml.py
python
RestrictionMatrixObsRow.get_cell
(self)
return self.cell
[]
def get_cell(self): return self.cell
[ "def", "get_cell", "(", "self", ")", ":", "return", "self", ".", "cell" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L12694-L12694
pyserial/pyserial
31fa4807d73ed4eb9891a88a15817b439c4eea2d
serial/rfc2217.py
python
PortManager.check_modem_lines
(self, force_notification=False)
\ read control lines from serial port and compare the last value sent to remote. send updates on changes.
\ read control lines from serial port and compare the last value sent to remote. send updates on changes.
[ "\\", "read", "control", "lines", "from", "serial", "port", "and", "compare", "the", "last", "value", "sent", "to", "remote", ".", "send", "updates", "on", "changes", "." ]
def check_modem_lines(self, force_notification=False): """\ read control lines from serial port and compare the last value sent to remote. send updates on changes. """ modemstate = ( (self.serial.cts and MODEMSTATE_MASK_CTS) | (self.serial.dsr and MODEMSTATE_MASK_DSR) | (self.serial.ri and MODEMSTATE_MASK_RI) | (self.serial.cd and MODEMSTATE_MASK_CD)) # check what has changed deltas = modemstate ^ (self.last_modemstate or 0) # when last is None -> 0 if deltas & MODEMSTATE_MASK_CTS: modemstate |= MODEMSTATE_MASK_CTS_CHANGE if deltas & MODEMSTATE_MASK_DSR: modemstate |= MODEMSTATE_MASK_DSR_CHANGE if deltas & MODEMSTATE_MASK_RI: modemstate |= MODEMSTATE_MASK_RI_CHANGE if deltas & MODEMSTATE_MASK_CD: modemstate |= MODEMSTATE_MASK_CD_CHANGE # if new state is different and the mask allows this change, send # notification. suppress notifications when client is not rfc2217 if modemstate != self.last_modemstate or force_notification: if (self._client_is_rfc2217 and (modemstate & self.modemstate_mask)) or force_notification: self.rfc2217_send_subnegotiation( SERVER_NOTIFY_MODEMSTATE, to_bytes([modemstate & self.modemstate_mask])) if self.logger: self.logger.info("NOTIFY_MODEMSTATE: {}".format(modemstate)) # save last state, but forget about deltas. # otherwise it would also notify about changing deltas which is # probably not very useful self.last_modemstate = modemstate & 0xf0
[ "def", "check_modem_lines", "(", "self", ",", "force_notification", "=", "False", ")", ":", "modemstate", "=", "(", "(", "self", ".", "serial", ".", "cts", "and", "MODEMSTATE_MASK_CTS", ")", "|", "(", "self", ".", "serial", ".", "dsr", "and", "MODEMSTATE_MASK_DSR", ")", "|", "(", "self", ".", "serial", ".", "ri", "and", "MODEMSTATE_MASK_RI", ")", "|", "(", "self", ".", "serial", ".", "cd", "and", "MODEMSTATE_MASK_CD", ")", ")", "# check what has changed", "deltas", "=", "modemstate", "^", "(", "self", ".", "last_modemstate", "or", "0", ")", "# when last is None -> 0", "if", "deltas", "&", "MODEMSTATE_MASK_CTS", ":", "modemstate", "|=", "MODEMSTATE_MASK_CTS_CHANGE", "if", "deltas", "&", "MODEMSTATE_MASK_DSR", ":", "modemstate", "|=", "MODEMSTATE_MASK_DSR_CHANGE", "if", "deltas", "&", "MODEMSTATE_MASK_RI", ":", "modemstate", "|=", "MODEMSTATE_MASK_RI_CHANGE", "if", "deltas", "&", "MODEMSTATE_MASK_CD", ":", "modemstate", "|=", "MODEMSTATE_MASK_CD_CHANGE", "# if new state is different and the mask allows this change, send", "# notification. suppress notifications when client is not rfc2217", "if", "modemstate", "!=", "self", ".", "last_modemstate", "or", "force_notification", ":", "if", "(", "self", ".", "_client_is_rfc2217", "and", "(", "modemstate", "&", "self", ".", "modemstate_mask", ")", ")", "or", "force_notification", ":", "self", ".", "rfc2217_send_subnegotiation", "(", "SERVER_NOTIFY_MODEMSTATE", ",", "to_bytes", "(", "[", "modemstate", "&", "self", ".", "modemstate_mask", "]", ")", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "\"NOTIFY_MODEMSTATE: {}\"", ".", "format", "(", "modemstate", ")", ")", "# save last state, but forget about deltas.", "# otherwise it would also notify about changing deltas which is", "# probably not very useful", "self", ".", "last_modemstate", "=", "modemstate", "&", "0xf0" ]
https://github.com/pyserial/pyserial/blob/31fa4807d73ed4eb9891a88a15817b439c4eea2d/serial/rfc2217.py#L1011-L1043
kubeflow/pipelines
bea751c9259ff0ae85290f873170aae89284ba8e
sdk/python/kfp/components/_component_store.py
python
ComponentStore.load_component_from_file
(self, path)
return comp.load_component_from_file(path)
Loads a component from a path. Args: path: The path of the component specification. Returns: A factory function with a strongly-typed signature.
Loads a component from a path.
[ "Loads", "a", "component", "from", "a", "path", "." ]
def load_component_from_file(self, path): """Loads a component from a path. Args: path: The path of the component specification. Returns: A factory function with a strongly-typed signature. """ return comp.load_component_from_file(path)
[ "def", "load_component_from_file", "(", "self", ",", "path", ")", ":", "return", "comp", ".", "load_component_from_file", "(", "path", ")" ]
https://github.com/kubeflow/pipelines/blob/bea751c9259ff0ae85290f873170aae89284ba8e/sdk/python/kfp/components/_component_store.py#L74-L83
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/warnings.py
python
catch_warnings.__init__
(self, record=False, module=None)
Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. For compatibility with Python 3.0, please consider all arguments to be keyword-only.
Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings'].
[ "Specify", "whether", "to", "record", "warnings", "and", "if", "an", "alternative", "module", "should", "be", "used", "other", "than", "sys", ".", "modules", "[", "warnings", "]", "." ]
def __init__(self, record=False, module=None): """Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. For compatibility with Python 3.0, please consider all arguments to be keyword-only. """ self._record = record self._module = sys.modules['warnings'] if module is None else module self._entered = False
[ "def", "__init__", "(", "self", ",", "record", "=", "False", ",", "module", "=", "None", ")", ":", "self", ".", "_record", "=", "record", "self", ".", "_module", "=", "sys", ".", "modules", "[", "'warnings'", "]", "if", "module", "is", "None", "else", "module", "self", ".", "_entered", "=", "False" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/warnings.py#L318-L328
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/bsddb/dbtables.py
python
Cond.__call__
(self, s)
return 1
[]
def __call__(self, s): return 1
[ "def", "__call__", "(", "self", ",", "s", ")", ":", "return", "1" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/bsddb/dbtables.py#L70-L71
skelsec/msldap
ed3134135ddf9e13c74a4d7208ef3e48ec898192
msldap/client.py
python
MSLDAPClient.get_all_users
(self)
Fetches all user objects available in the LDAP tree and yields them as MSADUser object. :return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error :rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)]
Fetches all user objects available in the LDAP tree and yields them as MSADUser object. :return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error :rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)]
[ "Fetches", "all", "user", "objects", "available", "in", "the", "LDAP", "tree", "and", "yields", "them", "as", "MSADUser", "object", ".", ":", "return", ":", "Async", "generator", "which", "yields", "(", "MSADUser", "None", ")", "tuple", "on", "success", "or", "(", "None", "Exception", ")", "on", "error", ":", "rtype", ":", "Iterator", "[", "(", ":", "class", ":", "MSADUser", ":", "class", ":", "Exception", ")", "]" ]
async def get_all_users(self): """ Fetches all user objects available in the LDAP tree and yields them as MSADUser object. :return: Async generator which yields (`MSADUser`, None) tuple on success or (None, `Exception`) on error :rtype: Iterator[(:class:`MSADUser`, :class:`Exception`)] """ logger.debug('Polling AD for all user objects') ldap_filter = r'(sAMAccountType=805306368)' async for entry, err in self.pagedsearch(ldap_filter, MSADUser_ATTRS): if err is not None: yield None, err return yield MSADUser.from_ldap(entry, self._ldapinfo), None logger.debug('Finished polling for entries!')
[ "async", "def", "get_all_users", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Polling AD for all user objects'", ")", "ldap_filter", "=", "r'(sAMAccountType=805306368)'", "async", "for", "entry", ",", "err", "in", "self", ".", "pagedsearch", "(", "ldap_filter", ",", "MSADUser_ATTRS", ")", ":", "if", "err", "is", "not", "None", ":", "yield", "None", ",", "err", "return", "yield", "MSADUser", ".", "from_ldap", "(", "entry", ",", "self", ".", "_ldapinfo", ")", ",", "None", "logger", ".", "debug", "(", "'Finished polling for entries!'", ")" ]
https://github.com/skelsec/msldap/blob/ed3134135ddf9e13c74a4d7208ef3e48ec898192/msldap/client.py#L188-L203
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/core/oinspect.py
python
Inspector._mime_format
(self, text:str, formatter=None)
Return a mime bundle representation of the input text. - if `formatter` is None, the returned mime bundle has a `text/plain` field, with the input text. a `text/html` field with a `<pre>` tag containing the input text. - if `formatter` is not None, it must be a callable transforming the input text into a mime bundle. Default values for `text/plain` and `text/html` representations are the ones described above. Note: Formatters returning strings are supported but this behavior is deprecated.
Return a mime bundle representation of the input text.
[ "Return", "a", "mime", "bundle", "representation", "of", "the", "input", "text", "." ]
def _mime_format(self, text:str, formatter=None) -> dict: """Return a mime bundle representation of the input text. - if `formatter` is None, the returned mime bundle has a `text/plain` field, with the input text. a `text/html` field with a `<pre>` tag containing the input text. - if `formatter` is not None, it must be a callable transforming the input text into a mime bundle. Default values for `text/plain` and `text/html` representations are the ones described above. Note: Formatters returning strings are supported but this behavior is deprecated. """ defaults = { 'text/plain': text, 'text/html': '<pre>' + text + '</pre>' } if formatter is None: return defaults else: formatted = formatter(text) if not isinstance(formatted, dict): # Handle the deprecated behavior of a formatter returning # a string instead of a mime bundle. return { 'text/plain': formatted, 'text/html': '<pre>' + formatted + '</pre>' } else: return dict(defaults, **formatted)
[ "def", "_mime_format", "(", "self", ",", "text", ":", "str", ",", "formatter", "=", "None", ")", "->", "dict", ":", "defaults", "=", "{", "'text/plain'", ":", "text", ",", "'text/html'", ":", "'<pre>'", "+", "text", "+", "'</pre>'", "}", "if", "formatter", "is", "None", ":", "return", "defaults", "else", ":", "formatted", "=", "formatter", "(", "text", ")", "if", "not", "isinstance", "(", "formatted", ",", "dict", ")", ":", "# Handle the deprecated behavior of a formatter returning", "# a string instead of a mime bundle.", "return", "{", "'text/plain'", ":", "formatted", ",", "'text/html'", ":", "'<pre>'", "+", "formatted", "+", "'</pre>'", "}", "else", ":", "return", "dict", "(", "defaults", ",", "*", "*", "formatted", ")" ]
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/core/oinspect.py#L517-L552
jet-admin/jet-django
9bd4536e02d581d39890d56190e8cc966e2714a4
jet_django/deps/rest_framework/serializers.py
python
ModelSerializer.build_standard_field
(self, field_name, model_field)
return field_class, field_kwargs
Create regular model fields.
Create regular model fields.
[ "Create", "regular", "model", "fields", "." ]
def build_standard_field(self, field_name, model_field): """ Create regular model fields. """ field_mapping = ClassLookupDict(self.serializer_field_mapping) field_class = field_mapping[model_field] field_kwargs = get_field_kwargs(field_name, model_field) # Special case to handle when a OneToOneField is also the primary key if model_field.one_to_one and model_field.primary_key: field_class = self.serializer_related_field field_kwargs['queryset'] = model_field.related_model.objects if 'choices' in field_kwargs: # Fields with choices get coerced into `ChoiceField` # instead of using their regular typed field. field_class = self.serializer_choice_field # Some model fields may introduce kwargs that would not be valid # for the choice field. We need to strip these out. # Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES) valid_kwargs = { 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'validators', 'allow_null', 'allow_blank', 'choices' } for key in list(field_kwargs): if key not in valid_kwargs: field_kwargs.pop(key) if not issubclass(field_class, ModelField): # `model_field` is only valid for the fallback case of # `ModelField`, which is used when no other typed field # matched to the model field. field_kwargs.pop('model_field', None) if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField): # `allow_blank` is only valid for textual fields. field_kwargs.pop('allow_blank', None) if postgres_fields and isinstance(model_field, postgres_fields.ArrayField): # Populate the `child` argument on `ListField` instances generated # for the PostgreSQL specific `ArrayField`. child_model_field = model_field.base_field child_field_class, child_field_kwargs = self.build_standard_field( 'child', child_model_field ) field_kwargs['child'] = child_field_class(**child_field_kwargs) return field_class, field_kwargs
[ "def", "build_standard_field", "(", "self", ",", "field_name", ",", "model_field", ")", ":", "field_mapping", "=", "ClassLookupDict", "(", "self", ".", "serializer_field_mapping", ")", "field_class", "=", "field_mapping", "[", "model_field", "]", "field_kwargs", "=", "get_field_kwargs", "(", "field_name", ",", "model_field", ")", "# Special case to handle when a OneToOneField is also the primary key", "if", "model_field", ".", "one_to_one", "and", "model_field", ".", "primary_key", ":", "field_class", "=", "self", ".", "serializer_related_field", "field_kwargs", "[", "'queryset'", "]", "=", "model_field", ".", "related_model", ".", "objects", "if", "'choices'", "in", "field_kwargs", ":", "# Fields with choices get coerced into `ChoiceField`", "# instead of using their regular typed field.", "field_class", "=", "self", ".", "serializer_choice_field", "# Some model fields may introduce kwargs that would not be valid", "# for the choice field. We need to strip these out.", "# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)", "valid_kwargs", "=", "{", "'read_only'", ",", "'write_only'", ",", "'required'", ",", "'default'", ",", "'initial'", ",", "'source'", ",", "'label'", ",", "'help_text'", ",", "'style'", ",", "'error_messages'", ",", "'validators'", ",", "'allow_null'", ",", "'allow_blank'", ",", "'choices'", "}", "for", "key", "in", "list", "(", "field_kwargs", ")", ":", "if", "key", "not", "in", "valid_kwargs", ":", "field_kwargs", ".", "pop", "(", "key", ")", "if", "not", "issubclass", "(", "field_class", ",", "ModelField", ")", ":", "# `model_field` is only valid for the fallback case of", "# `ModelField`, which is used when no other typed field", "# matched to the model field.", "field_kwargs", ".", "pop", "(", "'model_field'", ",", "None", ")", "if", "not", "issubclass", "(", "field_class", ",", "CharField", ")", "and", "not", "issubclass", "(", "field_class", ",", "ChoiceField", ")", ":", "# `allow_blank` is only valid for textual fields.", "field_kwargs", ".", "pop", "(", "'allow_blank'", ",", "None", ")", "if", "postgres_fields", "and", "isinstance", "(", "model_field", ",", "postgres_fields", ".", "ArrayField", ")", ":", "# Populate the `child` argument on `ListField` instances generated", "# for the PostgreSQL specific `ArrayField`.", "child_model_field", "=", "model_field", ".", "base_field", "child_field_class", ",", "child_field_kwargs", "=", "self", ".", "build_standard_field", "(", "'child'", ",", "child_model_field", ")", "field_kwargs", "[", "'child'", "]", "=", "child_field_class", "(", "*", "*", "child_field_kwargs", ")", "return", "field_class", ",", "field_kwargs" ]
https://github.com/jet-admin/jet-django/blob/9bd4536e02d581d39890d56190e8cc966e2714a4/jet_django/deps/rest_framework/serializers.py#L1192-L1243
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
seahub/api2/permissions.py
python
IsRepoAccessible.has_permission
(self, request, view, obj=None)
return True if check_permission(repo_id, user) else False
[]
def has_permission(self, request, view, obj=None): repo_id = view.kwargs.get('repo_id', '') user = request.user.username if request.user else '' return True if check_permission(repo_id, user) else False
[ "def", "has_permission", "(", "self", ",", "request", ",", "view", ",", "obj", "=", "None", ")", ":", "repo_id", "=", "view", ".", "kwargs", ".", "get", "(", "'repo_id'", ",", "''", ")", "user", "=", "request", ".", "user", ".", "username", "if", "request", ".", "user", "else", "''", "return", "True", "if", "check_permission", "(", "repo_id", ",", "user", ")", "else", "False" ]
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/api2/permissions.py#L36-L40
coinbase/coinbase-python
497c28158f529e8c7d0228521b4386a890baf088
coinbase/wallet/client.py
python
Client.get_buy_price
(self, **params)
return self._make_api_object(response, APIObject)
https://developers.coinbase.com/api/v2#get-buy-price
https://developers.coinbase.com/api/v2#get-buy-price
[ "https", ":", "//", "developers", ".", "coinbase", ".", "com", "/", "api", "/", "v2#get", "-", "buy", "-", "price" ]
def get_buy_price(self, **params): """https://developers.coinbase.com/api/v2#get-buy-price""" currency_pair = params.get('currency_pair', 'BTC-USD') response = self._get('v2', 'prices', currency_pair, 'buy', params=params) return self._make_api_object(response, APIObject)
[ "def", "get_buy_price", "(", "self", ",", "*", "*", "params", ")", ":", "currency_pair", "=", "params", ".", "get", "(", "'currency_pair'", ",", "'BTC-USD'", ")", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'prices'", ",", "currency_pair", ",", "'buy'", ",", "params", "=", "params", ")", "return", "self", ".", "_make_api_object", "(", "response", ",", "APIObject", ")" ]
https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/client.py#L217-L221
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/suds/xsd/schema.py
python
Schema.custom
(self, ref, context=None)
Get whether the specified reference is B{not} an (xs) builtin. @param ref: A str or qref. @type ref: (str|qref) @return: True if B{not} a builtin, else False. @rtype: bool
Get whether the specified reference is B{not} an (xs) builtin.
[ "Get", "whether", "the", "specified", "reference", "is", "B", "{", "not", "}", "an", "(", "xs", ")", "builtin", "." ]
def custom(self, ref, context=None): """ Get whether the specified reference is B{not} an (xs) builtin. @param ref: A str or qref. @type ref: (str|qref) @return: True if B{not} a builtin, else False. @rtype: bool """ if ref is None: return True else: return ( not self.builtin(ref, context) )
[ "def", "custom", "(", "self", ",", "ref", ",", "context", "=", "None", ")", ":", "if", "ref", "is", "None", ":", "return", "True", "else", ":", "return", "(", "not", "self", ".", "builtin", "(", "ref", ",", "context", ")", ")" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/suds/xsd/schema.py#L349-L360
sibblegp/b2blaze
5976bdefa4816f8d7586df0c5612bb6ce8d286b6
b2blaze/models/b2_file.py
python
B2File.__init__
(self, connector, parent_list, fileId, fileName, contentSha1, contentLength, contentType, fileInfo, action, uploadTimestamp, *args, **kwargs)
:param connector: :param parent_list: :param fileId: :param fileName: :param contentSha1: :param contentLength: :param contentType: :param fileInfo: :param action: :param uploadTimestamp: :param args: :param kwargs:
[]
def __init__(self, connector, parent_list, fileId, fileName, contentSha1, contentLength, contentType, fileInfo, action, uploadTimestamp, *args, **kwargs): """ :param connector: :param parent_list: :param fileId: :param fileName: :param contentSha1: :param contentLength: :param contentType: :param fileInfo: :param action: :param uploadTimestamp: :param args: :param kwargs: """ self.file_id = fileId # self.file_name_decoded = b2_url_decode(fileName) #TODO: Find out if this is necessary self.file_name = fileName self.content_sha1 = contentSha1 self.content_length = contentLength self.content_type = contentType self.file_info = fileInfo self.action = action self.uploadTimestamp = uploadTimestamp self.connector = connector self.parent_list = parent_list self.deleted = False
[ "def", "__init__", "(", "self", ",", "connector", ",", "parent_list", ",", "fileId", ",", "fileName", ",", "contentSha1", ",", "contentLength", ",", "contentType", ",", "fileInfo", ",", "action", ",", "uploadTimestamp", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "file_id", "=", "fileId", "# self.file_name_decoded = b2_url_decode(fileName)", "#TODO: Find out if this is necessary", "self", ".", "file_name", "=", "fileName", "self", ".", "content_sha1", "=", "contentSha1", "self", ".", "content_length", "=", "contentLength", "self", ".", "content_type", "=", "contentType", "self", ".", "file_info", "=", "fileInfo", "self", ".", "action", "=", "action", "self", ".", "uploadTimestamp", "=", "uploadTimestamp", "self", ".", "connector", "=", "connector", "self", ".", "parent_list", "=", "parent_list", "self", ".", "deleted", "=", "False" ]
https://github.com/sibblegp/b2blaze/blob/5976bdefa4816f8d7586df0c5612bb6ce8d286b6/b2blaze/models/b2_file.py#L13-L42
wnma3mz/wechat_articles_spider
77704ffe454a5f7cf287f7ccd07a005ea85ee066
wechatarticles/ArticlesInfo.py
python
ArticlesInfo.comments
(self, article_url)
获取文章评论 Parameters ---------- article_url: str 文章链接 Returns ------- json:: { "base_resp": { "errmsg": "ok", "ret": 0 }, "elected_comment": [ { "content": 用户评论文字, "content_id": "6846263421277569047", "create_time": 1520098511, "id": 3, "is_from_friend": 0, "is_from_me": 0, "is_top": 0, 是否被置顶 "like_id": 10001, "like_num": 3, "like_status": 0, "logo_url": "http://wx.qlogo.cn/mmhead/OibRNdtlJdkFLMHYLMR92Lvq0PicDpJpbnaicP3Z6kVcCicLPVjCWbAA9w/132", "my_id": 23, "nick_name": 评论用户的名字, "reply": { "reply_list": [ ] } } ], "elected_comment_total_cnt": 3, 评论总数 "enabled": 1, "friend_comment": [ ], "is_fans": 1, "logo_url": "http://wx.qlogo.cn/mmhead/Q3auHgzwzM6GAic0FAHOu9Gtv5lEu5kUqO6y6EjEFjAhuhUNIS7Y2AQ/132", "my_comment": [ ], "nick_name": 当前用户名, "only_fans_can_comment": false }
获取文章评论
[ "获取文章评论" ]
def comments(self, article_url): """ 获取文章评论 Parameters ---------- article_url: str 文章链接 Returns ------- json:: { "base_resp": { "errmsg": "ok", "ret": 0 }, "elected_comment": [ { "content": 用户评论文字, "content_id": "6846263421277569047", "create_time": 1520098511, "id": 3, "is_from_friend": 0, "is_from_me": 0, "is_top": 0, 是否被置顶 "like_id": 10001, "like_num": 3, "like_status": 0, "logo_url": "http://wx.qlogo.cn/mmhead/OibRNdtlJdkFLMHYLMR92Lvq0PicDpJpbnaicP3Z6kVcCicLPVjCWbAA9w/132", "my_id": 23, "nick_name": 评论用户的名字, "reply": { "reply_list": [ ] } } ], "elected_comment_total_cnt": 3, 评论总数 "enabled": 1, "friend_comment": [ ], "is_fans": 1, "logo_url": "http://wx.qlogo.cn/mmhead/Q3auHgzwzM6GAic0FAHOu9Gtv5lEu5kUqO6y6EjEFjAhuhUNIS7Y2AQ/132", "my_comment": [ ], "nick_name": 当前用户名, "only_fans_can_comment": false } """ __biz, _, idx, _ = self.__get_params(article_url) getcomment_url = "https://mp.weixin.qq.com/mp/appmsg_comment?action=getcomment&__biz={}&idx={}&comment_id={}&limit=100" try: comment_id = self.__get_comment_id(article_url) if comment_id == "": return {} url = getcomment_url.format(__biz, idx, comment_id) return self.s.get(url, headers=self.headers, proxies=self.proxies).json() except Exception as e: print(e) return {}
[ "def", "comments", "(", "self", ",", "article_url", ")", ":", "__biz", ",", "_", ",", "idx", ",", "_", "=", "self", ".", "__get_params", "(", "article_url", ")", "getcomment_url", "=", "\"https://mp.weixin.qq.com/mp/appmsg_comment?action=getcomment&__biz={}&idx={}&comment_id={}&limit=100\"", "try", ":", "comment_id", "=", "self", ".", "__get_comment_id", "(", "article_url", ")", "if", "comment_id", "==", "\"\"", ":", "return", "{", "}", "url", "=", "getcomment_url", ".", "format", "(", "__biz", ",", "idx", ",", "comment_id", ")", "return", "self", ".", "s", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "proxies", "=", "self", ".", "proxies", ")", ".", "json", "(", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "return", "{", "}" ]
https://github.com/wnma3mz/wechat_articles_spider/blob/77704ffe454a5f7cf287f7ccd07a005ea85ee066/wechatarticles/ArticlesInfo.py#L75-L133
crowdresearch/daemo
36e3b70d4e2c06b4853e9209a4916f8301ed6464
csp/utils.py
python
authenticate
(request)
Returns two-tuple of (user, token) if authentication succeeds, or None otherwise.
Returns two-tuple of (user, token) if authentication succeeds, or None otherwise.
[ "Returns", "two", "-", "tuple", "of", "(", "user", "token", ")", "if", "authentication", "succeeds", "or", "None", "otherwise", "." ]
def authenticate(request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: return r.user, r.access_token else: return None, None
[ "def", "authenticate", "(", "request", ")", ":", "oauthlib_core", "=", "get_oauthlib_core", "(", ")", "valid", ",", "r", "=", "oauthlib_core", ".", "verify_request", "(", "request", ",", "scopes", "=", "[", "]", ")", "if", "valid", ":", "return", "r", ".", "user", ",", "r", ".", "access_token", "else", ":", "return", "None", ",", "None" ]
https://github.com/crowdresearch/daemo/blob/36e3b70d4e2c06b4853e9209a4916f8301ed6464/csp/utils.py#L27-L37
getsentry/sentry
83b1f25aac3e08075e0e2495bc29efaf35aca18a
src/sentry_plugins/trello/client.py
python
TrelloApiClient.get_organization_options
(self)
return [(org["id"], org["name"]) for org in organizations]
Return organization options to use in a Django form
Return organization options to use in a Django form
[ "Return", "organization", "options", "to", "use", "in", "a", "Django", "form" ]
def get_organization_options(self): """ Return organization options to use in a Django form """ organizations = self.get_organization_list(fields="name") return [(org["id"], org["name"]) for org in organizations]
[ "def", "get_organization_options", "(", "self", ")", ":", "organizations", "=", "self", ".", "get_organization_list", "(", "fields", "=", "\"name\"", ")", "return", "[", "(", "org", "[", "\"id\"", "]", ",", "org", "[", "\"name\"", "]", ")", "for", "org", "in", "organizations", "]" ]
https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry_plugins/trello/client.py#L70-L75
mediacloud/backend
d36b489e4fbe6e44950916a04d9543a1d6cd5df0
apps/common/src/python/mediawords/db/locks.py
python
list_session_locks
(db: mediawords.db.DatabaseHandler, lock_type: str)
return db.query( "select objid from pg_locks where locktype = 'advisory' and classid = %(a)s", {'a': lock_type_id}).flat()
Return a list of all locked ids for the given lock_type.
Return a list of all locked ids for the given lock_type.
[ "Return", "a", "list", "of", "all", "locked", "ids", "for", "the", "given", "lock_type", "." ]
def list_session_locks(db: mediawords.db.DatabaseHandler, lock_type: str) -> list: """Return a list of all locked ids for the given lock_type.""" lock_type = str(decode_object_from_bytes_if_needed(lock_type)) if lock_type not in LOCK_TYPES: raise McDBLocksException("lock type not in LOCK_TYPES: %s" % lock_type) lock_type_id = LOCK_TYPES[lock_type] # noinspection SqlResolve return db.query( "select objid from pg_locks where locktype = 'advisory' and classid = %(a)s", {'a': lock_type_id}).flat()
[ "def", "list_session_locks", "(", "db", ":", "mediawords", ".", "db", ".", "DatabaseHandler", ",", "lock_type", ":", "str", ")", "->", "list", ":", "lock_type", "=", "str", "(", "decode_object_from_bytes_if_needed", "(", "lock_type", ")", ")", "if", "lock_type", "not", "in", "LOCK_TYPES", ":", "raise", "McDBLocksException", "(", "\"lock type not in LOCK_TYPES: %s\"", "%", "lock_type", ")", "lock_type_id", "=", "LOCK_TYPES", "[", "lock_type", "]", "# noinspection SqlResolve", "return", "db", ".", "query", "(", "\"select objid from pg_locks where locktype = 'advisory' and classid = %(a)s\"", ",", "{", "'a'", ":", "lock_type_id", "}", ")", ".", "flat", "(", ")" ]
https://github.com/mediacloud/backend/blob/d36b489e4fbe6e44950916a04d9543a1d6cd5df0/apps/common/src/python/mediawords/db/locks.py#L89-L101
whoosh-community/whoosh
5421f1ab3bb802114105b3181b7ce4f44ad7d0bb
src/whoosh/util/times.py
python
adatetime.floor
(self)
return datetime(y, m, d, h, mn, s, ms)
Returns a ``datetime`` version of this object with all unspecified (None) attributes replaced by their lowest values. This method raises an error if the ``adatetime`` object has no year. >>> adt = adatetime(year=2009, month=5) >>> adt.floor() datetime.datetime(2009, 5, 1, 0, 0, 0, 0)
Returns a ``datetime`` version of this object with all unspecified (None) attributes replaced by their lowest values.
[ "Returns", "a", "datetime", "version", "of", "this", "object", "with", "all", "unspecified", "(", "None", ")", "attributes", "replaced", "by", "their", "lowest", "values", "." ]
def floor(self): """Returns a ``datetime`` version of this object with all unspecified (None) attributes replaced by their lowest values. This method raises an error if the ``adatetime`` object has no year. >>> adt = adatetime(year=2009, month=5) >>> adt.floor() datetime.datetime(2009, 5, 1, 0, 0, 0, 0) """ y, m, d, h, mn, s, ms = (self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond) if y is None: raise ValueError("Date has no year") if m is None: m = 1 if d is None: d = 1 if h is None: h = 0 if mn is None: mn = 0 if s is None: s = 0 if ms is None: ms = 0 return datetime(y, m, d, h, mn, s, ms)
[ "def", "floor", "(", "self", ")", ":", "y", ",", "m", ",", "d", ",", "h", ",", "mn", ",", "s", ",", "ms", "=", "(", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day", ",", "self", ".", "hour", ",", "self", ".", "minute", ",", "self", ".", "second", ",", "self", ".", "microsecond", ")", "if", "y", "is", "None", ":", "raise", "ValueError", "(", "\"Date has no year\"", ")", "if", "m", "is", "None", ":", "m", "=", "1", "if", "d", "is", "None", ":", "d", "=", "1", "if", "h", "is", "None", ":", "h", "=", "0", "if", "mn", "is", "None", ":", "mn", "=", "0", "if", "s", "is", "None", ":", "s", "=", "0", "if", "ms", "is", "None", ":", "ms", "=", "0", "return", "datetime", "(", "y", ",", "m", ",", "d", ",", "h", ",", "mn", ",", "s", ",", "ms", ")" ]
https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/util/times.py#L179-L208
mwouts/jupytext
f8e8352859cc22e17b11154d0770fd946c4a430a
jupytext/config.py
python
find_global_jupytext_configuration_file
()
return None
Return the global Jupytext configuration file, if any
Return the global Jupytext configuration file, if any
[ "Return", "the", "global", "Jupytext", "configuration", "file", "if", "any" ]
def find_global_jupytext_configuration_file(): """Return the global Jupytext configuration file, if any""" for config_dir in global_jupytext_configuration_directories(): config_file = find_jupytext_configuration_file(config_dir, False) if config_file: return config_file return None
[ "def", "find_global_jupytext_configuration_file", "(", ")", ":", "for", "config_dir", "in", "global_jupytext_configuration_directories", "(", ")", ":", "config_file", "=", "find_jupytext_configuration_file", "(", "config_dir", ",", "False", ")", "if", "config_file", ":", "return", "config_file", "return", "None" ]
https://github.com/mwouts/jupytext/blob/f8e8352859cc22e17b11154d0770fd946c4a430a/jupytext/config.py#L303-L311
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/directorybackedaddressbook.py
python
DirectoryBackedAddressBookResource.makeChild
(self, name)
return self.directory
[]
def makeChild(self, name): from twistedcaldav.simpleresource import SimpleCalDAVResource return SimpleCalDAVResource(principalCollections=self.principalCollections()) return self.directory
[ "def", "makeChild", "(", "self", ",", "name", ")", ":", "from", "twistedcaldav", ".", "simpleresource", "import", "SimpleCalDAVResource", "return", "SimpleCalDAVResource", "(", "principalCollections", "=", "self", ".", "principalCollections", "(", ")", ")", "return", "self", ".", "directory" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/directorybackedaddressbook.py#L73-L76
has2k1/plotnine
6c82cdc20d6f81c96772da73fc07a672a0a0a6ef
plotnine/stats/stat.py
python
stat.compute_layer
(cls, data, params, layout)
return groupby_apply(data, 'PANEL', fn)
Calculate statistics for this layers This is the top-most computation method for the stat. It does not do any computations, but it knows how to verify the data, partition it call the next computation method and merge results. stats should not override this method. Parameters ---------- data : panda.DataFrame Data points for all objects in a layer. params : dict Stat parameters layout : plotnine.layout.Layout Panel layout information
Calculate statistics for this layers
[ "Calculate", "statistics", "for", "this", "layers" ]
def compute_layer(cls, data, params, layout): """ Calculate statistics for this layers This is the top-most computation method for the stat. It does not do any computations, but it knows how to verify the data, partition it call the next computation method and merge results. stats should not override this method. Parameters ---------- data : panda.DataFrame Data points for all objects in a layer. params : dict Stat parameters layout : plotnine.layout.Layout Panel layout information """ check_required_aesthetics( cls.REQUIRED_AES, list(data.columns) + list(params.keys()), cls.__name__) data = remove_missing( data, na_rm=params.get('na_rm', False), vars=list(cls.REQUIRED_AES | cls.NON_MISSING_AES), name=cls.__name__, finite=True) def fn(pdata): """ Helper compute function """ # Given data belonging to a specific panel, grab # the corresponding scales and call the method # that does the real computation if len(pdata) == 0: return pdata pscales = layout.get_scales(pdata['PANEL'].iat[0]) return cls.compute_panel(pdata, pscales, **params) return groupby_apply(data, 'PANEL', fn)
[ "def", "compute_layer", "(", "cls", ",", "data", ",", "params", ",", "layout", ")", ":", "check_required_aesthetics", "(", "cls", ".", "REQUIRED_AES", ",", "list", "(", "data", ".", "columns", ")", "+", "list", "(", "params", ".", "keys", "(", ")", ")", ",", "cls", ".", "__name__", ")", "data", "=", "remove_missing", "(", "data", ",", "na_rm", "=", "params", ".", "get", "(", "'na_rm'", ",", "False", ")", ",", "vars", "=", "list", "(", "cls", ".", "REQUIRED_AES", "|", "cls", ".", "NON_MISSING_AES", ")", ",", "name", "=", "cls", ".", "__name__", ",", "finite", "=", "True", ")", "def", "fn", "(", "pdata", ")", ":", "\"\"\"\n Helper compute function\n \"\"\"", "# Given data belonging to a specific panel, grab", "# the corresponding scales and call the method", "# that does the real computation", "if", "len", "(", "pdata", ")", "==", "0", ":", "return", "pdata", "pscales", "=", "layout", ".", "get_scales", "(", "pdata", "[", "'PANEL'", "]", ".", "iat", "[", "0", "]", ")", "return", "cls", ".", "compute_panel", "(", "pdata", ",", "pscales", ",", "*", "*", "params", ")", "return", "groupby_apply", "(", "data", ",", "'PANEL'", ",", "fn", ")" ]
https://github.com/has2k1/plotnine/blob/6c82cdc20d6f81c96772da73fc07a672a0a0a6ef/plotnine/stats/stat.py#L232-L276
awslabs/sockeye
ec2d13f7beb42d8c4f389dba0172250dc9154d5a
sockeye/model.py
python
SockeyeModel.save_version
(folder: str)
Saves version to <folder>/version. :param folder: Destination folder.
Saves version to <folder>/version.
[ "Saves", "version", "to", "<folder", ">", "/", "version", "." ]
def save_version(folder: str): """ Saves version to <folder>/version. :param folder: Destination folder. """ fname = os.path.join(folder, C.VERSION_NAME) with open(fname, "w") as out: out.write(__version__)
[ "def", "save_version", "(", "folder", ":", "str", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "C", ".", "VERSION_NAME", ")", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "out", ":", "out", ".", "write", "(", "__version__", ")" ]
https://github.com/awslabs/sockeye/blob/ec2d13f7beb42d8c4f389dba0172250dc9154d5a/sockeye/model.py#L405-L413
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
09-closure-deco/fibo_demo.py
python
fibonacci
(n)
return fibonacci(n - 2) + fibonacci(n - 1)
[]
def fibonacci(n): if n < 2: return n return fibonacci(n - 2) + fibonacci(n - 1)
[ "def", "fibonacci", "(", "n", ")", ":", "if", "n", "<", "2", ":", "return", "n", "return", "fibonacci", "(", "n", "-", "2", ")", "+", "fibonacci", "(", "n", "-", "1", ")" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/09-closure-deco/fibo_demo.py#L5-L8
jupyter-incubator/sparkmagic
ac0852cbe88a41faa368cf1e1c89045a2de973bf
sparkmagic/sparkmagic/utils/dataframe_parser.py
python
cell_components_iter
(cell)
Provides spans for each dataframe in a cell. 1. Determines if the evaluated output of a cell contains a Spark DF 2. Splits the cell output on Dataframes 3. Alternates yielding Plain Text and DF spans of evaluated cell output For example if our cell looked like this with provided line numbers: 0 1 Random stuff at the start 45 +---+------+ | id|animal| +---+------+ | 1| bat| | 2| mouse| | 3| horse| 247 +---+------+ Random stuff in the middle 293 The cell components are (CellComponent.TEXT, 0, 45) (CellComponentType.DF, 45, 247) (CellComponentType.TEXT, 247, 293)
Provides spans for each dataframe in a cell. 1. Determines if the evaluated output of a cell contains a Spark DF 2. Splits the cell output on Dataframes 3. Alternates yielding Plain Text and DF spans of evaluated cell output For example if our cell looked like this with provided line numbers:
[ "Provides", "spans", "for", "each", "dataframe", "in", "a", "cell", ".", "1", ".", "Determines", "if", "the", "evaluated", "output", "of", "a", "cell", "contains", "a", "Spark", "DF", "2", ".", "Splits", "the", "cell", "output", "on", "Dataframes", "3", ".", "Alternates", "yielding", "Plain", "Text", "and", "DF", "spans", "of", "evaluated", "cell", "output", "For", "example", "if", "our", "cell", "looked", "like", "this", "with", "provided", "line", "numbers", ":" ]
def cell_components_iter(cell): """Provides spans for each dataframe in a cell. 1. Determines if the evaluated output of a cell contains a Spark DF 2. Splits the cell output on Dataframes 3. Alternates yielding Plain Text and DF spans of evaluated cell output For example if our cell looked like this with provided line numbers: 0 1 Random stuff at the start 45 +---+------+ | id|animal| +---+------+ | 1| bat| | 2| mouse| | 3| horse| 247 +---+------+ Random stuff in the middle 293 The cell components are (CellComponent.TEXT, 0, 45) (CellComponentType.DF, 45, 247) (CellComponentType.TEXT, 247, 293) """ if not cell: return df_spans = dataframe_pattern_r.finditer(cell) if cell_contains_dataframe(cell): df_start, df_end = next(df_spans).span() if(df_start > 0): # Some text before the first Dataframe yield (CellComponentType.TEXT, 0, df_start) while df_start < len(cell): yield (CellComponentType.DF, df_start, df_end) try: start, end = next(df_spans).span() if start > df_end: # Some text before the next Dataframe yield (CellComponentType.TEXT, df_end, start) df_start, df_end = start, end except StopIteration: yield (CellComponentType.TEXT, df_end, len(cell)) return else: # Cell does not contain a DF. The whole cell is text. yield (CellComponentType.TEXT, 0, len(cell))
[ "def", "cell_components_iter", "(", "cell", ")", ":", "if", "not", "cell", ":", "return", "df_spans", "=", "dataframe_pattern_r", ".", "finditer", "(", "cell", ")", "if", "cell_contains_dataframe", "(", "cell", ")", ":", "df_start", ",", "df_end", "=", "next", "(", "df_spans", ")", ".", "span", "(", ")", "if", "(", "df_start", ">", "0", ")", ":", "# Some text before the first Dataframe", "yield", "(", "CellComponentType", ".", "TEXT", ",", "0", ",", "df_start", ")", "while", "df_start", "<", "len", "(", "cell", ")", ":", "yield", "(", "CellComponentType", ".", "DF", ",", "df_start", ",", "df_end", ")", "try", ":", "start", ",", "end", "=", "next", "(", "df_spans", ")", ".", "span", "(", ")", "if", "start", ">", "df_end", ":", "# Some text before the next Dataframe", "yield", "(", "CellComponentType", ".", "TEXT", ",", "df_end", ",", "start", ")", "df_start", ",", "df_end", "=", "start", ",", "end", "except", "StopIteration", ":", "yield", "(", "CellComponentType", ".", "TEXT", ",", "df_end", ",", "len", "(", "cell", ")", ")", "return", "else", ":", "# Cell does not contain a DF. The whole cell is text.", "yield", "(", "CellComponentType", ".", "TEXT", ",", "0", ",", "len", "(", "cell", ")", ")" ]
https://github.com/jupyter-incubator/sparkmagic/blob/ac0852cbe88a41faa368cf1e1c89045a2de973bf/sparkmagic/sparkmagic/utils/dataframe_parser.py#L93-L141
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_adm_registry.py
python
Service.add_portal_ip
(self, pip)
add cluster ip
add cluster ip
[ "add", "cluster", "ip" ]
def add_portal_ip(self, pip): '''add cluster ip''' self.put(Service.portal_ip, pip)
[ "def", "add_portal_ip", "(", "self", ",", "pip", ")", ":", "self", ".", "put", "(", "Service", ".", "portal_ip", ",", "pip", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_adm_registry.py#L2182-L2184
kivymd/KivyMD
1cb82f7d2437770f71be7c5a4f7de4b8da61f352
kivymd/uix/button/button.py
python
MDFloatingActionButtonSpeedDial.open_stack
( self, instance_floating_root_button: MDFloatingRootButton )
Opens a button stack.
Opens a button stack.
[ "Opens", "a", "button", "stack", "." ]
def open_stack( self, instance_floating_root_button: MDFloatingRootButton ) -> NoReturn: """Opens a button stack.""" for widget in self.children: if isinstance(widget, MDFloatingLabel): Animation.cancel_all(widget) if self.state != "open": y = 0 label_position = dp(56) anim_buttons_data = {} anim_labels_data = {} for widget in self.children: if isinstance(widget, MDFloatingBottomButton): # Sets new button positions. y += dp(56) widget.y = widget.y * 2 + y if not self._anim_buttons_data: anim_buttons_data[widget] = Animation( opacity=1, d=self.opening_time, t=self.opening_transition, ) elif isinstance(widget, MDFloatingLabel): # Sets new labels positions. label_position += dp(56) # Sets the position of signatures only once. if not self._label_pos_y_set: widget.y = widget.y * 2 + label_position widget.x = Window.width - widget.width - dp(86) if not self._anim_labels_data: anim_labels_data[widget] = Animation( opacity=1, d=self.opening_time ) elif ( isinstance(widget, MDFloatingRootButton) and self.root_button_anim ): # Rotates the root button 45 degrees. Animation( _angle=-45, d=self.opening_time_button_rotation, t=self.opening_transition_button_rotation, ).start(widget) if anim_buttons_data: self._anim_buttons_data = anim_buttons_data if anim_labels_data and not self.hint_animation: self._anim_labels_data = anim_labels_data self.state = "open" self.dispatch("on_open") self.do_animation_open_stack(self._anim_buttons_data) self.do_animation_open_stack(self._anim_labels_data) if not self._label_pos_y_set: self._label_pos_y_set = True else: self.close_stack()
[ "def", "open_stack", "(", "self", ",", "instance_floating_root_button", ":", "MDFloatingRootButton", ")", "->", "NoReturn", ":", "for", "widget", "in", "self", ".", "children", ":", "if", "isinstance", "(", "widget", ",", "MDFloatingLabel", ")", ":", "Animation", ".", "cancel_all", "(", "widget", ")", "if", "self", ".", "state", "!=", "\"open\"", ":", "y", "=", "0", "label_position", "=", "dp", "(", "56", ")", "anim_buttons_data", "=", "{", "}", "anim_labels_data", "=", "{", "}", "for", "widget", "in", "self", ".", "children", ":", "if", "isinstance", "(", "widget", ",", "MDFloatingBottomButton", ")", ":", "# Sets new button positions.", "y", "+=", "dp", "(", "56", ")", "widget", ".", "y", "=", "widget", ".", "y", "*", "2", "+", "y", "if", "not", "self", ".", "_anim_buttons_data", ":", "anim_buttons_data", "[", "widget", "]", "=", "Animation", "(", "opacity", "=", "1", ",", "d", "=", "self", ".", "opening_time", ",", "t", "=", "self", ".", "opening_transition", ",", ")", "elif", "isinstance", "(", "widget", ",", "MDFloatingLabel", ")", ":", "# Sets new labels positions.", "label_position", "+=", "dp", "(", "56", ")", "# Sets the position of signatures only once.", "if", "not", "self", ".", "_label_pos_y_set", ":", "widget", ".", "y", "=", "widget", ".", "y", "*", "2", "+", "label_position", "widget", ".", "x", "=", "Window", ".", "width", "-", "widget", ".", "width", "-", "dp", "(", "86", ")", "if", "not", "self", ".", "_anim_labels_data", ":", "anim_labels_data", "[", "widget", "]", "=", "Animation", "(", "opacity", "=", "1", ",", "d", "=", "self", ".", "opening_time", ")", "elif", "(", "isinstance", "(", "widget", ",", "MDFloatingRootButton", ")", "and", "self", ".", "root_button_anim", ")", ":", "# Rotates the root button 45 degrees.", "Animation", "(", "_angle", "=", "-", "45", ",", "d", "=", "self", ".", "opening_time_button_rotation", ",", "t", "=", "self", ".", "opening_transition_button_rotation", ",", ")", ".", "start", "(", "widget", ")", "if", "anim_buttons_data", ":", "self", ".", "_anim_buttons_data", "=", "anim_buttons_data", "if", "anim_labels_data", "and", "not", "self", ".", "hint_animation", ":", "self", ".", "_anim_labels_data", "=", "anim_labels_data", "self", ".", "state", "=", "\"open\"", "self", ".", "dispatch", "(", "\"on_open\"", ")", "self", ".", "do_animation_open_stack", "(", "self", ".", "_anim_buttons_data", ")", "self", ".", "do_animation_open_stack", "(", "self", ".", "_anim_labels_data", ")", "if", "not", "self", ".", "_label_pos_y_set", ":", "self", ".", "_label_pos_y_set", "=", "True", "else", ":", "self", ".", "close_stack", "(", ")" ]
https://github.com/kivymd/KivyMD/blob/1cb82f7d2437770f71be7c5a4f7de4b8da61f352/kivymd/uix/button/button.py#L1858-L1918
biocore/qiime
76d633c0389671e93febbe1338b5ded658eba31f
qiime/rarefaction.py
python
RarefactionMaker.rarefy_to_files
(self, output_dir, small_included=False, include_full=False, include_lineages=False, empty_otus_removed=False, subsample_f=subsample)
computes rarefied otu tables and writes them, one at a time this prevents large memory usage
computes rarefied otu tables and writes them, one at a time
[ "computes", "rarefied", "otu", "tables", "and", "writes", "them", "one", "at", "a", "time" ]
def rarefy_to_files(self, output_dir, small_included=False, include_full=False, include_lineages=False, empty_otus_removed=False, subsample_f=subsample): """ computes rarefied otu tables and writes them, one at a time this prevents large memory usage""" if not include_lineages: for (val, id, meta) in self.otu_table.iter(axis='observation'): try: del meta['taxonomy'] except (TypeError, KeyError) as e: # no meta or just no taxonomy present pass self.output_dir = output_dir for depth in self.rare_depths: for rep in range(self.num_reps): sub_otu_table = get_rare_data(self.otu_table, depth, small_included, subsample_f=subsample_f) if empty_otus_removed: sub_otu_table = filter_otus_from_otu_table( sub_otu_table, sub_otu_table.ids(axis='observation'), 1, inf, 0, inf) self._write_rarefaction(depth, rep, sub_otu_table) if include_full: self._write_rarefaction('full', 0, self.otu_table)
[ "def", "rarefy_to_files", "(", "self", ",", "output_dir", ",", "small_included", "=", "False", ",", "include_full", "=", "False", ",", "include_lineages", "=", "False", ",", "empty_otus_removed", "=", "False", ",", "subsample_f", "=", "subsample", ")", ":", "if", "not", "include_lineages", ":", "for", "(", "val", ",", "id", ",", "meta", ")", "in", "self", ".", "otu_table", ".", "iter", "(", "axis", "=", "'observation'", ")", ":", "try", ":", "del", "meta", "[", "'taxonomy'", "]", "except", "(", "TypeError", ",", "KeyError", ")", "as", "e", ":", "# no meta or just no taxonomy present", "pass", "self", ".", "output_dir", "=", "output_dir", "for", "depth", "in", "self", ".", "rare_depths", ":", "for", "rep", "in", "range", "(", "self", ".", "num_reps", ")", ":", "sub_otu_table", "=", "get_rare_data", "(", "self", ".", "otu_table", ",", "depth", ",", "small_included", ",", "subsample_f", "=", "subsample_f", ")", "if", "empty_otus_removed", ":", "sub_otu_table", "=", "filter_otus_from_otu_table", "(", "sub_otu_table", ",", "sub_otu_table", ".", "ids", "(", "axis", "=", "'observation'", ")", ",", "1", ",", "inf", ",", "0", ",", "inf", ")", "self", ".", "_write_rarefaction", "(", "depth", ",", "rep", ",", "sub_otu_table", ")", "if", "include_full", ":", "self", ".", "_write_rarefaction", "(", "'full'", ",", "0", ",", "self", ".", "otu_table", ")" ]
https://github.com/biocore/qiime/blob/76d633c0389671e93febbe1338b5ded658eba31f/qiime/rarefaction.py#L96-L125
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo._apply_pax_info
(self, pax_headers, encoding, errors)
Replace fields with supplemental information from a previous pax extended or global header.
Replace fields with supplemental information from a previous pax extended or global header.
[ "Replace", "fields", "with", "supplemental", "information", "from", "a", "previous", "pax", "extended", "or", "global", "header", "." ]
def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pax_headers.items(): if keyword == "GNU.sparse.name": setattr(self, "path", value) elif keyword == "GNU.sparse.size": setattr(self, "size", int(value)) elif keyword == "GNU.sparse.realsize": setattr(self, "size", int(value)) elif keyword in PAX_FIELDS: if keyword in PAX_NUMBER_FIELDS: try: value = PAX_NUMBER_FIELDS[keyword](value) except ValueError: value = 0 if keyword == "path": value = value.rstrip("/") setattr(self, keyword, value) self.pax_headers = pax_headers.copy()
[ "def", "_apply_pax_info", "(", "self", ",", "pax_headers", ",", "encoding", ",", "errors", ")", ":", "for", "keyword", ",", "value", "in", "pax_headers", ".", "items", "(", ")", ":", "if", "keyword", "==", "\"GNU.sparse.name\"", ":", "setattr", "(", "self", ",", "\"path\"", ",", "value", ")", "elif", "keyword", "==", "\"GNU.sparse.size\"", ":", "setattr", "(", "self", ",", "\"size\"", ",", "int", "(", "value", ")", ")", "elif", "keyword", "==", "\"GNU.sparse.realsize\"", ":", "setattr", "(", "self", ",", "\"size\"", ",", "int", "(", "value", ")", ")", "elif", "keyword", "in", "PAX_FIELDS", ":", "if", "keyword", "in", "PAX_NUMBER_FIELDS", ":", "try", ":", "value", "=", "PAX_NUMBER_FIELDS", "[", "keyword", "]", "(", "value", ")", "except", "ValueError", ":", "value", "=", "0", "if", "keyword", "==", "\"path\"", ":", "value", "=", "value", ".", "rstrip", "(", "\"/\"", ")", "setattr", "(", "self", ",", "keyword", ",", "value", ")", "self", ".", "pax_headers", "=", "pax_headers", ".", "copy", "(", ")" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1518-L1539
maurosoria/dirsearch
b83e68c8fdf360ab06be670d7b92b263262ee5b1
thirdparty/requests/auth.py
python
HTTPDigestAuth.handle_redirect
(self, r, **kwargs)
Reset num_401_calls counter on redirects.
Reset num_401_calls counter on redirects.
[ "Reset", "num_401_calls", "counter", "on", "redirects", "." ]
def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1
[ "def", "handle_redirect", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "r", ".", "is_redirect", ":", "self", ".", "_thread_local", ".", "num_401_calls", "=", "1" ]
https://github.com/maurosoria/dirsearch/blob/b83e68c8fdf360ab06be670d7b92b263262ee5b1/thirdparty/requests/auth.py#L229-L232
ctallec/world-models
d6abd9ce97409734a766eb67ccf0d1967ba9bf0c
envs/simulated_carracing.py
python
SimulatedCarracing.render
(self)
Rendering
Rendering
[ "Rendering" ]
def render(self): # pylint: disable=arguments-differ """ Rendering """ import matplotlib.pyplot as plt if not self.monitor: self.figure = plt.figure() self.monitor = plt.imshow( np.zeros((RED_SIZE, RED_SIZE, 3), dtype=np.uint8)) self.monitor.set_data(self._visual_obs) plt.pause(.01)
[ "def", "render", "(", "self", ")", ":", "# pylint: disable=arguments-differ", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "not", "self", ".", "monitor", ":", "self", ".", "figure", "=", "plt", ".", "figure", "(", ")", "self", ".", "monitor", "=", "plt", ".", "imshow", "(", "np", ".", "zeros", "(", "(", "RED_SIZE", ",", "RED_SIZE", ",", "3", ")", ",", "dtype", "=", "np", ".", "uint8", ")", ")", "self", ".", "monitor", ".", "set_data", "(", "self", ".", "_visual_obs", ")", "plt", ".", "pause", "(", ".01", ")" ]
https://github.com/ctallec/world-models/blob/d6abd9ce97409734a766eb67ccf0d1967ba9bf0c/envs/simulated_carracing.py#L101-L110
nyu-dl/dl4marco-bert
f1d18d63271d9e53cd23fc27bd7cc911f89b89db
tokenization.py
python
convert_tokens_to_ids
(vocab, tokens)
return [vocab[token] for token in tokens]
Converts a sequence of tokens into ids using the vocab.
Converts a sequence of tokens into ids using the vocab.
[ "Converts", "a", "sequence", "of", "tokens", "into", "ids", "using", "the", "vocab", "." ]
def convert_tokens_to_ids(vocab, tokens): """Converts a sequence of tokens into ids using the vocab.""" return [vocab[token] for token in tokens]
[ "def", "convert_tokens_to_ids", "(", "vocab", ",", "tokens", ")", ":", "return", "[", "vocab", "[", "token", "]", "for", "token", "in", "tokens", "]" ]
https://github.com/nyu-dl/dl4marco-bert/blob/f1d18d63271d9e53cd23fc27bd7cc911f89b89db/tokenization.py#L120-L122
SaltieRL/Saltie
a491ecfa5c77583ec370a0a378d27865dbd8da63
framework/self_evolving_car/genetic_algorithm.py
python
GeneticAlgorithm.mutate
(self, list, mut_rate)
Randomizes a certain amount of the first five models' parameters based on mutation rate :param list contains the parameters to be mutated :param mut_rate is the mutation rate
Randomizes a certain amount of the first five models' parameters based on mutation rate :param list contains the parameters to be mutated :param mut_rate is the mutation rate
[ "Randomizes", "a", "certain", "amount", "of", "the", "first", "five", "models", "parameters", "based", "on", "mutation", "rate", ":", "param", "list", "contains", "the", "parameters", "to", "be", "mutated", ":", "param", "mut_rate", "is", "the", "mutation", "rate" ]
def mutate(self, list, mut_rate): """Randomizes a certain amount of the first five models' parameters based on mutation rate :param list contains the parameters to be mutated :param mut_rate is the mutation rate""" for i, bot in enumerate(list): new_genes = self.Model() for param, param_new in zip(bot.parameters(), new_genes.parameters()): mask = self.torch.rand(param.data.size()) < mut_rate / (i + 1) param.data[mask] = param_new.data[mask]
[ "def", "mutate", "(", "self", ",", "list", ",", "mut_rate", ")", ":", "for", "i", ",", "bot", "in", "enumerate", "(", "list", ")", ":", "new_genes", "=", "self", ".", "Model", "(", ")", "for", "param", ",", "param_new", "in", "zip", "(", "bot", ".", "parameters", "(", ")", ",", "new_genes", ".", "parameters", "(", ")", ")", ":", "mask", "=", "self", ".", "torch", ".", "rand", "(", "param", ".", "data", ".", "size", "(", ")", ")", "<", "mut_rate", "/", "(", "i", "+", "1", ")", "param", ".", "data", "[", "mask", "]", "=", "param_new", ".", "data", "[", "mask", "]" ]
https://github.com/SaltieRL/Saltie/blob/a491ecfa5c77583ec370a0a378d27865dbd8da63/framework/self_evolving_car/genetic_algorithm.py#L61-L70
zsdonghao/text-to-image
c1fbfa4349f5aa1c74c9fe17743cc0cff34f1aab
tensorlayer/cost.py
python
dice_coe
(output, target, epsilon=1e-10)
Sørensen–Dice coefficient for comparing the similarity of two distributions, usually be used for binary image segmentation i.e. labels are binary. The coefficient = [0, 1], 1 if totally match. Parameters ----------- output : tensor A distribution with shape: [batch_size, ....], (any dimensions). target : tensor A distribution with shape: [batch_size, ....], (any dimensions). epsilon : float An optional name to attach to this layer. Examples --------- >>> outputs = tl.act.pixel_wise_softmax(network.outputs) >>> dice_loss = 1 - tl.cost.dice_coe(outputs, y_, epsilon=1e-5) References ----------- - `wiki-dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`_
Sørensen–Dice coefficient for comparing the similarity of two distributions, usually be used for binary image segmentation i.e. labels are binary. The coefficient = [0, 1], 1 if totally match.
[ "Sørensen–Dice", "coefficient", "for", "comparing", "the", "similarity", "of", "two", "distributions", "usually", "be", "used", "for", "binary", "image", "segmentation", "i", ".", "e", ".", "labels", "are", "binary", ".", "The", "coefficient", "=", "[", "0", "1", "]", "1", "if", "totally", "match", "." ]
def dice_coe(output, target, epsilon=1e-10): """Sørensen–Dice coefficient for comparing the similarity of two distributions, usually be used for binary image segmentation i.e. labels are binary. The coefficient = [0, 1], 1 if totally match. Parameters ----------- output : tensor A distribution with shape: [batch_size, ....], (any dimensions). target : tensor A distribution with shape: [batch_size, ....], (any dimensions). epsilon : float An optional name to attach to this layer. Examples --------- >>> outputs = tl.act.pixel_wise_softmax(network.outputs) >>> dice_loss = 1 - tl.cost.dice_coe(outputs, y_, epsilon=1e-5) References ----------- - `wiki-dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`_ """ # inse = tf.reduce_sum( tf.mul(output, target) ) # l = tf.reduce_sum( tf.mul(output, output) ) # r = tf.reduce_sum( tf.mul(target, target) ) inse = tf.reduce_sum( output * target ) l = tf.reduce_sum( output * output ) r = tf.reduce_sum( target * target ) dice = 2 * (inse) / (l + r) if epsilon == 0: return dice else: return tf.clip_by_value(dice, 0, 1.0-epsilon)
[ "def", "dice_coe", "(", "output", ",", "target", ",", "epsilon", "=", "1e-10", ")", ":", "# inse = tf.reduce_sum( tf.mul(output, target) )", "# l = tf.reduce_sum( tf.mul(output, output) )", "# r = tf.reduce_sum( tf.mul(target, target) )", "inse", "=", "tf", ".", "reduce_sum", "(", "output", "*", "target", ")", "l", "=", "tf", ".", "reduce_sum", "(", "output", "*", "output", ")", "r", "=", "tf", ".", "reduce_sum", "(", "target", "*", "target", ")", "dice", "=", "2", "*", "(", "inse", ")", "/", "(", "l", "+", "r", ")", "if", "epsilon", "==", "0", ":", "return", "dice", "else", ":", "return", "tf", ".", "clip_by_value", "(", "dice", ",", "0", ",", "1.0", "-", "epsilon", ")" ]
https://github.com/zsdonghao/text-to-image/blob/c1fbfa4349f5aa1c74c9fe17743cc0cff34f1aab/tensorlayer/cost.py#L107-L140
ansible/ansible-modules-core
00911a75ad6635834b6d28eef41f197b2f73c381
source_control/subversion.py
python
Subversion.get_revision
(self)
return rev, url
Revision and URL of subversion working directory.
Revision and URL of subversion working directory.
[ "Revision", "and", "URL", "of", "subversion", "working", "directory", "." ]
def get_revision(self): '''Revision and URL of subversion working directory.''' text = '\n'.join(self._exec(["info", self.dest])) rev = re.search(r'^Revision:.*$', text, re.MULTILINE).group(0) url = re.search(r'^URL:.*$', text, re.MULTILINE).group(0) return rev, url
[ "def", "get_revision", "(", "self", ")", ":", "text", "=", "'\\n'", ".", "join", "(", "self", ".", "_exec", "(", "[", "\"info\"", ",", "self", ".", "dest", "]", ")", ")", "rev", "=", "re", ".", "search", "(", "r'^Revision:.*$'", ",", "text", ",", "re", ".", "MULTILINE", ")", ".", "group", "(", "0", ")", "url", "=", "re", ".", "search", "(", "r'^URL:.*$'", ",", "text", ",", "re", ".", "MULTILINE", ")", ".", "group", "(", "0", ")", "return", "rev", ",", "url" ]
https://github.com/ansible/ansible-modules-core/blob/00911a75ad6635834b6d28eef41f197b2f73c381/source_control/subversion.py#L194-L199
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
api/client/src/pcluster_client/model/image_builder_image_status.py
python
ImageBuilderImageStatus.openapi_types
()
return { 'value': (str,), }
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { 'value': (str,), }
[ "def", "openapi_types", "(", ")", ":", "return", "{", "'value'", ":", "(", "str", ",", ")", ",", "}" ]
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/api/client/src/pcluster_client/model/image_builder_image_status.py#L74-L85
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
fairseq/optim/fairseq_optimizer.py
python
FairseqOptimizer.clip_grad_norm
(self, max_norm, aggregate_norm_fn=None)
return utils.clip_grad_norm_(self.params, max_norm, aggregate_norm_fn)
Clips gradient norm.
Clips gradient norm.
[ "Clips", "gradient", "norm", "." ]
def clip_grad_norm(self, max_norm, aggregate_norm_fn=None): """Clips gradient norm.""" return utils.clip_grad_norm_(self.params, max_norm, aggregate_norm_fn)
[ "def", "clip_grad_norm", "(", "self", ",", "max_norm", ",", "aggregate_norm_fn", "=", "None", ")", ":", "return", "utils", ".", "clip_grad_norm_", "(", "self", ".", "params", ",", "max_norm", ",", "aggregate_norm_fn", ")" ]
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/optim/fairseq_optimizer.py#L110-L112
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/gui/gtkui/Dialog.py
python
InviteWindow.__init__
(self, session, callback, l_buddy_exclude)
constructor
constructor
[ "constructor" ]
def __init__(self, session, callback, l_buddy_exclude): """ constructor """ gtk.Window.__init__(self) global dialogs dialogs.append(self) self.set_border_width(1) self.set_title(_('Invite friend')) self.set_default_size(300, 250) self.session = session self.callback = callback ContactList = extension.get_default('contact list') self.contact_list = ContactList(session) sel = self.contact_list.get_selection() sel.set_mode(gtk.SELECTION_MULTIPLE) self.contact_list.destroy_on_filtering = True self.contact_list.nick_template = \ '[$DISPLAY_NAME][$NL][$small][$ACCOUNT][$/small]' order_by_group = self.contact_list.session.config.b_order_by_group show_blocked = self.contact_list.session.config.b_show_blocked show_offline = self.contact_list.session.config.b_show_offline self.contact_list.order_by_group = False self.contact_list.show_blocked = False self.contact_list.show_offline = False self.contact_list.hide_on_filtering = True self.contact_list.session.config.b_order_by_group = order_by_group self.contact_list.session.config.b_show_blocked = show_blocked self.contact_list.session.config.b_show_offline = show_offline self.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox() vbox.set_spacing(1) bbox = gtk.HButtonBox() bbox.set_spacing(1) bbox.set_layout(gtk.BUTTONBOX_END) badd = gtk.Button(stock=gtk.STOCK_ADD) bclose = gtk.Button(stock=gtk.STOCK_CLOSE) search = SearchEntry.SearchEntry() search.connect('changed', self._on_search_changed) scroll = gtk.ScrolledWindow() scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) scroll.set_shadow_type(gtk.SHADOW_IN) scroll.set_border_width(1) scroll.add(self.contact_list) bbox.pack_start(bclose) bbox.pack_start(badd) vbox.pack_start(scroll, True, True) vbox.pack_start(search, False) vbox.pack_start(bbox, False) self.add(vbox) badd.connect('clicked', self._on_add_clicked) bclose.connect('clicked', lambda *args: self.destroy()) self.connect('key-press-event', self._on_key_press) self.connect('delete-event', lambda *args: self.destroy()) self.contact_list.contact_selected.subscribe( self._on_contact_selected) self.contact_list.fill() l_buddy_exclude.append(self.session.account.account) for buddy in l_buddy_exclude: self.contact_list.remove_contact(e3.Contact(buddy)) self.set_modal(True) self.show() vbox.show_all()
[ "def", "__init__", "(", "self", ",", "session", ",", "callback", ",", "l_buddy_exclude", ")", ":", "gtk", ".", "Window", ".", "__init__", "(", "self", ")", "global", "dialogs", "dialogs", ".", "append", "(", "self", ")", "self", ".", "set_border_width", "(", "1", ")", "self", ".", "set_title", "(", "_", "(", "'Invite friend'", ")", ")", "self", ".", "set_default_size", "(", "300", ",", "250", ")", "self", ".", "session", "=", "session", "self", ".", "callback", "=", "callback", "ContactList", "=", "extension", ".", "get_default", "(", "'contact list'", ")", "self", ".", "contact_list", "=", "ContactList", "(", "session", ")", "sel", "=", "self", ".", "contact_list", ".", "get_selection", "(", ")", "sel", ".", "set_mode", "(", "gtk", ".", "SELECTION_MULTIPLE", ")", "self", ".", "contact_list", ".", "destroy_on_filtering", "=", "True", "self", ".", "contact_list", ".", "nick_template", "=", "'[$DISPLAY_NAME][$NL][$small][$ACCOUNT][$/small]'", "order_by_group", "=", "self", ".", "contact_list", ".", "session", ".", "config", ".", "b_order_by_group", "show_blocked", "=", "self", ".", "contact_list", ".", "session", ".", "config", ".", "b_show_blocked", "show_offline", "=", "self", ".", "contact_list", ".", "session", ".", "config", ".", "b_show_offline", "self", ".", "contact_list", ".", "order_by_group", "=", "False", "self", ".", "contact_list", ".", "show_blocked", "=", "False", "self", ".", "contact_list", ".", "show_offline", "=", "False", "self", ".", "contact_list", ".", "hide_on_filtering", "=", "True", "self", ".", "contact_list", ".", "session", ".", "config", ".", "b_order_by_group", "=", "order_by_group", "self", ".", "contact_list", ".", "session", ".", "config", ".", "b_show_blocked", "=", "show_blocked", "self", ".", "contact_list", ".", "session", ".", "config", ".", "b_show_offline", "=", "show_offline", "self", ".", "set_type_hint", "(", "gtk", ".", "gdk", ".", "WINDOW_TYPE_HINT_DIALOG", ")", "self", ".", "set_position", "(", "gtk", ".", "WIN_POS_CENTER", ")", "vbox", "=", "gtk", ".", "VBox", "(", ")", "vbox", ".", "set_spacing", "(", "1", ")", "bbox", "=", "gtk", ".", "HButtonBox", "(", ")", "bbox", ".", "set_spacing", "(", "1", ")", "bbox", ".", "set_layout", "(", "gtk", ".", "BUTTONBOX_END", ")", "badd", "=", "gtk", ".", "Button", "(", "stock", "=", "gtk", ".", "STOCK_ADD", ")", "bclose", "=", "gtk", ".", "Button", "(", "stock", "=", "gtk", ".", "STOCK_CLOSE", ")", "search", "=", "SearchEntry", ".", "SearchEntry", "(", ")", "search", ".", "connect", "(", "'changed'", ",", "self", ".", "_on_search_changed", ")", "scroll", "=", "gtk", ".", "ScrolledWindow", "(", ")", "scroll", ".", "set_policy", "(", "gtk", ".", "POLICY_NEVER", ",", "gtk", ".", "POLICY_AUTOMATIC", ")", "scroll", ".", "set_shadow_type", "(", "gtk", ".", "SHADOW_IN", ")", "scroll", ".", "set_border_width", "(", "1", ")", "scroll", ".", "add", "(", "self", ".", "contact_list", ")", "bbox", ".", "pack_start", "(", "bclose", ")", "bbox", ".", "pack_start", "(", "badd", ")", "vbox", ".", "pack_start", "(", "scroll", ",", "True", ",", "True", ")", "vbox", ".", "pack_start", "(", "search", ",", "False", ")", "vbox", ".", "pack_start", "(", "bbox", ",", "False", ")", "self", ".", "add", "(", "vbox", ")", "badd", ".", "connect", "(", "'clicked'", ",", "self", ".", "_on_add_clicked", ")", "bclose", ".", "connect", "(", "'clicked'", ",", "lambda", "*", "args", ":", "self", ".", "destroy", "(", ")", ")", "self", ".", "connect", "(", "'key-press-event'", ",", "self", ".", "_on_key_press", ")", "self", ".", "connect", "(", "'delete-event'", ",", "lambda", "*", "args", ":", "self", ".", "destroy", "(", ")", ")", "self", ".", "contact_list", ".", "contact_selected", ".", "subscribe", "(", "self", ".", "_on_contact_selected", ")", "self", ".", "contact_list", ".", "fill", "(", ")", "l_buddy_exclude", ".", "append", "(", "self", ".", "session", ".", "account", ".", "account", ")", "for", "buddy", "in", "l_buddy_exclude", ":", "self", ".", "contact_list", ".", "remove_contact", "(", "e3", ".", "Contact", "(", "buddy", ")", ")", "self", ".", "set_modal", "(", "True", ")", "self", ".", "show", "(", ")", "vbox", ".", "show_all", "(", ")" ]
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/gui/gtkui/Dialog.py#L1558-L1633
9miao/Firefly
fd2795b8c26de6ab63bbec23d11f18c3dfb39a50
gfirefly/utils/interfaces.py
python
IDataPackProtoc.getHeadlength
()
获取数据包的长度
获取数据包的长度
[ "获取数据包的长度" ]
def getHeadlength(): """获取数据包的长度 """ pass
[ "def", "getHeadlength", "(", ")", ":", "pass" ]
https://github.com/9miao/Firefly/blob/fd2795b8c26de6ab63bbec23d11f18c3dfb39a50/gfirefly/utils/interfaces.py#L13-L16
siznax/wptools
788cdc2078696dacb14652d5f2ad098a585e4763
wptools/query.py
python
WPToolsQuery.labels
(self, qids)
return query
Returns Wikidata labels query string
Returns Wikidata labels query string
[ "Returns", "Wikidata", "labels", "query", "string" ]
def labels(self, qids): """ Returns Wikidata labels query string """ if len(qids) > 50: raise ValueError("The limit is 50.") self.domain = 'www.wikidata.org' self.uri = self.wiki_uri(self.domain) query = self.WIKIDATA.substitute( WIKI=self.uri, ENDPOINT=self.endpoint, LANG=self.variant or self.lang, PROPS='labels') qids = '|'.join(qids) query += "&ids=%s" % qids self.set_status('labels', qids) return query
[ "def", "labels", "(", "self", ",", "qids", ")", ":", "if", "len", "(", "qids", ")", ">", "50", ":", "raise", "ValueError", "(", "\"The limit is 50.\"", ")", "self", ".", "domain", "=", "'www.wikidata.org'", "self", ".", "uri", "=", "self", ".", "wiki_uri", "(", "self", ".", "domain", ")", "query", "=", "self", ".", "WIKIDATA", ".", "substitute", "(", "WIKI", "=", "self", ".", "uri", ",", "ENDPOINT", "=", "self", ".", "endpoint", ",", "LANG", "=", "self", ".", "variant", "or", "self", ".", "lang", ",", "PROPS", "=", "'labels'", ")", "qids", "=", "'|'", ".", "join", "(", "qids", ")", "query", "+=", "\"&ids=%s\"", "%", "qids", "self", ".", "set_status", "(", "'labels'", ",", "qids", ")", "return", "query" ]
https://github.com/siznax/wptools/blob/788cdc2078696dacb14652d5f2ad098a585e4763/wptools/query.py#L161-L182
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/rigged_configurations/rigged_configuration_element.py
python
RCNonSimplyLacedElement.to_virtual_configuration
(self)
return self.parent().to_virtual(self)
Return the corresponding rigged configuration in the virtual crystal. EXAMPLES:: sage: RC = RiggedConfigurations(['C',2,1], [[1,2],[1,1],[2,1]]) sage: elt = RC(partition_list=[[3],[2]]); elt <BLANKLINE> 0[ ][ ][ ]0 <BLANKLINE> 0[ ][ ]0 sage: elt.to_virtual_configuration() <BLANKLINE> 0[ ][ ][ ]0 <BLANKLINE> 0[ ][ ][ ][ ]0 <BLANKLINE> 0[ ][ ][ ]0
Return the corresponding rigged configuration in the virtual crystal.
[ "Return", "the", "corresponding", "rigged", "configuration", "in", "the", "virtual", "crystal", "." ]
def to_virtual_configuration(self): """ Return the corresponding rigged configuration in the virtual crystal. EXAMPLES:: sage: RC = RiggedConfigurations(['C',2,1], [[1,2],[1,1],[2,1]]) sage: elt = RC(partition_list=[[3],[2]]); elt <BLANKLINE> 0[ ][ ][ ]0 <BLANKLINE> 0[ ][ ]0 sage: elt.to_virtual_configuration() <BLANKLINE> 0[ ][ ][ ]0 <BLANKLINE> 0[ ][ ][ ][ ]0 <BLANKLINE> 0[ ][ ][ ]0 """ return self.parent().to_virtual(self)
[ "def", "to_virtual_configuration", "(", "self", ")", ":", "return", "self", ".", "parent", "(", ")", ".", "to_virtual", "(", "self", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/rigged_configurations/rigged_configuration_element.py#L944-L964
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
24-class-metaprog/metabunch/pre3.6/bunch.py
python
MetaBunch.__prepare__
(name, *bases, **kwargs)
return collections.OrderedDict()
[]
def __prepare__(name, *bases, **kwargs): return collections.OrderedDict()
[ "def", "__prepare__", "(", "name", ",", "*", "bases", ",", "*", "*", "kwargs", ")", ":", "return", "collections", ".", "OrderedDict", "(", ")" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/24-class-metaprog/metabunch/pre3.6/bunch.py#L5-L6
kylebebak/Requester
4a9f9f051fa5fc951a8f7ad098a328261ca2db97
deps/graphql/parser.py
python
GraphQLParser.p_selection
(self, p)
selection : field | fragment_spread | inline_fragment
selection : field | fragment_spread | inline_fragment
[ "selection", ":", "field", "|", "fragment_spread", "|", "inline_fragment" ]
def p_selection(self, p): """ selection : field | fragment_spread | inline_fragment """ p[0] = p[1]
[ "def", "p_selection", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/kylebebak/Requester/blob/4a9f9f051fa5fc951a8f7ad098a328261ca2db97/deps/graphql/parser.py#L191-L197
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/kombu/transport/virtual/base.py
python
AbstractChannel._get_and_deliver
(self, queue, callback)
[]
def _get_and_deliver(self, queue, callback): message = self._get(queue) callback(message, queue)
[ "def", "_get_and_deliver", "(", "self", ",", "queue", ",", "callback", ")", ":", "message", "=", "self", ".", "_get", "(", "queue", ")", "callback", "(", "message", ",", "queue", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/kombu/transport/virtual/base.py#L404-L406
mtianyan/OnlineMooc
51a910e27c8d2808a8a5198b4db31f463e646bf6
app_api/models.py
python
EmailVerifyRecord.__str__
(self)
return self.code + ":" + self.email
[]
def __str__(self): return self.code + ":" + self.email
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "code", "+", "\":\"", "+", "self", ".", "email" ]
https://github.com/mtianyan/OnlineMooc/blob/51a910e27c8d2808a8a5198b4db31f463e646bf6/app_api/models.py#L28-L29
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tagging/models.py
python
TagManager.update_tags
(self, obj, tag_names)
Update tags associated with an object.
Update tags associated with an object.
[ "Update", "tags", "associated", "with", "an", "object", "." ]
def update_tags(self, obj, tag_names): """ Update tags associated with an object. """ ctype = ContentType.objects.get_for_model(obj) current_tags = list(self.filter(items__content_type__pk=ctype.pk, items__object_id=obj.pk)) updated_tag_names = parse_tag_input(tag_names) if settings.FORCE_LOWERCASE_TAGS: updated_tag_names = [t.lower() for t in updated_tag_names] # Remove tags which no longer apply tags_for_removal = [tag for tag in current_tags \ if tag.name not in updated_tag_names] if len(tags_for_removal): TaggedItem._default_manager.filter(content_type__pk=ctype.pk, object_id=obj.pk, tag__in=tags_for_removal).delete() # Add new tags current_tag_names = [tag.name for tag in current_tags] for tag_name in updated_tag_names: if tag_name not in current_tag_names: tag, created = self.get_or_create(name=tag_name) TaggedItem._default_manager.create(tag=tag, object=obj)
[ "def", "update_tags", "(", "self", ",", "obj", ",", "tag_names", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "current_tags", "=", "list", "(", "self", ".", "filter", "(", "items__content_type__pk", "=", "ctype", ".", "pk", ",", "items__object_id", "=", "obj", ".", "pk", ")", ")", "updated_tag_names", "=", "parse_tag_input", "(", "tag_names", ")", "if", "settings", ".", "FORCE_LOWERCASE_TAGS", ":", "updated_tag_names", "=", "[", "t", ".", "lower", "(", ")", "for", "t", "in", "updated_tag_names", "]", "# Remove tags which no longer apply", "tags_for_removal", "=", "[", "tag", "for", "tag", "in", "current_tags", "if", "tag", ".", "name", "not", "in", "updated_tag_names", "]", "if", "len", "(", "tags_for_removal", ")", ":", "TaggedItem", ".", "_default_manager", ".", "filter", "(", "content_type__pk", "=", "ctype", ".", "pk", ",", "object_id", "=", "obj", ".", "pk", ",", "tag__in", "=", "tags_for_removal", ")", ".", "delete", "(", ")", "# Add new tags", "current_tag_names", "=", "[", "tag", ".", "name", "for", "tag", "in", "current_tags", "]", "for", "tag_name", "in", "updated_tag_names", ":", "if", "tag_name", "not", "in", "current_tag_names", ":", "tag", ",", "created", "=", "self", ".", "get_or_create", "(", "name", "=", "tag_name", ")", "TaggedItem", ".", "_default_manager", ".", "create", "(", "tag", "=", "tag", ",", "object", "=", "obj", ")" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tagging/models.py#L27-L50
slush0/stratum-mining
b2a24d7424784cada95010232cdb79cfed481da6
lib/util.py
python
ser_uint256_be
(u)
return rs
ser_uint256 to big endian
ser_uint256 to big endian
[ "ser_uint256", "to", "big", "endian" ]
def ser_uint256_be(u): '''ser_uint256 to big endian''' rs = "" for i in xrange(8): rs += struct.pack(">I", u & 0xFFFFFFFFL) u >>= 32 return rs
[ "def", "ser_uint256_be", "(", "u", ")", ":", "rs", "=", "\"\"", "for", "i", "in", "xrange", "(", "8", ")", ":", "rs", "+=", "struct", ".", "pack", "(", "\">I\"", ",", "u", "&", "0xFFFFFFFFL", ")", "u", ">>=", "32", "return", "rs" ]
https://github.com/slush0/stratum-mining/blob/b2a24d7424784cada95010232cdb79cfed481da6/lib/util.py#L176-L182
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractCcKhatUs.py
python
extractCcKhatUs
(item)
return False
Parser for 'cc.khat.us'
Parser for 'cc.khat.us'
[ "Parser", "for", "cc", ".", "khat", ".", "us" ]
def extractCcKhatUs(item): ''' Parser for 'cc.khat.us' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractCcKhatUs", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", "in", "item", "[", "'title'", "]", ".", "lower", "(", ")", ":", "return", "None", "tagmap", "=", "[", "(", "'PRC'", ",", "'PRC'", ",", "'translated'", ")", ",", "(", "'Loiterous'", ",", "'Loiterous'", ",", "'oel'", ")", ",", "]", "for", "tagname", ",", "name", ",", "tl_type", "in", "tagmap", ":", "if", "tagname", "in", "item", "[", "'tags'", "]", ":", "return", "buildReleaseMessageWithType", "(", "item", ",", "name", ",", "vol", ",", "chp", ",", "frag", "=", "frag", ",", "postfix", "=", "postfix", ",", "tl_type", "=", "tl_type", ")", "return", "False" ]
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractCcKhatUs.py#L2-L21
wrobstory/vincent
c5a06e50179015fbb788a7a42e4570ff4467a9e9
vincent/marks.py
python
Mark.scales
(value)
list or KeyedList: For grouped marks, you can define a set of scales for within the mark groups
list or KeyedList: For grouped marks, you can define a set of scales for within the mark groups
[ "list", "or", "KeyedList", ":", "For", "grouped", "marks", "you", "can", "define", "a", "set", "of", "scales", "for", "within", "the", "mark", "groups" ]
def scales(value): """list or KeyedList: For grouped marks, you can define a set of scales for within the mark groups """
[ "def", "scales", "(", "value", ")", ":" ]
https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/marks.py#L132-L135
Mindwerks/worldengine
64dff8eb7824ce46b5b6cb8006bcef21822ef144
worldengine/drawing_functions.py
python
_draw_tropical_dry_forest
(pixels, x, y, w, h)
[]
def _draw_tropical_dry_forest(pixels, x, y, w, h): c = (51, 36, 3, 255) c2 = (139, 204, 58, 255) _draw_forest_pattern2(pixels, x, y, c, c2)
[ "def", "_draw_tropical_dry_forest", "(", "pixels", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "c", "=", "(", "51", ",", "36", ",", "3", ",", "255", ")", "c2", "=", "(", "139", ",", "204", ",", "58", ",", "255", ")", "_draw_forest_pattern2", "(", "pixels", ",", "x", ",", "y", ",", "c", ",", "c2", ")" ]
https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/drawing_functions.py#L244-L247
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team.py
python
RevokeDeviceSessionArg.mobile_client
(cls, val)
return cls('mobile_client', val)
Create an instance of this class set to the ``mobile_client`` tag with value ``val``. :param DeviceSessionArg val: :rtype: RevokeDeviceSessionArg
Create an instance of this class set to the ``mobile_client`` tag with value ``val``.
[ "Create", "an", "instance", "of", "this", "class", "set", "to", "the", "mobile_client", "tag", "with", "value", "val", "." ]
def mobile_client(cls, val): """ Create an instance of this class set to the ``mobile_client`` tag with value ``val``. :param DeviceSessionArg val: :rtype: RevokeDeviceSessionArg """ return cls('mobile_client', val)
[ "def", "mobile_client", "(", "cls", ",", "val", ")", ":", "return", "cls", "(", "'mobile_client'", ",", "val", ")" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team.py#L10232-L10240
wummel/linkchecker
c2ce810c3fb00b895a841a7be6b2e78c64e7b042
linkcheck/fileutil.py
python
get_mtime
(filename)
Return modification time of filename or zero on errors.
Return modification time of filename or zero on errors.
[ "Return", "modification", "time", "of", "filename", "or", "zero", "on", "errors", "." ]
def get_mtime (filename): """Return modification time of filename or zero on errors.""" try: return os.path.getmtime(filename) except os.error: return 0
[ "def", "get_mtime", "(", "filename", ")", ":", "try", ":", "return", "os", ".", "path", ".", "getmtime", "(", "filename", ")", "except", "os", ".", "error", ":", "return", "0" ]
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/fileutil.py#L141-L146
UlionTse/translators
af661ebb7b797e0e9493f1a1c8d30a1ea2edef90
translators/apis.py
python
Alibaba.alibaba_api
(self, query_text:str, from_language:str='auto', to_language:str='en', **kwargs)
return data if is_detail_result else data['listTargetText'][0]
https://translate.alibaba.com :param query_text: str, must. :param from_language: str, default 'auto'. :param to_language: str, default 'en'. :param **kwargs: :param professional_field: str, default 'message', choose from ("general","message","offer") :param if_ignore_limit_of_length: boolean, default False. :param is_detail_result: boolean, default False. :param timeout: float, default None. :param proxies: dict, default None. :param sleep_seconds: float, default `random.random()`. :return: str or dict
https://translate.alibaba.com :param query_text: str, must. :param from_language: str, default 'auto'. :param to_language: str, default 'en'. :param **kwargs: :param professional_field: str, default 'message', choose from ("general","message","offer") :param if_ignore_limit_of_length: boolean, default False. :param is_detail_result: boolean, default False. :param timeout: float, default None. :param proxies: dict, default None. :param sleep_seconds: float, default `random.random()`. :return: str or dict
[ "https", ":", "//", "translate", ".", "alibaba", ".", "com", ":", "param", "query_text", ":", "str", "must", ".", ":", "param", "from_language", ":", "str", "default", "auto", ".", ":", "param", "to_language", ":", "str", "default", "en", ".", ":", "param", "**", "kwargs", ":", ":", "param", "professional_field", ":", "str", "default", "message", "choose", "from", "(", "general", "message", "offer", ")", ":", "param", "if_ignore_limit_of_length", ":", "boolean", "default", "False", ".", ":", "param", "is_detail_result", ":", "boolean", "default", "False", ".", ":", "param", "timeout", ":", "float", "default", "None", ".", ":", "param", "proxies", ":", "dict", "default", "None", ".", ":", "param", "sleep_seconds", ":", "float", "default", "random", ".", "random", "()", ".", ":", "return", ":", "str", "or", "dict" ]
def alibaba_api(self, query_text:str, from_language:str='auto', to_language:str='en', **kwargs) -> Union[str,dict]: """ https://translate.alibaba.com :param query_text: str, must. :param from_language: str, default 'auto'. :param to_language: str, default 'en'. :param **kwargs: :param professional_field: str, default 'message', choose from ("general","message","offer") :param if_ignore_limit_of_length: boolean, default False. :param is_detail_result: boolean, default False. :param timeout: float, default None. :param proxies: dict, default None. :param sleep_seconds: float, default `random.random()`. :return: str or dict """ use_domain = kwargs.get('professional_field', 'message') assert use_domain in ("general", "message", "offer") is_detail_result = kwargs.get('is_detail_result', False) timeout = kwargs.get('timeout', None) proxies = kwargs.get('proxies', None) sleep_seconds = kwargs.get('sleep_seconds', random.random()) if_ignore_limit_of_length = kwargs.get('if_ignore_limit_of_length', False) query_text = self.check_query_text(query_text, if_ignore_limit_of_length) with requests.Session() as ss: host_response = ss.get(self.host_url, headers=self.host_headers, timeout=timeout, proxies=proxies) dmtrack_pageid = self.get_dmtrack_pageid(host_response) if not self.language_map: self.language_map = self.get_language_map(ss, use_domain, dmtrack_pageid, timeout, proxies) from_language, to_language = self.check_language(from_language, to_language, self.language_map, output_zh=self.output_zh) form_data = { "srcLanguage": from_language, "tgtLanguage": to_language, "srcText": query_text, "viewType": "", "source": "", "bizType": use_domain, } params = {"dmtrack_pageid":dmtrack_pageid} r = ss.post(self.api_url, headers=self.api_headers, params=params, data=form_data, timeout=timeout, proxies=proxies) r.raise_for_status() data = r.json() time.sleep(sleep_seconds) self.query_count += 1 return data if is_detail_result else data['listTargetText'][0]
[ "def", "alibaba_api", "(", "self", ",", "query_text", ":", "str", ",", "from_language", ":", "str", "=", "'auto'", ",", "to_language", ":", "str", "=", "'en'", ",", "*", "*", "kwargs", ")", "->", "Union", "[", "str", ",", "dict", "]", ":", "use_domain", "=", "kwargs", ".", "get", "(", "'professional_field'", ",", "'message'", ")", "assert", "use_domain", "in", "(", "\"general\"", ",", "\"message\"", ",", "\"offer\"", ")", "is_detail_result", "=", "kwargs", ".", "get", "(", "'is_detail_result'", ",", "False", ")", "timeout", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "None", ")", "proxies", "=", "kwargs", ".", "get", "(", "'proxies'", ",", "None", ")", "sleep_seconds", "=", "kwargs", ".", "get", "(", "'sleep_seconds'", ",", "random", ".", "random", "(", ")", ")", "if_ignore_limit_of_length", "=", "kwargs", ".", "get", "(", "'if_ignore_limit_of_length'", ",", "False", ")", "query_text", "=", "self", ".", "check_query_text", "(", "query_text", ",", "if_ignore_limit_of_length", ")", "with", "requests", ".", "Session", "(", ")", "as", "ss", ":", "host_response", "=", "ss", ".", "get", "(", "self", ".", "host_url", ",", "headers", "=", "self", ".", "host_headers", ",", "timeout", "=", "timeout", ",", "proxies", "=", "proxies", ")", "dmtrack_pageid", "=", "self", ".", "get_dmtrack_pageid", "(", "host_response", ")", "if", "not", "self", ".", "language_map", ":", "self", ".", "language_map", "=", "self", ".", "get_language_map", "(", "ss", ",", "use_domain", ",", "dmtrack_pageid", ",", "timeout", ",", "proxies", ")", "from_language", ",", "to_language", "=", "self", ".", "check_language", "(", "from_language", ",", "to_language", ",", "self", ".", "language_map", ",", "output_zh", "=", "self", ".", "output_zh", ")", "form_data", "=", "{", "\"srcLanguage\"", ":", "from_language", ",", "\"tgtLanguage\"", ":", "to_language", ",", "\"srcText\"", ":", "query_text", ",", "\"viewType\"", ":", "\"\"", ",", "\"source\"", ":", "\"\"", ",", "\"bizType\"", ":", "use_domain", ",", "}", "params", "=", "{", "\"dmtrack_pageid\"", ":", "dmtrack_pageid", "}", "r", "=", "ss", ".", "post", "(", "self", ".", "api_url", ",", "headers", "=", "self", ".", "api_headers", ",", "params", "=", "params", ",", "data", "=", "form_data", ",", "timeout", "=", "timeout", ",", "proxies", "=", "proxies", ")", "r", ".", "raise_for_status", "(", ")", "data", "=", "r", ".", "json", "(", ")", "time", ".", "sleep", "(", "sleep_seconds", ")", "self", ".", "query_count", "+=", "1", "return", "data", "if", "is_detail_result", "else", "data", "[", "'listTargetText'", "]", "[", "0", "]" ]
https://github.com/UlionTse/translators/blob/af661ebb7b797e0e9493f1a1c8d30a1ea2edef90/translators/apis.py#L756-L800
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/poplib.py
python
POP3.uidl
(self, which=None)
return self._longcmd('UIDL')
Return message digest (unique id) list. If 'which', result contains unique id for that message in the form 'response mesgnum uid', otherwise result is the list ['response', ['mesgnum uid', ...], octets]
Return message digest (unique id) list.
[ "Return", "message", "digest", "(", "unique", "id", ")", "list", "." ]
def uidl(self, which=None): """Return message digest (unique id) list. If 'which', result contains unique id for that message in the form 'response mesgnum uid', otherwise result is the list ['response', ['mesgnum uid', ...], octets] """ if which is not None: return self._shortcmd('UIDL %s' % which) return self._longcmd('UIDL')
[ "def", "uidl", "(", "self", ",", "which", "=", "None", ")", ":", "if", "which", "is", "not", "None", ":", "return", "self", ".", "_shortcmd", "(", "'UIDL %s'", "%", "which", ")", "return", "self", ".", "_longcmd", "(", "'UIDL'", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/poplib.py#L316-L325
PaddlePaddle/PaddleSpeech
26524031d242876b7fdb71582b0b3a7ea45c7d9d
third_party/python_kaldi_features/python_speech_features/sigproc.py
python
powspec
(frames, NFFT)
return numpy.square(magspec(frames, NFFT))
Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :returns: If frames is an NxD matrix, output will be Nx(NFFT/2+1). Each row will be the power spectrum of the corresponding frame.
Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1).
[ "Compute", "the", "power", "spectrum", "of", "each", "frame", "in", "frames", ".", "If", "frames", "is", "an", "NxD", "matrix", "output", "will", "be", "Nx", "(", "NFFT", "/", "2", "+", "1", ")", "." ]
def powspec(frames, NFFT): """Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :returns: If frames is an NxD matrix, output will be Nx(NFFT/2+1). Each row will be the power spectrum of the corresponding frame. """ return numpy.square(magspec(frames, NFFT))
[ "def", "powspec", "(", "frames", ",", "NFFT", ")", ":", "return", "numpy", ".", "square", "(", "magspec", "(", "frames", ",", "NFFT", ")", ")" ]
https://github.com/PaddlePaddle/PaddleSpeech/blob/26524031d242876b7fdb71582b0b3a7ea45c7d9d/third_party/python_kaldi_features/python_speech_features/sigproc.py#L117-L124
onaio/onadata
89ad16744e8f247fb748219476f6ac295869a95f
onadata/libs/utils/openid_connect_tools.py
python
OpenIDHandler.end_openid_provider_session
(self)
return response
Clears the SSO cookie set at authentication and redirects the User to the end_session endpoint provided by the provider configuration
Clears the SSO cookie set at authentication and redirects the User to the end_session endpoint provided by the provider configuration
[ "Clears", "the", "SSO", "cookie", "set", "at", "authentication", "and", "redirects", "the", "User", "to", "the", "end_session", "endpoint", "provided", "by", "the", "provider", "configuration" ]
def end_openid_provider_session(self): """ Clears the SSO cookie set at authentication and redirects the User to the end_session endpoint provided by the provider configuration """ end_session_endpoint = self.provider_configuration.get( 'end_session_endpoint') target_url_after_logout = self.provider_configuration.get( 'target_url_after_logout') response = HttpResponseRedirect( end_session_endpoint + '?post_logout_redirect_uri=' + target_url_after_logout) response.delete_cookie('SSO') return response
[ "def", "end_openid_provider_session", "(", "self", ")", ":", "end_session_endpoint", "=", "self", ".", "provider_configuration", ".", "get", "(", "'end_session_endpoint'", ")", "target_url_after_logout", "=", "self", ".", "provider_configuration", ".", "get", "(", "'target_url_after_logout'", ")", "response", "=", "HttpResponseRedirect", "(", "end_session_endpoint", "+", "'?post_logout_redirect_uri='", "+", "target_url_after_logout", ")", "response", ".", "delete_cookie", "(", "'SSO'", ")", "return", "response" ]
https://github.com/onaio/onadata/blob/89ad16744e8f247fb748219476f6ac295869a95f/onadata/libs/utils/openid_connect_tools.py#L196-L211
jparkhill/TensorMol
d52104dc7ee46eec8301d332a95d672270ac0bd1
TensorMol/TFNetworks/TFMolInstanceDirect.py
python
MolInstance_DirectBP_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout_Conv.energy_inference
(self, inp, indexs, cc_energy, xyzs, Zs, eles, c6, R_vdw, Reep, EE_cuton, EE_cutoff, keep_prob)
return total_energy_with_vdw, bp_energy, vdw_energy, energy_vars, output
Builds a Behler-Parinello graph Args: inp: a list of (num_of atom type X flattened input shape) matrix of input cases. index: a list of (num_of atom type X batchsize) array which linearly combines the elements Returns: The BP graph output
Builds a Behler-Parinello graph
[ "Builds", "a", "Behler", "-", "Parinello", "graph" ]
def energy_inference(self, inp, indexs, cc_energy, xyzs, Zs, eles, c6, R_vdw, Reep, EE_cuton, EE_cutoff, keep_prob): """ Builds a Behler-Parinello graph Args: inp: a list of (num_of atom type X flattened input shape) matrix of input cases. index: a list of (num_of atom type X batchsize) array which linearly combines the elements Returns: The BP graph output """ # convert the index matrix from bool to float xyzsInBohr = tf.multiply(xyzs,BOHRPERA) Ebranches=[] output = tf.zeros([self.batch_size, self.MaxNAtoms], dtype=self.tf_prec) atom_outputs = [] with tf.name_scope("EnergyNet"): for e in range(len(self.eles)): Ebranches.append([]) inputs = inp[e] shp_in = tf.shape(inputs) index = tf.cast(indexs[e], tf.int64) for i in range(len(self.filters)): if i == 0: with tf.name_scope(str(self.eles[e])+'_conv_hidden1_energy'): conv = tf.layers.conv2d(tf.reshape(tf.cast(inputs, dtype=tf.float32),[-1, self.inshape, 1, 1]), filters=self.filters[i], kernel_size=self.kernel_size[i], strides=self.strides[i], padding="valid", activation=tf.nn.relu) Ebranches[-1].append(conv) else: with tf.name_scope(str(self.eles[e])+'_conv_hidden'+str(i+1)+"_energy"): conv = tf.layers.conv2d(Ebranches[-1][-1], filters=self.filters[i], kernel_size=self.kernel_size[i], strides=self.strides[i], padding="valid", activation=tf.nn.relu) Ebranches[-1].append(conv) for i in range(len(self.HiddenLayers)): if i == 0: with tf.name_scope(str(self.eles[e])+'_hidden1_energy'): Ebranches[-1][-1] = tf.reshape(tf.cast(Ebranches[-1][-1], dtype=tf.float64), [shp_in[0], -1]) weights = self._variable_with_weight_decay(var_name='weights', var_shape=[512 , self.HiddenLayers[i]], var_stddev=1.0/(10+math.sqrt(float(512.0))), var_wd=0.001) biases = tf.Variable(tf.zeros([self.HiddenLayers[i]], dtype=self.tf_prec), name='biases') Ebranches[-1].append(self.activation_function(tf.matmul(Ebranches[-1][-1], weights) + biases)) else: with tf.name_scope(str(self.eles[e])+'_hidden'+str(i+1)+"_energy"): weights = self._variable_with_weight_decay(var_name='weights', var_shape=[self.HiddenLayers[i-1], self.HiddenLayers[i]], var_stddev=1.0/(10+math.sqrt(float(self.HiddenLayers[i-1]))), var_wd=0.001) biases = tf.Variable(tf.zeros([self.HiddenLayers[i]], dtype=self.tf_prec), name='biases') Ebranches[-1].append(self.activation_function(tf.matmul(Ebranches[-1][-1], weights) + biases)) with tf.name_scope(str(self.eles[e])+'_regression_linear'): shp = tf.shape(inputs) weights = self._variable_with_weight_decay(var_name='weights', var_shape=[self.HiddenLayers[-1], 1], var_stddev=1.0/(10+math.sqrt(float(self.HiddenLayers[-1]))), var_wd=None) biases = tf.Variable(tf.zeros([1], dtype=self.tf_prec), name='biases') Ebranches[-1].append(tf.matmul(tf.nn.dropout(Ebranches[-1][-1], keep_prob), weights) + biases) shp_out = tf.shape(Ebranches[-1][-1]) cut = tf.slice(Ebranches[-1][-1],[0,0],[shp_out[0],1]) rshp = tf.reshape(cut,[1,shp_out[0]]) atom_outputs.append(rshp) rshpflat = tf.reshape(cut,[shp_out[0]]) atom_indice = tf.slice(index, [0,1], [shp_out[0],1]) ToAdd = tf.reshape(tf.scatter_nd(atom_indice, rshpflat, [self.batch_size*self.MaxNAtoms]),[self.batch_size, self.MaxNAtoms]) output = tf.add(output, ToAdd) tf.verify_tensor_all_finite(output,"Nan in output!!!") bp_energy = tf.reshape(tf.reduce_sum(output, axis=1), [self.batch_size]) total_energy = tf.add(bp_energy, cc_energy) vdw_energy = TFVdwPolyLR(xyzsInBohr, Zs, eles, c6, R_vdw, EE_cuton*BOHRPERA, Reep) total_energy_with_vdw = tf.add(total_energy, vdw_energy) energy_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="EnergyNet") return total_energy_with_vdw, bp_energy, vdw_energy, energy_vars, output
[ "def", "energy_inference", "(", "self", ",", "inp", ",", "indexs", ",", "cc_energy", ",", "xyzs", ",", "Zs", ",", "eles", ",", "c6", ",", "R_vdw", ",", "Reep", ",", "EE_cuton", ",", "EE_cutoff", ",", "keep_prob", ")", ":", "# convert the index matrix from bool to float", "xyzsInBohr", "=", "tf", ".", "multiply", "(", "xyzs", ",", "BOHRPERA", ")", "Ebranches", "=", "[", "]", "output", "=", "tf", ".", "zeros", "(", "[", "self", ".", "batch_size", ",", "self", ".", "MaxNAtoms", "]", ",", "dtype", "=", "self", ".", "tf_prec", ")", "atom_outputs", "=", "[", "]", "with", "tf", ".", "name_scope", "(", "\"EnergyNet\"", ")", ":", "for", "e", "in", "range", "(", "len", "(", "self", ".", "eles", ")", ")", ":", "Ebranches", ".", "append", "(", "[", "]", ")", "inputs", "=", "inp", "[", "e", "]", "shp_in", "=", "tf", ".", "shape", "(", "inputs", ")", "index", "=", "tf", ".", "cast", "(", "indexs", "[", "e", "]", ",", "tf", ".", "int64", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "filters", ")", ")", ":", "if", "i", "==", "0", ":", "with", "tf", ".", "name_scope", "(", "str", "(", "self", ".", "eles", "[", "e", "]", ")", "+", "'_conv_hidden1_energy'", ")", ":", "conv", "=", "tf", ".", "layers", ".", "conv2d", "(", "tf", ".", "reshape", "(", "tf", ".", "cast", "(", "inputs", ",", "dtype", "=", "tf", ".", "float32", ")", ",", "[", "-", "1", ",", "self", ".", "inshape", ",", "1", ",", "1", "]", ")", ",", "filters", "=", "self", ".", "filters", "[", "i", "]", ",", "kernel_size", "=", "self", ".", "kernel_size", "[", "i", "]", ",", "strides", "=", "self", ".", "strides", "[", "i", "]", ",", "padding", "=", "\"valid\"", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ")", "Ebranches", "[", "-", "1", "]", ".", "append", "(", "conv", ")", "else", ":", "with", "tf", ".", "name_scope", "(", "str", "(", "self", ".", "eles", "[", "e", "]", ")", "+", "'_conv_hidden'", "+", "str", "(", "i", "+", "1", ")", "+", "\"_energy\"", ")", ":", "conv", "=", "tf", ".", "layers", ".", "conv2d", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ",", "filters", "=", "self", ".", "filters", "[", "i", "]", ",", "kernel_size", "=", "self", ".", "kernel_size", "[", "i", "]", ",", "strides", "=", "self", ".", "strides", "[", "i", "]", ",", "padding", "=", "\"valid\"", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ")", "Ebranches", "[", "-", "1", "]", ".", "append", "(", "conv", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "HiddenLayers", ")", ")", ":", "if", "i", "==", "0", ":", "with", "tf", ".", "name_scope", "(", "str", "(", "self", ".", "eles", "[", "e", "]", ")", "+", "'_hidden1_energy'", ")", ":", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", "=", "tf", ".", "reshape", "(", "tf", ".", "cast", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ",", "dtype", "=", "tf", ".", "float64", ")", ",", "[", "shp_in", "[", "0", "]", ",", "-", "1", "]", ")", "weights", "=", "self", ".", "_variable_with_weight_decay", "(", "var_name", "=", "'weights'", ",", "var_shape", "=", "[", "512", ",", "self", ".", "HiddenLayers", "[", "i", "]", "]", ",", "var_stddev", "=", "1.0", "/", "(", "10", "+", "math", ".", "sqrt", "(", "float", "(", "512.0", ")", ")", ")", ",", "var_wd", "=", "0.001", ")", "biases", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "self", ".", "HiddenLayers", "[", "i", "]", "]", ",", "dtype", "=", "self", ".", "tf_prec", ")", ",", "name", "=", "'biases'", ")", "Ebranches", "[", "-", "1", "]", ".", "append", "(", "self", ".", "activation_function", "(", "tf", ".", "matmul", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ",", "weights", ")", "+", "biases", ")", ")", "else", ":", "with", "tf", ".", "name_scope", "(", "str", "(", "self", ".", "eles", "[", "e", "]", ")", "+", "'_hidden'", "+", "str", "(", "i", "+", "1", ")", "+", "\"_energy\"", ")", ":", "weights", "=", "self", ".", "_variable_with_weight_decay", "(", "var_name", "=", "'weights'", ",", "var_shape", "=", "[", "self", ".", "HiddenLayers", "[", "i", "-", "1", "]", ",", "self", ".", "HiddenLayers", "[", "i", "]", "]", ",", "var_stddev", "=", "1.0", "/", "(", "10", "+", "math", ".", "sqrt", "(", "float", "(", "self", ".", "HiddenLayers", "[", "i", "-", "1", "]", ")", ")", ")", ",", "var_wd", "=", "0.001", ")", "biases", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "self", ".", "HiddenLayers", "[", "i", "]", "]", ",", "dtype", "=", "self", ".", "tf_prec", ")", ",", "name", "=", "'biases'", ")", "Ebranches", "[", "-", "1", "]", ".", "append", "(", "self", ".", "activation_function", "(", "tf", ".", "matmul", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ",", "weights", ")", "+", "biases", ")", ")", "with", "tf", ".", "name_scope", "(", "str", "(", "self", ".", "eles", "[", "e", "]", ")", "+", "'_regression_linear'", ")", ":", "shp", "=", "tf", ".", "shape", "(", "inputs", ")", "weights", "=", "self", ".", "_variable_with_weight_decay", "(", "var_name", "=", "'weights'", ",", "var_shape", "=", "[", "self", ".", "HiddenLayers", "[", "-", "1", "]", ",", "1", "]", ",", "var_stddev", "=", "1.0", "/", "(", "10", "+", "math", ".", "sqrt", "(", "float", "(", "self", ".", "HiddenLayers", "[", "-", "1", "]", ")", ")", ")", ",", "var_wd", "=", "None", ")", "biases", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "1", "]", ",", "dtype", "=", "self", ".", "tf_prec", ")", ",", "name", "=", "'biases'", ")", "Ebranches", "[", "-", "1", "]", ".", "append", "(", "tf", ".", "matmul", "(", "tf", ".", "nn", ".", "dropout", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ",", "keep_prob", ")", ",", "weights", ")", "+", "biases", ")", "shp_out", "=", "tf", ".", "shape", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ")", "cut", "=", "tf", ".", "slice", "(", "Ebranches", "[", "-", "1", "]", "[", "-", "1", "]", ",", "[", "0", ",", "0", "]", ",", "[", "shp_out", "[", "0", "]", ",", "1", "]", ")", "rshp", "=", "tf", ".", "reshape", "(", "cut", ",", "[", "1", ",", "shp_out", "[", "0", "]", "]", ")", "atom_outputs", ".", "append", "(", "rshp", ")", "rshpflat", "=", "tf", ".", "reshape", "(", "cut", ",", "[", "shp_out", "[", "0", "]", "]", ")", "atom_indice", "=", "tf", ".", "slice", "(", "index", ",", "[", "0", ",", "1", "]", ",", "[", "shp_out", "[", "0", "]", ",", "1", "]", ")", "ToAdd", "=", "tf", ".", "reshape", "(", "tf", ".", "scatter_nd", "(", "atom_indice", ",", "rshpflat", ",", "[", "self", ".", "batch_size", "*", "self", ".", "MaxNAtoms", "]", ")", ",", "[", "self", ".", "batch_size", ",", "self", ".", "MaxNAtoms", "]", ")", "output", "=", "tf", ".", "add", "(", "output", ",", "ToAdd", ")", "tf", ".", "verify_tensor_all_finite", "(", "output", ",", "\"Nan in output!!!\"", ")", "bp_energy", "=", "tf", ".", "reshape", "(", "tf", ".", "reduce_sum", "(", "output", ",", "axis", "=", "1", ")", ",", "[", "self", ".", "batch_size", "]", ")", "total_energy", "=", "tf", ".", "add", "(", "bp_energy", ",", "cc_energy", ")", "vdw_energy", "=", "TFVdwPolyLR", "(", "xyzsInBohr", ",", "Zs", ",", "eles", ",", "c6", ",", "R_vdw", ",", "EE_cuton", "*", "BOHRPERA", ",", "Reep", ")", "total_energy_with_vdw", "=", "tf", ".", "add", "(", "total_energy", ",", "vdw_energy", ")", "energy_vars", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "scope", "=", "\"EnergyNet\"", ")", "return", "total_energy_with_vdw", ",", "bp_energy", ",", "vdw_energy", ",", "energy_vars", ",", "output" ]
https://github.com/jparkhill/TensorMol/blob/d52104dc7ee46eec8301d332a95d672270ac0bd1/TensorMol/TFNetworks/TFMolInstanceDirect.py#L6585-L6646
pytoolz/toolz
294e981edad035a7ac6f0e2b48f1738368fa4b34
toolz/_signatures.py
python
_is_partial_args
(func, args, kwargs)
return any(check_partial(sig, args, kwargs) for sig in sigs)
Like ``is_partial_args`` for builtins in our ``signatures`` registry
Like ``is_partial_args`` for builtins in our ``signatures`` registry
[ "Like", "is_partial_args", "for", "builtins", "in", "our", "signatures", "registry" ]
def _is_partial_args(func, args, kwargs): """ Like ``is_partial_args`` for builtins in our ``signatures`` registry""" if func not in signatures: return None sigs = signatures[func] return any(check_partial(sig, args, kwargs) for sig in sigs)
[ "def", "_is_partial_args", "(", "func", ",", "args", ",", "kwargs", ")", ":", "if", "func", "not", "in", "signatures", ":", "return", "None", "sigs", "=", "signatures", "[", "func", "]", "return", "any", "(", "check_partial", "(", "sig", ",", "args", ",", "kwargs", ")", "for", "sig", "in", "sigs", ")" ]
https://github.com/pytoolz/toolz/blob/294e981edad035a7ac6f0e2b48f1738368fa4b34/toolz/_signatures.py#L709-L714
conda/conda
09cb6bdde68e551852c3844fd2b59c8ba4cafce2
conda/common/configuration.py
python
PrimitiveParameter.__init__
(self, default, element_type=None, validation=None)
Args: default (primitive value): default value if the Parameter is not found. element_type (type or Tuple[type]): Type-validation of parameter's value. If None, type(default) is used.
Args: default (primitive value): default value if the Parameter is not found. element_type (type or Tuple[type]): Type-validation of parameter's value. If None, type(default) is used.
[ "Args", ":", "default", "(", "primitive", "value", ")", ":", "default", "value", "if", "the", "Parameter", "is", "not", "found", ".", "element_type", "(", "type", "or", "Tuple", "[", "type", "]", ")", ":", "Type", "-", "validation", "of", "parameter", "s", "value", ".", "If", "None", "type", "(", "default", ")", "is", "used", "." ]
def __init__(self, default, element_type=None, validation=None): """ Args: default (primitive value): default value if the Parameter is not found. element_type (type or Tuple[type]): Type-validation of parameter's value. If None, type(default) is used. """ self._type = type(default) if element_type is None else element_type self._element_type = self._type super(PrimitiveParameter, self).__init__(default, validation)
[ "def", "__init__", "(", "self", ",", "default", ",", "element_type", "=", "None", ",", "validation", "=", "None", ")", ":", "self", ".", "_type", "=", "type", "(", "default", ")", "if", "element_type", "is", "None", "else", "element_type", "self", ".", "_element_type", "=", "self", ".", "_type", "super", "(", "PrimitiveParameter", ",", "self", ")", ".", "__init__", "(", "default", ",", "validation", ")" ]
https://github.com/conda/conda/blob/09cb6bdde68e551852c3844fd2b59c8ba4cafce2/conda/common/configuration.py#L961-L970
seopbo/nlp_classification
21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf
Efficient_Character-level_Document_Classification_by_Combining_Convolution_and_Recurrent_Layers/utils.py
python
Config.update
(self, json_path_or_dict)
Updating Config instance Args: json_path_or_dict (Union[str, dict]): filepath of config or dictionary which has attributes
Updating Config instance
[ "Updating", "Config", "instance" ]
def update(self, json_path_or_dict) -> None: """Updating Config instance Args: json_path_or_dict (Union[str, dict]): filepath of config or dictionary which has attributes """ if isinstance(json_path_or_dict, dict): self.__dict__.update(json_path_or_dict) else: with open(json_path_or_dict, mode="r") as io: params = json.loads(io.read()) self.__dict__.update(params)
[ "def", "update", "(", "self", ",", "json_path_or_dict", ")", "->", "None", ":", "if", "isinstance", "(", "json_path_or_dict", ",", "dict", ")", ":", "self", ".", "__dict__", ".", "update", "(", "json_path_or_dict", ")", "else", ":", "with", "open", "(", "json_path_or_dict", ",", "mode", "=", "\"r\"", ")", "as", "io", ":", "params", "=", "json", ".", "loads", "(", "io", ".", "read", "(", ")", ")", "self", ".", "__dict__", ".", "update", "(", "params", ")" ]
https://github.com/seopbo/nlp_classification/blob/21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf/Efficient_Character-level_Document_Classification_by_Combining_Convolution_and_Recurrent_Layers/utils.py#L32-L43
svenkreiss/pysparkling
f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78
pysparkling/sql/functions.py
python
month
(e)
return col(Month(ensure_column(e)))
:rtype: Column
:rtype: Column
[ ":", "rtype", ":", "Column" ]
def month(e): """ :rtype: Column """ return col(Month(ensure_column(e)))
[ "def", "month", "(", "e", ")", ":", "return", "col", "(", "Month", "(", "ensure_column", "(", "e", ")", ")", ")" ]
https://github.com/svenkreiss/pysparkling/blob/f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78/pysparkling/sql/functions.py#L1719-L1723
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/classify.py
python
Bo1Model.score
(self, weight_in_top, weight_in_collection, top_total)
return weight_in_top * log((1.0 + f) / f, 2) + log(1.0 + f, 2)
[]
def score(self, weight_in_top, weight_in_collection, top_total): f = weight_in_collection / self.N return weight_in_top * log((1.0 + f) / f, 2) + log(1.0 + f, 2)
[ "def", "score", "(", "self", ",", "weight_in_top", ",", "weight_in_collection", ",", "top_total", ")", ":", "f", "=", "weight_in_collection", "/", "self", ".", "N", "return", "weight_in_top", "*", "log", "(", "(", "1.0", "+", "f", ")", "/", "f", ",", "2", ")", "+", "log", "(", "1.0", "+", "f", ",", "2", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/classify.py#L64-L66
pycontribs/pyrax
a0c022981f76a4cba96a22ecc19bb52843ac4fbe
pyrax/client.py
python
BaseClient.get
(self, item)
return self._manager.get(item)
Gets a specific resource.
Gets a specific resource.
[ "Gets", "a", "specific", "resource", "." ]
def get(self, item): """Gets a specific resource.""" return self._manager.get(item)
[ "def", "get", "(", "self", ",", "item", ")", ":", "return", "self", ".", "_manager", ".", "get", "(", "item", ")" ]
https://github.com/pycontribs/pyrax/blob/a0c022981f76a4cba96a22ecc19bb52843ac4fbe/pyrax/client.py#L94-L96
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/dev/repos/policy.py
python
create_policy_approver_count
(repository_id, branch, blocking, enabled, minimum_approver_count, creator_vote_counts, allow_downvotes, reset_on_source_push, branch_match_type='exact', organization=None, project=None, detect=None)
return policy_client.create_policy_configuration(configuration=configuration, project=project)
Create approver count policy
Create approver count policy
[ "Create", "approver", "count", "policy" ]
def create_policy_approver_count(repository_id, branch, blocking, enabled, minimum_approver_count, creator_vote_counts, allow_downvotes, reset_on_source_push, branch_match_type='exact', organization=None, project=None, detect=None): """Create approver count policy """ organization, project = resolve_instance_and_project( detect=detect, organization=organization, project=project) policy_client = get_policy_client(organization) param_name_array = ['minimumApproverCount', 'creatorVoteCounts', 'allowDownvotes', 'resetOnSourcePush'] param_value_array = [minimum_approver_count, creator_vote_counts, allow_downvotes, reset_on_source_push] configuration = create_configuration_object(repository_id, branch, blocking, enabled, 'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd', param_name_array, param_value_array, branch_match_type) return policy_client.create_policy_configuration(configuration=configuration, project=project)
[ "def", "create_policy_approver_count", "(", "repository_id", ",", "branch", ",", "blocking", ",", "enabled", ",", "minimum_approver_count", ",", "creator_vote_counts", ",", "allow_downvotes", ",", "reset_on_source_push", ",", "branch_match_type", "=", "'exact'", ",", "organization", "=", "None", ",", "project", "=", "None", ",", "detect", "=", "None", ")", ":", "organization", ",", "project", "=", "resolve_instance_and_project", "(", "detect", "=", "detect", ",", "organization", "=", "organization", ",", "project", "=", "project", ")", "policy_client", "=", "get_policy_client", "(", "organization", ")", "param_name_array", "=", "[", "'minimumApproverCount'", ",", "'creatorVoteCounts'", ",", "'allowDownvotes'", ",", "'resetOnSourcePush'", "]", "param_value_array", "=", "[", "minimum_approver_count", ",", "creator_vote_counts", ",", "allow_downvotes", ",", "reset_on_source_push", "]", "configuration", "=", "create_configuration_object", "(", "repository_id", ",", "branch", ",", "blocking", ",", "enabled", ",", "'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd'", ",", "param_name_array", ",", "param_value_array", ",", "branch_match_type", ")", "return", "policy_client", ".", "create_policy_configuration", "(", "configuration", "=", "configuration", ",", "project", "=", "project", ")" ]
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/dev/repos/policy.py#L96-L111
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/unsupervised/owdistancemap.py
python
DistanceMapItem.__elastic_band_select
(self, area, command)
[]
def __elastic_band_select(self, area, command): if command & self.Clear and self.__dragging: item, area = self.__dragging _remove_item(item) self.__dragging = None if command & self.Select: if self.__dragging: item, _ = self.__dragging else: item = DistanceMapItem.SelectionRect(self) item.setPen(QPen(Qt.red, 0)) # intersection with existing regions intersection = [(item, selarea) for item, selarea in self.__selections if area.intersects(selarea)] fullarea = reduce( QRect.united, (selarea for _, selarea in intersection), area ) visualarea = self.__visualRectForSelection(fullarea) item.setRect(visualarea) self.__dragging = item, area if command & self.Commit and self.__dragging: item, area = self.__dragging self.__select(area, self.Select)
[ "def", "__elastic_band_select", "(", "self", ",", "area", ",", "command", ")", ":", "if", "command", "&", "self", ".", "Clear", "and", "self", ".", "__dragging", ":", "item", ",", "area", "=", "self", ".", "__dragging", "_remove_item", "(", "item", ")", "self", ".", "__dragging", "=", "None", "if", "command", "&", "self", ".", "Select", ":", "if", "self", ".", "__dragging", ":", "item", ",", "_", "=", "self", ".", "__dragging", "else", ":", "item", "=", "DistanceMapItem", ".", "SelectionRect", "(", "self", ")", "item", ".", "setPen", "(", "QPen", "(", "Qt", ".", "red", ",", "0", ")", ")", "# intersection with existing regions", "intersection", "=", "[", "(", "item", ",", "selarea", ")", "for", "item", ",", "selarea", "in", "self", ".", "__selections", "if", "area", ".", "intersects", "(", "selarea", ")", "]", "fullarea", "=", "reduce", "(", "QRect", ".", "united", ",", "(", "selarea", "for", "_", ",", "selarea", "in", "intersection", ")", ",", "area", ")", "visualarea", "=", "self", ".", "__visualRectForSelection", "(", "fullarea", ")", "item", ".", "setRect", "(", "visualarea", ")", "self", ".", "__dragging", "=", "item", ",", "area", "if", "command", "&", "self", ".", "Commit", "and", "self", ".", "__dragging", ":", "item", ",", "area", "=", "self", ".", "__dragging", "self", ".", "__select", "(", "area", ",", "self", ".", "Select", ")" ]
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/unsupervised/owdistancemap.py#L113-L141
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/__init__.py
python
get_home
()
Return the user's home directory. If the user's home directory cannot be found, return None.
Return the user's home directory.
[ "Return", "the", "user", "s", "home", "directory", "." ]
def get_home(): """ Return the user's home directory. If the user's home directory cannot be found, return None. """ try: return str(Path.home()) except Exception: return None
[ "def", "get_home", "(", ")", ":", "try", ":", "return", "str", "(", "Path", ".", "home", "(", ")", ")", "except", "Exception", ":", "return", "None" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/__init__.py#L556-L565
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/pyrevit/coreutils/__init__.py
python
format_hex_rgb
(rgb_value)
Formats rgb value as #RGB value string.
Formats rgb value as #RGB value string.
[ "Formats", "rgb", "value", "as", "#RGB", "value", "string", "." ]
def format_hex_rgb(rgb_value): """Formats rgb value as #RGB value string.""" if isinstance(rgb_value, str): if not rgb_value.startswith('#'): return '#%s' % rgb_value else: return rgb_value elif isinstance(rgb_value, int): return '#%x' % rgb_value
[ "def", "format_hex_rgb", "(", "rgb_value", ")", ":", "if", "isinstance", "(", "rgb_value", ",", "str", ")", ":", "if", "not", "rgb_value", ".", "startswith", "(", "'#'", ")", ":", "return", "'#%s'", "%", "rgb_value", "else", ":", "return", "rgb_value", "elif", "isinstance", "(", "rgb_value", ",", "int", ")", ":", "return", "'#%x'", "%", "rgb_value" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/pyrevit/coreutils/__init__.py#L1194-L1202
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/organization/v20181225/organization_client.py
python
OrganizationClient.QuitOrganization
(self, request)
退出企业组织 :param request: Request instance for QuitOrganization. :type request: :class:`tencentcloud.organization.v20181225.models.QuitOrganizationRequest` :rtype: :class:`tencentcloud.organization.v20181225.models.QuitOrganizationResponse`
退出企业组织
[ "退出企业组织" ]
def QuitOrganization(self, request): """退出企业组织 :param request: Request instance for QuitOrganization. :type request: :class:`tencentcloud.organization.v20181225.models.QuitOrganizationRequest` :rtype: :class:`tencentcloud.organization.v20181225.models.QuitOrganizationResponse` """ try: params = request._serialize() body = self.call("QuitOrganization", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.QuitOrganizationResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "QuitOrganization", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"QuitOrganization\"", ",", "params", ")", "response", "=", "json", ".", "loads", "(", "body", ")", "if", "\"Error\"", "not", "in", "response", "[", "\"Response\"", "]", ":", "model", "=", "models", ".", "QuitOrganizationResponse", "(", ")", "model", ".", "_deserialize", "(", "response", "[", "\"Response\"", "]", ")", "return", "model", "else", ":", "code", "=", "response", "[", "\"Response\"", "]", "[", "\"Error\"", "]", "[", "\"Code\"", "]", "message", "=", "response", "[", "\"Response\"", "]", "[", "\"Error\"", "]", "[", "\"Message\"", "]", "reqid", "=", "response", "[", "\"Response\"", "]", "[", "\"RequestId\"", "]", "raise", "TencentCloudSDKException", "(", "code", ",", "message", ",", "reqid", ")", "except", "Exception", "as", "e", ":", "if", "isinstance", "(", "e", ",", "TencentCloudSDKException", ")", ":", "raise", "else", ":", "raise", "TencentCloudSDKException", "(", "e", ".", "message", ",", "e", ".", "message", ")" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/organization/v20181225/organization_client.py#L477-L502
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/mhlib.py
python
MH.getcontext
(self)
return context
Return the name of the current folder.
Return the name of the current folder.
[ "Return", "the", "name", "of", "the", "current", "folder", "." ]
def getcontext(self): """Return the name of the current folder.""" context = pickline(os.path.join(self.getpath(), 'context'), 'Current-Folder') if not context: context = 'inbox' return context
[ "def", "getcontext", "(", "self", ")", ":", "context", "=", "pickline", "(", "os", ".", "path", ".", "join", "(", "self", ".", "getpath", "(", ")", ",", "'context'", ")", ",", "'Current-Folder'", ")", "if", "not", "context", ":", "context", "=", "'inbox'", "return", "context" ]
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/mhlib.py#L130-L135
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
chainer_/chainercv2/models/pspnet.py
python
pspnet_resnetd50b_cityscapes
(pretrained_backbone=False, classes=19, aux=True, **kwargs)
return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd50b_cityscapes", **kwargs)
PSPNet model on the base of ResNet(D)-50b for Cityscapes from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. Parameters: ---------- pretrained_backbone : bool, default False Whether to load the pretrained weights for feature extractor. classes : int, default 19 Number of segmentation classes. aux : bool, default True Whether to output an auxiliary result. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters.
PSPNet model on the base of ResNet(D)-50b for Cityscapes from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105.
[ "PSPNet", "model", "on", "the", "base", "of", "ResNet", "(", "D", ")", "-", "50b", "for", "Cityscapes", "from", "Pyramid", "Scene", "Parsing", "Network", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1612", ".", "01105", "." ]
def pspnet_resnetd50b_cityscapes(pretrained_backbone=False, classes=19, aux=True, **kwargs): """ PSPNet model on the base of ResNet(D)-50b for Cityscapes from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. Parameters: ---------- pretrained_backbone : bool, default False Whether to load the pretrained weights for feature extractor. classes : int, default 19 Number of segmentation classes. aux : bool, default True Whether to output an auxiliary result. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features del backbone.final_pool return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd50b_cityscapes", **kwargs)
[ "def", "pspnet_resnetd50b_cityscapes", "(", "pretrained_backbone", "=", "False", ",", "classes", "=", "19", ",", "aux", "=", "True", ",", "*", "*", "kwargs", ")", ":", "backbone", "=", "resnetd50b", "(", "pretrained", "=", "pretrained_backbone", ",", "ordinary_init", "=", "False", ",", "bends", "=", "(", "3", ",", ")", ")", ".", "features", "del", "backbone", ".", "final_pool", "return", "get_pspnet", "(", "backbone", "=", "backbone", ",", "classes", "=", "classes", ",", "aux", "=", "aux", ",", "model_name", "=", "\"pspnet_resnetd50b_cityscapes\"", ",", "*", "*", "kwargs", ")" ]
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/pspnet.py#L387-L408
locationtech-labs/geopyspark
97bcb17a56ed4b4059e2f0dbab97706562cac692
geopyspark/geotrellis/catalog.py
python
ValueReader.__init__
(self, uri, layer_name, zoom=None)
[]
def __init__(self, uri, layer_name, zoom=None): self.layer_name = layer_name self.zoom = zoom pysc = get_spark_context() ValueReaderWrapper = pysc._gateway.jvm.geopyspark.geotrellis.io.ValueReaderWrapper self.wrapper = ValueReaderWrapper(uri)
[ "def", "__init__", "(", "self", ",", "uri", ",", "layer_name", ",", "zoom", "=", "None", ")", ":", "self", ".", "layer_name", "=", "layer_name", "self", ".", "zoom", "=", "zoom", "pysc", "=", "get_spark_context", "(", ")", "ValueReaderWrapper", "=", "pysc", ".", "_gateway", ".", "jvm", ".", "geopyspark", ".", "geotrellis", ".", "io", ".", "ValueReaderWrapper", "self", ".", "wrapper", "=", "ValueReaderWrapper", "(", "uri", ")" ]
https://github.com/locationtech-labs/geopyspark/blob/97bcb17a56ed4b4059e2f0dbab97706562cac692/geopyspark/geotrellis/catalog.py#L79-L85
rpmuller/pyquante2
6e34cb4480ae7dbd8c5e44d221d8b27584890c83
pyquante2/ints/one.py
python
nuclear_attraction
(alpha1,lmn1,A,alpha2,lmn2,B,C)
return val
Full form of the nuclear attraction integral >>> isclose(nuclear_attraction(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d'),array((0,0,0),'d')),-3.141593) True
Full form of the nuclear attraction integral >>> isclose(nuclear_attraction(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d'),array((0,0,0),'d')),-3.141593) True
[ "Full", "form", "of", "the", "nuclear", "attraction", "integral", ">>>", "isclose", "(", "nuclear_attraction", "(", "1", "(", "0", "0", "0", ")", "array", "((", "0", "0", "0", ")", "d", ")", "1", "(", "0", "0", "0", ")", "array", "((", "0", "0", "0", ")", "d", ")", "array", "((", "0", "0", "0", ")", "d", "))", "-", "3", ".", "141593", ")", "True" ]
def nuclear_attraction(alpha1,lmn1,A,alpha2,lmn2,B,C): """ Full form of the nuclear attraction integral >>> isclose(nuclear_attraction(1,(0,0,0),array((0,0,0),'d'),1,(0,0,0),array((0,0,0),'d'),array((0,0,0),'d')),-3.141593) True """ l1,m1,n1 = lmn1 l2,m2,n2 = lmn2 gamma = alpha1+alpha2 P = gaussian_product_center(alpha1,A,alpha2,B) rab2 = norm2(A-B) rcp2 = norm2(C-P) dPA = P-A dPB = P-B dPC = P-C Ax = A_array(l1,l2,dPA[0],dPB[0],dPC[0],gamma) Ay = A_array(m1,m2,dPA[1],dPB[1],dPC[1],gamma) Az = A_array(n1,n2,dPA[2],dPB[2],dPC[2],gamma) total = 0. for I in range(l1+l2+1): for J in range(m1+m2+1): for K in range(n1+n2+1): total += Ax[I]*Ay[J]*Az[K]*Fgamma(I+J+K,rcp2*gamma) val= -2*pi/gamma*exp(-alpha1*alpha2*rab2/gamma)*total return val
[ "def", "nuclear_attraction", "(", "alpha1", ",", "lmn1", ",", "A", ",", "alpha2", ",", "lmn2", ",", "B", ",", "C", ")", ":", "l1", ",", "m1", ",", "n1", "=", "lmn1", "l2", ",", "m2", ",", "n2", "=", "lmn2", "gamma", "=", "alpha1", "+", "alpha2", "P", "=", "gaussian_product_center", "(", "alpha1", ",", "A", ",", "alpha2", ",", "B", ")", "rab2", "=", "norm2", "(", "A", "-", "B", ")", "rcp2", "=", "norm2", "(", "C", "-", "P", ")", "dPA", "=", "P", "-", "A", "dPB", "=", "P", "-", "B", "dPC", "=", "P", "-", "C", "Ax", "=", "A_array", "(", "l1", ",", "l2", ",", "dPA", "[", "0", "]", ",", "dPB", "[", "0", "]", ",", "dPC", "[", "0", "]", ",", "gamma", ")", "Ay", "=", "A_array", "(", "m1", ",", "m2", ",", "dPA", "[", "1", "]", ",", "dPB", "[", "1", "]", ",", "dPC", "[", "1", "]", ",", "gamma", ")", "Az", "=", "A_array", "(", "n1", ",", "n2", ",", "dPA", "[", "2", "]", ",", "dPB", "[", "2", "]", ",", "dPC", "[", "2", "]", ",", "gamma", ")", "total", "=", "0.", "for", "I", "in", "range", "(", "l1", "+", "l2", "+", "1", ")", ":", "for", "J", "in", "range", "(", "m1", "+", "m2", "+", "1", ")", ":", "for", "K", "in", "range", "(", "n1", "+", "n2", "+", "1", ")", ":", "total", "+=", "Ax", "[", "I", "]", "*", "Ay", "[", "J", "]", "*", "Az", "[", "K", "]", "*", "Fgamma", "(", "I", "+", "J", "+", "K", ",", "rcp2", "*", "gamma", ")", "val", "=", "-", "2", "*", "pi", "/", "gamma", "*", "exp", "(", "-", "alpha1", "*", "alpha2", "*", "rab2", "/", "gamma", ")", "*", "total", "return", "val" ]
https://github.com/rpmuller/pyquante2/blob/6e34cb4480ae7dbd8c5e44d221d8b27584890c83/pyquante2/ints/one.py#L172-L201
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pymongo/pool.py
python
PoolOptions.event_listeners
(self)
return self.__event_listeners
An instance of pymongo.monitoring._EventListeners.
An instance of pymongo.monitoring._EventListeners.
[ "An", "instance", "of", "pymongo", ".", "monitoring", ".", "_EventListeners", "." ]
def event_listeners(self): """An instance of pymongo.monitoring._EventListeners. """ return self.__event_listeners
[ "def", "event_listeners", "(", "self", ")", ":", "return", "self", ".", "__event_listeners" ]
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pymongo/pool.py#L442-L445
ANSSI-FR/polichombr
e2dc3874ae3d78c3b496e9656c9a6d1b88ae91e1
polichombr/views/api_sample.py
python
api_get_iat_matches
(sid)
return jsonify({'result': result})
TODO : Get IAT hashes
TODO : Get IAT hashes
[ "TODO", ":", "Get", "IAT", "hashes" ]
def api_get_iat_matches(sid): """ TODO : Get IAT hashes """ sample = api.get_elem_by_type("sample", sid) result = None return jsonify({'result': result})
[ "def", "api_get_iat_matches", "(", "sid", ")", ":", "sample", "=", "api", ".", "get_elem_by_type", "(", "\"sample\"", ",", "sid", ")", "result", "=", "None", "return", "jsonify", "(", "{", "'result'", ":", "result", "}", ")" ]
https://github.com/ANSSI-FR/polichombr/blob/e2dc3874ae3d78c3b496e9656c9a6d1b88ae91e1/polichombr/views/api_sample.py#L225-L231
kengz/SLM-Lab
667ba73349ad00c6f4b3e428dcd10eebbdab4c70
slm_lab/spec/random_baseline.py
python
gen_random_return
(env_name, seed)
return total_reward
Generate a single-episode random policy return for an environment
Generate a single-episode random policy return for an environment
[ "Generate", "a", "single", "-", "episode", "random", "policy", "return", "for", "an", "environment" ]
def gen_random_return(env_name, seed): '''Generate a single-episode random policy return for an environment''' # TODO generalize for unity too once it has a gym wrapper env = gym.make(env_name) env.seed(seed) env.reset() done = False total_reward = 0 while not done: _, reward, done, _ = env.step(env.action_space.sample()) total_reward += reward return total_reward
[ "def", "gen_random_return", "(", "env_name", ",", "seed", ")", ":", "# TODO generalize for unity too once it has a gym wrapper", "env", "=", "gym", ".", "make", "(", "env_name", ")", "env", ".", "seed", "(", "seed", ")", "env", ".", "reset", "(", ")", "done", "=", "False", "total_reward", "=", "0", "while", "not", "done", ":", "_", ",", "reward", ",", "done", ",", "_", "=", "env", ".", "step", "(", "env", ".", "action_space", ".", "sample", "(", ")", ")", "total_reward", "+=", "reward", "return", "total_reward" ]
https://github.com/kengz/SLM-Lab/blob/667ba73349ad00c6f4b3e428dcd10eebbdab4c70/slm_lab/spec/random_baseline.py#L85-L96
riffnshred/nhl-led-scoreboard
14baa7f0691ca507e4c6f7f2ec02e50ccd1ed9e1
src/nhl_api/data.py
python
get_standings_wildcard
()
[]
def get_standings_wildcard(): try: data = requests.get(STANDINGS_WILD_CARD, timeout=REQUEST_TIMEOUT) return data except requests.exceptions.RequestException as e: raise ValueError(e)
[ "def", "get_standings_wildcard", "(", ")", ":", "try", ":", "data", "=", "requests", ".", "get", "(", "STANDINGS_WILD_CARD", ",", "timeout", "=", "REQUEST_TIMEOUT", ")", "return", "data", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "ValueError", "(", "e", ")" ]
https://github.com/riffnshred/nhl-led-scoreboard/blob/14baa7f0691ca507e4c6f7f2ec02e50ccd1ed9e1/src/nhl_api/data.py#L81-L86
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/core/cli/db/upgrade.py
python
ask_question
(question, default=None)
return answer
Ask a question to the user and receive an answer. Parameters ---------- question: str The question to be asked. default: str The default value to use if the user enters nothing. Returns ------- str The answer provided by the user.
Ask a question to the user and receive an answer.
[ "Ask", "a", "question", "to", "the", "user", "and", "receive", "an", "answer", "." ]
def ask_question(question, default=None): """Ask a question to the user and receive an answer. Parameters ---------- question: str The question to be asked. default: str The default value to use if the user enters nothing. Returns ------- str The answer provided by the user. """ if default is not None: question = question + " (default: {}) ".format(default) answer = input(question) if answer.strip() == "": return default return answer
[ "def", "ask_question", "(", "question", ",", "default", "=", "None", ")", ":", "if", "default", "is", "not", "None", ":", "question", "=", "question", "+", "\" (default: {}) \"", ".", "format", "(", "default", ")", "answer", "=", "input", "(", "question", ")", "if", "answer", ".", "strip", "(", ")", "==", "\"\"", ":", "return", "default", "return", "answer" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/core/cli/db/upgrade.py#L26-L50
qhduan/just_another_seq2seq
ac9be1b1599c05e0802824afa8a351dcb9ba936e
threadedgenerator.py
python
ThreadedGenerator.__repr__
(self)
return 'ThreadedGenerator({!r})'.format(self._iterator)
[]
def __repr__(self): return 'ThreadedGenerator({!r})'.format(self._iterator)
[ "def", "__repr__", "(", "self", ")", ":", "return", "'ThreadedGenerator({!r})'", ".", "format", "(", "self", ".", "_iterator", ")" ]
https://github.com/qhduan/just_another_seq2seq/blob/ac9be1b1599c05e0802824afa8a351dcb9ba936e/threadedgenerator.py#L38-L39
HumanCompatibleAI/adversarial-policies
bba910b89149f1274bb9652a6f378b22c3c9b6c5
src/aprl/multi/score.py
python
extract_data
(path_generator, out_dir, experiment_dirs, ray_upload_dir)
Helper method to extract data from multiple_score experiments.
Helper method to extract data from multiple_score experiments.
[ "Helper", "method", "to", "extract", "data", "from", "multiple_score", "experiments", "." ]
def extract_data(path_generator, out_dir, experiment_dirs, ray_upload_dir): """Helper method to extract data from multiple_score experiments.""" for experiment, experiment_dir in experiment_dirs.items(): experiment_root = osp.join(ray_upload_dir, experiment_dir) # video_root contains one directory for each score_agent trial. # These directories have names of form score-<hash>_<id_num>_<k=v>... for dir_entry in os.scandir(experiment_root): if not dir_entry.is_dir(): continue trial_name = dir_entry.name # Each trial contains the Sacred output from score_agent. # Note Ray Tune is running with a fresh working directory per trial, so Sacred # output will always be at score/1. trial_root = osp.join(experiment_root, trial_name) sacred_config = osp.join(trial_root, "data", "sacred", "score", "1", "config.json") with open(sacred_config, "r") as f: cfg = json.load(f) def agent_key(agent): return cfg[agent + "_type"], cfg[agent + "_path"] env_name = cfg["env_name"] victim_index = VICTIM_INDEX[env_name] if victim_index == 0: victim_type, victim_path = agent_key("agent_a") opponent_type, opponent_path = agent_key("agent_b") else: victim_type, victim_path = agent_key("agent_b") opponent_type, opponent_path = agent_key("agent_a") if "multicomp" in cfg["env_name"]: env_name = env_name_to_canonical(env_name) env_name = env_name.replace("/", "-") # sanitize src_path, new_name, suffix = path_generator( trial_root=trial_root, cfg=cfg, env_sanitized=env_name, victim_index=victim_index, victim_type=victim_type, victim_path=victim_path, opponent_type=opponent_type, opponent_path=opponent_path, ) dst_path = osp.join(out_dir, f"{new_name}.{suffix}") shutil.copy(src_path, dst_path) dst_config = osp.join(out_dir, f"{new_name}_sacred.json") shutil.copy(sacred_config, dst_config)
[ "def", "extract_data", "(", "path_generator", ",", "out_dir", ",", "experiment_dirs", ",", "ray_upload_dir", ")", ":", "for", "experiment", ",", "experiment_dir", "in", "experiment_dirs", ".", "items", "(", ")", ":", "experiment_root", "=", "osp", ".", "join", "(", "ray_upload_dir", ",", "experiment_dir", ")", "# video_root contains one directory for each score_agent trial.", "# These directories have names of form score-<hash>_<id_num>_<k=v>...", "for", "dir_entry", "in", "os", ".", "scandir", "(", "experiment_root", ")", ":", "if", "not", "dir_entry", ".", "is_dir", "(", ")", ":", "continue", "trial_name", "=", "dir_entry", ".", "name", "# Each trial contains the Sacred output from score_agent.", "# Note Ray Tune is running with a fresh working directory per trial, so Sacred", "# output will always be at score/1.", "trial_root", "=", "osp", ".", "join", "(", "experiment_root", ",", "trial_name", ")", "sacred_config", "=", "osp", ".", "join", "(", "trial_root", ",", "\"data\"", ",", "\"sacred\"", ",", "\"score\"", ",", "\"1\"", ",", "\"config.json\"", ")", "with", "open", "(", "sacred_config", ",", "\"r\"", ")", "as", "f", ":", "cfg", "=", "json", ".", "load", "(", "f", ")", "def", "agent_key", "(", "agent", ")", ":", "return", "cfg", "[", "agent", "+", "\"_type\"", "]", ",", "cfg", "[", "agent", "+", "\"_path\"", "]", "env_name", "=", "cfg", "[", "\"env_name\"", "]", "victim_index", "=", "VICTIM_INDEX", "[", "env_name", "]", "if", "victim_index", "==", "0", ":", "victim_type", ",", "victim_path", "=", "agent_key", "(", "\"agent_a\"", ")", "opponent_type", ",", "opponent_path", "=", "agent_key", "(", "\"agent_b\"", ")", "else", ":", "victim_type", ",", "victim_path", "=", "agent_key", "(", "\"agent_b\"", ")", "opponent_type", ",", "opponent_path", "=", "agent_key", "(", "\"agent_a\"", ")", "if", "\"multicomp\"", "in", "cfg", "[", "\"env_name\"", "]", ":", "env_name", "=", "env_name_to_canonical", "(", "env_name", ")", "env_name", "=", "env_name", ".", "replace", "(", "\"/\"", ",", "\"-\"", ")", "# sanitize", "src_path", ",", "new_name", ",", "suffix", "=", "path_generator", "(", "trial_root", "=", "trial_root", ",", "cfg", "=", "cfg", ",", "env_sanitized", "=", "env_name", ",", "victim_index", "=", "victim_index", ",", "victim_type", "=", "victim_type", ",", "victim_path", "=", "victim_path", ",", "opponent_type", "=", "opponent_type", ",", "opponent_path", "=", "opponent_path", ",", ")", "dst_path", "=", "osp", ".", "join", "(", "out_dir", ",", "f\"{new_name}.{suffix}\"", ")", "shutil", ".", "copy", "(", "src_path", ",", "dst_path", ")", "dst_config", "=", "osp", ".", "join", "(", "out_dir", ",", "f\"{new_name}_sacred.json\"", ")", "shutil", ".", "copy", "(", "sacred_config", ",", "dst_config", ")" ]
https://github.com/HumanCompatibleAI/adversarial-policies/blob/bba910b89149f1274bb9652a6f378b22c3c9b6c5/src/aprl/multi/score.py#L129-L178
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/core/kernel/base.py
python
ICategorizedObject.name
(self)
return self.getname(fully_qualified=True)
The object's fully qualified name. Alias for `obj.getname(fully_qualified=True)`.
The object's fully qualified name. Alias for `obj.getname(fully_qualified=True)`.
[ "The", "object", "s", "fully", "qualified", "name", ".", "Alias", "for", "obj", ".", "getname", "(", "fully_qualified", "=", "True", ")", "." ]
def name(self): """The object's fully qualified name. Alias for `obj.getname(fully_qualified=True)`.""" return self.getname(fully_qualified=True)
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "getname", "(", "fully_qualified", "=", "True", ")" ]
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/kernel/base.py#L184-L187
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/relay/op/nn/_nn.py
python
convert_global_avg_pool2d
(attrs, inputs, tinfos, desired_layouts)
return relay.nn.global_avg_pool2d(*inputs, **new_attrs)
Convert Layout pass registration for global_avg_pool2d op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current pooling inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized tinfos : list of types List of input and output types desired_layouts : list of one layout string layout string defining our desired layout for input and output. Returns ------- result : tvm.relay.Expr The transformed expr
Convert Layout pass registration for global_avg_pool2d op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current pooling inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized tinfos : list of types List of input and output types desired_layouts : list of one layout string layout string defining our desired layout for input and output. Returns ------- result : tvm.relay.Expr The transformed expr
[ "Convert", "Layout", "pass", "registration", "for", "global_avg_pool2d", "op", ".", "Parameters", "----------", "attrs", ":", "tvm", ".", "ir", ".", "Attrs", "Attributes", "of", "current", "pooling", "inputs", ":", "list", "of", "tvm", ".", "relay", ".", "Expr", "The", "args", "of", "the", "Relay", "expr", "to", "be", "legalized", "tinfos", ":", "list", "of", "types", "List", "of", "input", "and", "output", "types", "desired_layouts", ":", "list", "of", "one", "layout", "string", "layout", "string", "defining", "our", "desired", "layout", "for", "input", "and", "output", ".", "Returns", "-------", "result", ":", "tvm", ".", "relay", ".", "Expr", "The", "transformed", "expr" ]
def convert_global_avg_pool2d(attrs, inputs, tinfos, desired_layouts): """Convert Layout pass registration for global_avg_pool2d op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current pooling inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized tinfos : list of types List of input and output types desired_layouts : list of one layout string layout string defining our desired layout for input and output. Returns ------- result : tvm.relay.Expr The transformed expr """ new_attrs = dict(attrs) new_attrs["layout"] = str(desired_layouts[0]) new_attrs["out_layout"] = str(desired_layouts[0]) return relay.nn.global_avg_pool2d(*inputs, **new_attrs)
[ "def", "convert_global_avg_pool2d", "(", "attrs", ",", "inputs", ",", "tinfos", ",", "desired_layouts", ")", ":", "new_attrs", "=", "dict", "(", "attrs", ")", "new_attrs", "[", "\"layout\"", "]", "=", "str", "(", "desired_layouts", "[", "0", "]", ")", "new_attrs", "[", "\"out_layout\"", "]", "=", "str", "(", "desired_layouts", "[", "0", "]", ")", "return", "relay", ".", "nn", ".", "global_avg_pool2d", "(", "*", "inputs", ",", "*", "*", "new_attrs", ")" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/op/nn/_nn.py#L647-L667
viewflow/viewflow
2389bd379a2ab22cc277585df7c09514e273541d
viewflow/fields.py
python
import_flow_by_ref
(flow_strref)
return import_string('{}.{}'.format(get_app_package(app_label), flow_path))
Return flow class by flow string reference.
Return flow class by flow string reference.
[ "Return", "flow", "class", "by", "flow", "string", "reference", "." ]
def import_flow_by_ref(flow_strref): """Return flow class by flow string reference.""" app_label, flow_path = flow_strref.split('/') return import_string('{}.{}'.format(get_app_package(app_label), flow_path))
[ "def", "import_flow_by_ref", "(", "flow_strref", ")", ":", "app_label", ",", "flow_path", "=", "flow_strref", ".", "split", "(", "'/'", ")", "return", "import_string", "(", "'{}.{}'", ".", "format", "(", "get_app_package", "(", "app_label", ")", ",", "flow_path", ")", ")" ]
https://github.com/viewflow/viewflow/blob/2389bd379a2ab22cc277585df7c09514e273541d/viewflow/fields.py#L12-L15
tanghaibao/goatools
647e9dd833695f688cd16c2f9ea18f1692e5c6bc
goatools/wr_tbl_class.py
python
WrXlsx.wr_row_mergeall
(self, worksheet, txtstr, fmt, row_idx)
return row_idx + 1
Merge all columns and place text string in widened cell.
Merge all columns and place text string in widened cell.
[ "Merge", "all", "columns", "and", "place", "text", "string", "in", "widened", "cell", "." ]
def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx): """Merge all columns and place text string in widened cell.""" hdridxval = len(self.hdrs) - 1 worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt) return row_idx + 1
[ "def", "wr_row_mergeall", "(", "self", ",", "worksheet", ",", "txtstr", ",", "fmt", ",", "row_idx", ")", ":", "hdridxval", "=", "len", "(", "self", ".", "hdrs", ")", "-", "1", "worksheet", ".", "merge_range", "(", "row_idx", ",", "0", ",", "row_idx", ",", "hdridxval", ",", "txtstr", ",", "fmt", ")", "return", "row_idx", "+", "1" ]
https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/wr_tbl_class.py#L49-L53
makelove/OpenCV-Python-Tutorial
e428d648f7aa50d6a0fb4f4d0fb1bd1a600fef41
官方samples/gabor_threads.py
python
process_threaded
(img, filters, threadn = 8)
return accum
[]
def process_threaded(img, filters, threadn = 8): accum = np.zeros_like(img) def f(kern): return cv2.filter2D(img, cv2.CV_8UC3, kern) pool = ThreadPool(processes=threadn) for fimg in pool.imap_unordered(f, filters): np.maximum(accum, fimg, accum) return accum
[ "def", "process_threaded", "(", "img", ",", "filters", ",", "threadn", "=", "8", ")", ":", "accum", "=", "np", ".", "zeros_like", "(", "img", ")", "def", "f", "(", "kern", ")", ":", "return", "cv2", ".", "filter2D", "(", "img", ",", "cv2", ".", "CV_8UC3", ",", "kern", ")", "pool", "=", "ThreadPool", "(", "processes", "=", "threadn", ")", "for", "fimg", "in", "pool", ".", "imap_unordered", "(", "f", ",", "filters", ")", ":", "np", ".", "maximum", "(", "accum", ",", "fimg", ",", "accum", ")", "return", "accum" ]
https://github.com/makelove/OpenCV-Python-Tutorial/blob/e428d648f7aa50d6a0fb4f4d0fb1bd1a600fef41/官方samples/gabor_threads.py#L41-L48
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/interface.py
python
Interface._search_headers_binary
(self, height, bad, bad_header, chain)
return good, bad, bad_header
[]
async def _search_headers_binary(self, height, bad, bad_header, chain): assert bad == bad_header['block_height'] _assert_header_does_not_check_against_any_chain(bad_header) self.blockchain = chain if isinstance(chain, Blockchain) else self.blockchain good = height while True: assert good < bad, (good, bad) height = (good + bad) // 2 self.logger.info(f"binary step. good {good}, bad {bad}, height {height}") header = await self.get_block_header(height, 'binary') chain = blockchain.check_header(header) if 'mock' not in header else header['mock']['check'](header) if chain: self.blockchain = chain if isinstance(chain, Blockchain) else self.blockchain good = height else: bad = height bad_header = header if good + 1 == bad: break mock = 'mock' in bad_header and bad_header['mock']['connect'](height) real = not mock and self.blockchain.can_connect(bad_header, check_height=False) if not real and not mock: raise Exception('unexpected bad header during binary: {}'.format(bad_header)) _assert_header_does_not_check_against_any_chain(bad_header) self.logger.info(f"binary search exited. good {good}, bad {bad}") return good, bad, bad_header
[ "async", "def", "_search_headers_binary", "(", "self", ",", "height", ",", "bad", ",", "bad_header", ",", "chain", ")", ":", "assert", "bad", "==", "bad_header", "[", "'block_height'", "]", "_assert_header_does_not_check_against_any_chain", "(", "bad_header", ")", "self", ".", "blockchain", "=", "chain", "if", "isinstance", "(", "chain", ",", "Blockchain", ")", "else", "self", ".", "blockchain", "good", "=", "height", "while", "True", ":", "assert", "good", "<", "bad", ",", "(", "good", ",", "bad", ")", "height", "=", "(", "good", "+", "bad", ")", "//", "2", "self", ".", "logger", ".", "info", "(", "f\"binary step. good {good}, bad {bad}, height {height}\"", ")", "header", "=", "await", "self", ".", "get_block_header", "(", "height", ",", "'binary'", ")", "chain", "=", "blockchain", ".", "check_header", "(", "header", ")", "if", "'mock'", "not", "in", "header", "else", "header", "[", "'mock'", "]", "[", "'check'", "]", "(", "header", ")", "if", "chain", ":", "self", ".", "blockchain", "=", "chain", "if", "isinstance", "(", "chain", ",", "Blockchain", ")", "else", "self", ".", "blockchain", "good", "=", "height", "else", ":", "bad", "=", "height", "bad_header", "=", "header", "if", "good", "+", "1", "==", "bad", ":", "break", "mock", "=", "'mock'", "in", "bad_header", "and", "bad_header", "[", "'mock'", "]", "[", "'connect'", "]", "(", "height", ")", "real", "=", "not", "mock", "and", "self", ".", "blockchain", ".", "can_connect", "(", "bad_header", ",", "check_height", "=", "False", ")", "if", "not", "real", "and", "not", "mock", ":", "raise", "Exception", "(", "'unexpected bad header during binary: {}'", ".", "format", "(", "bad_header", ")", ")", "_assert_header_does_not_check_against_any_chain", "(", "bad_header", ")", "self", ".", "logger", ".", "info", "(", "f\"binary search exited. good {good}, bad {bad}\"", ")", "return", "good", ",", "bad", ",", "bad_header" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/interface.py#L790-L818
wonderworks-software/PyFlow
57e2c858933bf63890d769d985396dfad0fca0f0
.vscode/.ropeproject/config.py
python
project_opened
(project)
This function is called after opening the project
This function is called after opening the project
[ "This", "function", "is", "called", "after", "opening", "the", "project" ]
def project_opened(project): """This function is called after opening the project"""
[ "def", "project_opened", "(", "project", ")", ":" ]
https://github.com/wonderworks-software/PyFlow/blob/57e2c858933bf63890d769d985396dfad0fca0f0/.vscode/.ropeproject/config.py#L112-L113