nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
crownpku/Rasa_NLU_Chi
ec0e4ef155b1ee3e4c1bf277346548351e9e9c11
rasa_nlu/persistor.py
python
AWSPersistor._persist_tar
(self, file_key, tar_path)
Uploads a model persisted in the `target_dir` to s3.
Uploads a model persisted in the `target_dir` to s3.
[ "Uploads", "a", "model", "persisted", "in", "the", "target_dir", "to", "s3", "." ]
def _persist_tar(self, file_key, tar_path): # type: (Text, Text) -> None """Uploads a model persisted in the `target_dir` to s3.""" with open(tar_path, 'rb') as f: self.s3.Object(self.bucket_name, file_key).put(Body=f)
[ "def", "_persist_tar", "(", "self", ",", "file_key", ",", "tar_path", ")", ":", "# type: (Text, Text) -> None", "with", "open", "(", "tar_path", ",", "'rb'", ")", "as", "f", ":", "self", ".", "s3", ".", "Object", "(", "self", ".", "bucket_name", ",", "fi...
https://github.com/crownpku/Rasa_NLU_Chi/blob/ec0e4ef155b1ee3e4c1bf277346548351e9e9c11/rasa_nlu/persistor.py#L184-L189
pjkundert/cpppo
4c217b6c06b88bede3888cc5ea2731f271a95086
automata.py
python
dfa_base.terminal
( self )
return self._terminal and self.current.terminal and not self.loop()
Reflects the terminal condition of this state, our sub-machine, and done all 'repeat' loops. If we have a multi-state sub-machine (which may in turn contain further multi-state dfas), we must not return terminal 'til A) we ourself were designated as terminal, we are in the last loop, and the current state of our multi-state machine is also marked terminal.
Reflects the terminal condition of this state, our sub-machine, and done all 'repeat' loops. If we have a multi-state sub-machine (which may in turn contain further multi-state dfas), we must not return terminal 'til A) we ourself were designated as terminal, we are in the last loop, and the current state of our multi-state machine is also marked terminal.
[ "Reflects", "the", "terminal", "condition", "of", "this", "state", "our", "sub", "-", "machine", "and", "done", "all", "repeat", "loops", ".", "If", "we", "have", "a", "multi", "-", "state", "sub", "-", "machine", "(", "which", "may", "in", "turn", "co...
def terminal( self ): """Reflects the terminal condition of this state, our sub-machine, and done all 'repeat' loops. If we have a multi-state sub-machine (which may in turn contain further multi-state dfas), we must not return terminal 'til A) we ourself were designated as terminal, we are in the last loop, and the current state of our multi-state machine is also marked terminal.""" return self._terminal and self.current.terminal and not self.loop()
[ "def", "terminal", "(", "self", ")", ":", "return", "self", ".", "_terminal", "and", "self", ".", "current", ".", "terminal", "and", "not", "self", ".", "loop", "(", ")" ]
https://github.com/pjkundert/cpppo/blob/4c217b6c06b88bede3888cc5ea2731f271a95086/automata.py#L1196-L1201
D-X-Y/AutoDL-Projects
d2cef525f34b4c97525a397a0c6da9a937f2642c
exps/NAS-Bench-201-algos/R_EA.py
python
mutate_arch_func
(op_names)
return mutate_arch_func
Computes the architecture for a child of the given parent architecture. The parent architecture is cloned and mutated to produce the child architecture. The child architecture is mutated by randomly switch one operation to another.
Computes the architecture for a child of the given parent architecture. The parent architecture is cloned and mutated to produce the child architecture. The child architecture is mutated by randomly switch one operation to another.
[ "Computes", "the", "architecture", "for", "a", "child", "of", "the", "given", "parent", "architecture", ".", "The", "parent", "architecture", "is", "cloned", "and", "mutated", "to", "produce", "the", "child", "architecture", ".", "The", "child", "architecture", ...
def mutate_arch_func(op_names): """Computes the architecture for a child of the given parent architecture. The parent architecture is cloned and mutated to produce the child architecture. The child architecture is mutated by randomly switch one operation to another. """ def mutate_arch_func(parent_arch): child_arch = deepcopy(parent_arch) node_id = random.randint(0, len(child_arch.nodes) - 1) node_info = list(child_arch.nodes[node_id]) snode_id = random.randint(0, len(node_info) - 1) xop = random.choice(op_names) while xop == node_info[snode_id][0]: xop = random.choice(op_names) node_info[snode_id] = (xop, node_info[snode_id][1]) child_arch.nodes[node_id] = tuple(node_info) return child_arch return mutate_arch_func
[ "def", "mutate_arch_func", "(", "op_names", ")", ":", "def", "mutate_arch_func", "(", "parent_arch", ")", ":", "child_arch", "=", "deepcopy", "(", "parent_arch", ")", "node_id", "=", "random", ".", "randint", "(", "0", ",", "len", "(", "child_arch", ".", "...
https://github.com/D-X-Y/AutoDL-Projects/blob/d2cef525f34b4c97525a397a0c6da9a937f2642c/exps/NAS-Bench-201-algos/R_EA.py#L131-L148
mu-editor/mu
5a5d7723405db588f67718a63a0ec0ecabebae33
mu/interface/main.py
python
Window.remove_python_runner
(self)
Removes the runner pane from the application.
Removes the runner pane from the application.
[ "Removes", "the", "runner", "pane", "from", "the", "application", "." ]
def remove_python_runner(self): """ Removes the runner pane from the application. """ if hasattr(self, "runner") and self.runner: if self.process_runner.debugger: self._debugger_area = self.dockWidgetArea(self.runner) else: self._runner_area = self.dockWidgetArea(self.runner) self.process_runner = None self.runner.setParent(None) self.runner.deleteLater() self.runner = None
[ "def", "remove_python_runner", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"runner\"", ")", "and", "self", ".", "runner", ":", "if", "self", ".", "process_runner", ".", "debugger", ":", "self", ".", "_debugger_area", "=", "self", ".", "do...
https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/interface/main.py#L922-L934
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/qparser/plugins.py
python
PseudoFieldPlugin.__init__
(self, xform_map)
:param xform_map: a dictionary mapping psuedo-field names to transform functions. The function should take a :class:`whoosh.qparser.SyntaxNode` as an argument, and return a :class:`~whoosh.qparser.SyntaxNode`. If the function returns None, the node will be removed from the query.
:param xform_map: a dictionary mapping psuedo-field names to transform functions. The function should take a :class:`whoosh.qparser.SyntaxNode` as an argument, and return a :class:`~whoosh.qparser.SyntaxNode`. If the function returns None, the node will be removed from the query.
[ ":", "param", "xform_map", ":", "a", "dictionary", "mapping", "psuedo", "-", "field", "names", "to", "transform", "functions", ".", "The", "function", "should", "take", "a", ":", "class", ":", "whoosh", ".", "qparser", ".", "SyntaxNode", "as", "an", "argum...
def __init__(self, xform_map): """ :param xform_map: a dictionary mapping psuedo-field names to transform functions. The function should take a :class:`whoosh.qparser.SyntaxNode` as an argument, and return a :class:`~whoosh.qparser.SyntaxNode`. If the function returns None, the node will be removed from the query. """ self.xform_map = xform_map
[ "def", "__init__", "(", "self", ",", "xform_map", ")", ":", "self", ".", "xform_map", "=", "xform_map" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/qparser/plugins.py#L1370-L1379
aburkov/theMLbook
a0344c72360b03c5a61bfaf55539e8a47f395574
Animated_Illustrations/kmeans.py
python
voronoi_finite_polygons_2d
(vor, radius=None)
return new_regions, np.asarray(new_vertices)
Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end.
Reconstruct infinite voronoi regions in a 2D diagram to finite regions.
[ "Reconstruct", "infinite", "voronoi", "regions", "in", "a", "2D", "diagram", "to", "finite", "regions", "." ]
def voronoi_finite_polygons_2d(vor, radius=None): """ Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max()*2 # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all([v >= 0 for v in vertices]): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
[ "def", "voronoi_finite_polygons_2d", "(", "vor", ",", "radius", "=", "None", ")", ":", "if", "vor", ".", "points", ".", "shape", "[", "1", "]", "!=", "2", ":", "raise", "ValueError", "(", "\"Requires 2D input\"", ")", "new_regions", "=", "[", "]", "new_v...
https://github.com/aburkov/theMLbook/blob/a0344c72360b03c5a61bfaf55539e8a47f395574/Animated_Illustrations/kmeans.py#L20-L101
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/swift/swift/common/manager.py
python
Server.wait
(self, **kwargs)
return status
wait on spawned procs to start
wait on spawned procs to start
[ "wait", "on", "spawned", "procs", "to", "start" ]
def wait(self, **kwargs): """ wait on spawned procs to start """ status = 0 for proc in self.procs: # wait for process to close its stdout output = proc.stdout.read() if output: print output start = time.time() # wait for process to die (output may just be a warning) while time.time() - start < WARNING_WAIT: time.sleep(0.1) if proc.poll() is not None: status += proc.returncode break return status
[ "def", "wait", "(", "self", ",", "*", "*", "kwargs", ")", ":", "status", "=", "0", "for", "proc", "in", "self", ".", "procs", ":", "# wait for process to close its stdout", "output", "=", "proc", ".", "stdout", ".", "read", "(", ")", "if", "output", ":...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/swift/swift/common/manager.py#L541-L558
PyRetri/PyRetri
3faf94e740e48a64c080626fd4949e1eec7518b2
pyretri/index/helper/helper.py
python
IndexHelper.show_topk_retrieved_images
(self, single_query_info: Dict, topk: int, gallery_info: List[Dict])
Show the top-k retrieved images of one query. Args: single_query_info (dict): a dict of single query information. topk (int): number of the nearest images to be showed. gallery_info (list): a list of gallery set information.
Show the top-k retrieved images of one query.
[ "Show", "the", "top", "-", "k", "retrieved", "images", "of", "one", "query", "." ]
def show_topk_retrieved_images(self, single_query_info: Dict, topk: int, gallery_info: List[Dict]) -> None: """ Show the top-k retrieved images of one query. Args: single_query_info (dict): a dict of single query information. topk (int): number of the nearest images to be showed. gallery_info (list): a list of gallery set information. """ query_idx = single_query_info["ranked_neighbors_idx"] query_topk_idx = query_idx[:topk] for idx in query_topk_idx: img_path = gallery_info[idx]["path"] plt.figure() plt.imshow(img_path) plt.show()
[ "def", "show_topk_retrieved_images", "(", "self", ",", "single_query_info", ":", "Dict", ",", "topk", ":", "int", ",", "gallery_info", ":", "List", "[", "Dict", "]", ")", "->", "None", ":", "query_idx", "=", "single_query_info", "[", "\"ranked_neighbors_idx\"", ...
https://github.com/PyRetri/PyRetri/blob/3faf94e740e48a64c080626fd4949e1eec7518b2/pyretri/index/helper/helper.py#L44-L60
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/topi/x86/conv2d.py
python
schedule_conv2d_nhwc
(outs)
return s
Create schedule for conv2d_nhwc
Create schedule for conv2d_nhwc
[ "Create", "schedule", "for", "conv2d_nhwc" ]
def schedule_conv2d_nhwc(outs): """Create schedule for conv2d_nhwc""" outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) output_op = outs[0].op def _callback(op): if "conv2d_nhwc" in op.tag: conv = op.output(0) kernel = op.input_tensors[1] if isinstance(kernel.op, tvm.te.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() data = op.input_tensors[0] data_pad = None if isinstance(data.op, tvm.te.ComputeOp) and "pad" in data.op.tag: data_pad = data data = data_pad.op.input_tensors[0] n_pad, h_pad, w_pad, c_pad = data_pad.op.axis pad_fused = s[data_pad].fuse(n_pad, h_pad) s[data_pad].parallel(pad_fused) C = conv n, h, w, c = C.op.axis s[C].vectorize(c) O = output_op.output(0) if len(O.op.axis) == 4: # schedule bias + bn + relu n, h, w, c = O.op.axis fused = s[O].fuse(n, h, w) s[O].parallel(fused) channels = int(O.shape[-1]) if channels % 64 == 0: c, ci = s[O].split(c, 64) s[O].vectorize(ci) if C != O: s[C].compute_at(s[O], c) traverse_inline(s, output_op, _callback) return s
[ "def", "schedule_conv2d_nhwc", "(", "outs", ")", ":", "outs", "=", "[", "outs", "]", "if", "isinstance", "(", "outs", ",", "te", ".", "tensor", ".", "Tensor", ")", "else", "outs", "s", "=", "te", ".", "create_schedule", "(", "[", "x", ".", "op", "f...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/topi/x86/conv2d.py#L85-L124
rlgraph/rlgraph
428fc136a9a075f29a397495b4226a491a287be2
rlgraph/components/helpers/dynamic_batching.py
python
batch_fn_with_options
(minimum_batch_size=1, maximum_batch_size=1024, timeout_ms=100)
return decorator
Python decorator that automatically batches computations. When the decorated function is called, it creates an operation that adds the inputs to a queue, waits until the computation is done, and returns the tensors. The inputs must be nests (see `tf.contrib.framework.nest`) and the first dimension of each tensor in the nest must have size 1. It adds a QueueRunner that asynchronously keeps fetching batches of data, computes the results and pushes the results back to the caller. Example usage: @dynamic_batching.batch_fn_with_options(minimum_batch_size=10, timeout_ms=100) def fn(a, b): return a + b output0 = fn(tf.constant([1]), tf.constant([2])) # Will be batched with the next call. output1 = fn(tf.constant([3]), tf.constant([4])) Note, gradients are currently not supported. Note, if minimum_batch_size == maximum_batch_size and timeout_ms=None, then the batch size of input arguments will be set statically. Otherwise, it will be None. Args: minimum_batch_size: The minimum batch size before processing starts. maximum_batch_size: The maximum batch size. timeout_ms: Milliseconds after a batch of samples is requested before it is processed, even if the batch size is smaller than `minimum_batch_size`. If None, there is no timeout. Returns: The decorator.
Python decorator that automatically batches computations.
[ "Python", "decorator", "that", "automatically", "batches", "computations", "." ]
def batch_fn_with_options(minimum_batch_size=1, maximum_batch_size=1024, timeout_ms=100): """ Python decorator that automatically batches computations. When the decorated function is called, it creates an operation that adds the inputs to a queue, waits until the computation is done, and returns the tensors. The inputs must be nests (see `tf.contrib.framework.nest`) and the first dimension of each tensor in the nest must have size 1. It adds a QueueRunner that asynchronously keeps fetching batches of data, computes the results and pushes the results back to the caller. Example usage: @dynamic_batching.batch_fn_with_options(minimum_batch_size=10, timeout_ms=100) def fn(a, b): return a + b output0 = fn(tf.constant([1]), tf.constant([2])) # Will be batched with the next call. output1 = fn(tf.constant([3]), tf.constant([4])) Note, gradients are currently not supported. Note, if minimum_batch_size == maximum_batch_size and timeout_ms=None, then the batch size of input arguments will be set statically. Otherwise, it will be None. Args: minimum_batch_size: The minimum batch size before processing starts. maximum_batch_size: The maximum batch size. timeout_ms: Milliseconds after a batch of samples is requested before it is processed, even if the batch size is smaller than `minimum_batch_size`. If None, there is no timeout. Returns: The decorator. """ def decorator(f): """Decorator.""" batcher = [None] batched_output = [None] @functools.wraps(f) def wrapper(*args): """Wrapper.""" self_arg = args[0] args = args[1:] flat_args = [tf.convert_to_tensor(arg) for arg in nest.flatten(args)] #flat_args = nest.flatten(args) if batcher[0] is None: # Remove control dependencies which is necessary when created in loops, # etc. with tf.control_dependencies(None): input_dtypes = [t.dtype for t in flat_args] batcher[0] = Batcher(minimum_batch_size, maximum_batch_size, timeout_ms) # Compute in batches using a queue runner. if minimum_batch_size == maximum_batch_size and timeout_ms is None: batch_size = minimum_batch_size else: batch_size = None # Dequeue batched input. inputs, computation_id = batcher[0].get_inputs(input_dtypes) nest.map_structure( lambda i, a: i.set_shape([batch_size] + a.shape.as_list()[1:]), inputs, flat_args ) # Compute result. result = f(self_arg, *nest.pack_sequence_as(args, inputs)) batched_output[0] = result flat_result = nest.flatten(result) # Insert results back into batcher. set_op = batcher[0].set_outputs(flat_result, computation_id) tf.train.add_queue_runner(tf.train.QueueRunner(batcher[0], [set_op])) # Insert inputs into input queue. flat_result = batcher[0].compute( flat_args, [t.dtype for t in nest.flatten(batched_output[0])]) # Restore structure and shapes. result = nest.pack_sequence_as(batched_output[0], flat_result) static_batch_size = nest.flatten(args)[0].shape[0] nest.map_structure( lambda t, b: t.set_shape([static_batch_size] + b.shape[1:].as_list()), result, batched_output[0] ) return result return wrapper return decorator
[ "def", "batch_fn_with_options", "(", "minimum_batch_size", "=", "1", ",", "maximum_batch_size", "=", "1024", ",", "timeout_ms", "=", "100", ")", ":", "def", "decorator", "(", "f", ")", ":", "\"\"\"Decorator.\"\"\"", "batcher", "=", "[", "None", "]", "batched_o...
https://github.com/rlgraph/rlgraph/blob/428fc136a9a075f29a397495b4226a491a287be2/rlgraph/components/helpers/dynamic_batching.py#L78-L175
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/api/logservice/logservice.py
python
AppLog.source_location
(self)
return self._source_location
Source source_location of the log statement, or None if not supported.
Source source_location of the log statement, or None if not supported.
[ "Source", "source_location", "of", "the", "log", "statement", "or", "None", "if", "not", "supported", "." ]
def source_location(self): """Source source_location of the log statement, or None if not supported.""" return self._source_location
[ "def", "source_location", "(", "self", ")", ":", "return", "self", ".", "_source_location" ]
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/api/logservice/logservice.py#L936-L938
sfepy/sfepy
02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25
sfepy/discrete/fem/utils.py
python
prepare_remap
(indices, n_full)
return remap
Prepare vector for remapping range `[0, n_full]` to its subset given by `indices`.
Prepare vector for remapping range `[0, n_full]` to its subset given by `indices`.
[ "Prepare", "vector", "for", "remapping", "range", "[", "0", "n_full", "]", "to", "its", "subset", "given", "by", "indices", "." ]
def prepare_remap(indices, n_full): """ Prepare vector for remapping range `[0, n_full]` to its subset given by `indices`. """ remap = nm.empty((n_full,), dtype=nm.int32) remap.fill(-1) remap[indices] = nm.arange(indices.shape[0], dtype=nm.int32) return remap
[ "def", "prepare_remap", "(", "indices", ",", "n_full", ")", ":", "remap", "=", "nm", ".", "empty", "(", "(", "n_full", ",", ")", ",", "dtype", "=", "nm", ".", "int32", ")", "remap", ".", "fill", "(", "-", "1", ")", "remap", "[", "indices", "]", ...
https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/discrete/fem/utils.py#L9-L18
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/distutils/command/build_py.py
python
build_py.find_data_files
(self, package, src_dir)
return files
Return filenames for package's data files in 'src_dir
Return filenames for package's data files in 'src_dir
[ "Return", "filenames", "for", "package", "s", "data", "files", "in", "src_dir" ]
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = [] for pattern in globs: # Each pattern has to be converted to a platform-specific path filelist = glob(os.path.join(src_dir, convert_path(pattern))) # Files that match more than one pattern are only added once files.extend([fn for fn in filelist if fn not in files and os.path.isfile(fn)]) return files
[ "def", "find_data_files", "(", "self", ",", "package", ",", "src_dir", ")", ":", "globs", "=", "(", "self", ".", "package_data", ".", "get", "(", "''", ",", "[", "]", ")", "+", "self", ".", "package_data", ".", "get", "(", "package", ",", "[", "]",...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/distutils/command/build_py.py#L121-L132
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_distutils/msvc9compiler.py
python
MSVCCompiler.__init__
(self, verbose=0, dry_run=0, force=0)
[]
def __init__(self, verbose=0, dry_run=0, force=0): CCompiler.__init__ (self, verbose, dry_run, force) self.__version = VERSION self.__root = r"Software\Microsoft\VisualStudio" # self.__macros = MACROS self.__paths = [] # target platform (.plat_name is consistent with 'bdist') self.plat_name = None self.__arch = None # deprecated name self.initialized = False
[ "def", "__init__", "(", "self", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "force", "=", "0", ")", ":", "CCompiler", ".", "__init__", "(", "self", ",", "verbose", ",", "dry_run", ",", "force", ")", "self", ".", "__version", "=", "VERS...
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_distutils/msvc9compiler.py#L326-L335
cupy/cupy
a47ad3105f0fe817a4957de87d98ddccb8c7491f
cupyx/scipy/sparse/linalg/_solve.py
python
SuperLU.solve
(self, rhs, trans='N')
return x
Solves linear system of equations with one or several right-hand sides. Args: rhs (cupy.ndarray): Right-hand side(s) of equation with dimension ``(M)`` or ``(M, K)``. trans (str): 'N', 'T' or 'H'. 'N': Solves ``A * x = rhs``. 'T': Solves ``A.T * x = rhs``. 'H': Solves ``A.conj().T * x = rhs``. Returns: cupy.ndarray: Solution vector(s)
Solves linear system of equations with one or several right-hand sides.
[ "Solves", "linear", "system", "of", "equations", "with", "one", "or", "several", "right", "-", "hand", "sides", "." ]
def solve(self, rhs, trans='N'): """Solves linear system of equations with one or several right-hand sides. Args: rhs (cupy.ndarray): Right-hand side(s) of equation with dimension ``(M)`` or ``(M, K)``. trans (str): 'N', 'T' or 'H'. 'N': Solves ``A * x = rhs``. 'T': Solves ``A.T * x = rhs``. 'H': Solves ``A.conj().T * x = rhs``. Returns: cupy.ndarray: Solution vector(s) """ if not isinstance(rhs, cupy.ndarray): raise TypeError('ojb must be cupy.ndarray') if rhs.ndim not in (1, 2): raise ValueError('rhs.ndim must be 1 or 2 (actual: {})'. format(rhs.ndim)) if rhs.shape[0] != self.shape[0]: raise ValueError('shape mismatch (self.shape: {}, rhs.shape: {})' .format(self.shape, rhs.shape)) if trans not in ('N', 'T', 'H'): raise ValueError('trans must be \'N\', \'T\', or \'H\'') if not cusparse.check_availability('csrsm2'): raise NotImplementedError x = rhs.astype(self.L.dtype) if trans == 'N': if self.perm_r is not None: x = x[self._perm_r_rev] cusparse.csrsm2(self.L, x, lower=True, transa=trans) cusparse.csrsm2(self.U, x, lower=False, transa=trans) if self.perm_c is not None: x = x[self.perm_c] else: if self.perm_c is not None: x = x[self._perm_c_rev] cusparse.csrsm2(self.U, x, lower=False, transa=trans) cusparse.csrsm2(self.L, x, lower=True, transa=trans) if self.perm_r is not None: x = x[self.perm_r] if not x._f_contiguous: # For compatibility with SciPy x = x.copy(order='F') return x
[ "def", "solve", "(", "self", ",", "rhs", ",", "trans", "=", "'N'", ")", ":", "if", "not", "isinstance", "(", "rhs", ",", "cupy", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'ojb must be cupy.ndarray'", ")", "if", "rhs", ".", "ndim", "not", ...
https://github.com/cupy/cupy/blob/a47ad3105f0fe817a4957de87d98ddccb8c7491f/cupyx/scipy/sparse/linalg/_solve.py#L519-L566
wecatch/app-turbo
d3b931db1b0f210d8af1da109edbf88756fa427d
turbo/util.py
python
utf8
(value)
return value.encode("utf-8")
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
Converts a string argument to a byte string.
[ "Converts", "a", "string", "argument", "to", "a", "byte", "string", "." ]
def utf8(value): # type: (typing.Union[bytes,unicode_type,None])->typing.Union[bytes,None] """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value if not isinstance(value, unicode_type): raise TypeError( "Expected bytes, unicode, or None; got %r" % type(value) ) return value.encode("utf-8")
[ "def", "utf8", "(", "value", ")", ":", "# type: (typing.Union[bytes,unicode_type,None])->typing.Union[bytes,None]", "if", "isinstance", "(", "value", ",", "_UTF8_TYPES", ")", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "unicode_type", ")", ...
https://github.com/wecatch/app-turbo/blob/d3b931db1b0f210d8af1da109edbf88756fa427d/turbo/util.py#L345-L358
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/config/writer.py
python
ConfigurationWriter.execute
(self, args)
[]
def execute(self, args): config_data = {} if args is None: raise Exception("Args empty") if args.clients is None: raise Exception("No clients defined") if 'all' in args.clients or 'console' in args.clients: self.add_to_config(config_data, ConsoleConfiguration(), args.defaults) if 'all' in args.clients or 'socket' in args.clients: self.add_to_config(config_data, SocketConfiguration(), args.defaults) if 'all' in args.clients or 'slack' in args.clients: self.add_to_config(config_data, SlackConfiguration(), args.defaults) if 'all' in args.clients or 'telegram' in args.clients: self.add_to_config(config_data, TelegramConfiguration(), args.defaults) if 'all' in args.clients or 'twitter' in args.clients: self.add_to_config(config_data, TwitterConfiguration(), args.defaults) if 'all' in args.clients or 'xmpp' in args.clients: self.add_to_config(config_data, XmppConfiguration(), args.defaults) if 'all' in args.clients or 'rest' in args.clients: self.add_to_config(config_data, RestConfiguration(name="rest")) if 'all' in args.clients or 'facebook' in args.clients: self.add_to_config(config_data, FacebookConfiguration(), args.defaults) if 'all' in args.clients or 'kik' in args.clients: self.add_to_config(config_data, KikConfiguration(), args.defaults) if 'all' in args.clients or 'line' in args.clients: self.add_to_config(config_data, LineConfiguration(), args.defaults) if 'all' in args.clients or 'twilio' in args.clients: self.add_to_config(config_data, TwilioConfiguration(), args.defaults) if 'all' in args.clients or 'viber' in args.clients: self.add_to_config(config_data, ViberConfiguration(), args.defaults) if 'all' in args.clients or 'sanic' in args.clients: self.add_to_config(config_data, SanicRestConfiguration(name="sanic")) client_config = ConsoleConfiguration() bot_config = client_config.configurations[0] self.add_to_config(config_data, bot_config, args.defaults) brain_config = bot_config.configurations[0] self.add_to_config(config_data, brain_config, args.defaults) self.write_yaml(args.file, config_data)
[ "def", "execute", "(", "self", ",", "args", ")", ":", "config_data", "=", "{", "}", "if", "args", "is", "None", ":", "raise", "Exception", "(", "\"Args empty\"", ")", "if", "args", ".", "clients", "is", "None", ":", "raise", "Exception", "(", "\"No cli...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/config/writer.py#L45-L104
qgriffith-zz/OpenEats
9373ce65f838f19fead6f73c9491d2211e770769
recipe/migrations/0001_initial.py
python
Migration.forwards
(self, orm)
[]
def forwards(self, orm): # Adding model 'Recipe' db.create_table('recipe_recipe', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=250)), ('slug', self.gf('django.db.models.fields.SlugField')(db_index=True, unique=True, max_length=50, blank=True)), ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('photo', self.gf('django.db.models.fields.files.ImageField')(max_length=100, blank=True)), ('course', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['recipe_groups.Course'])), ('cuisine', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['recipe_groups.Cuisine'])), ('info', self.gf('django.db.models.fields.TextField')()), ('cook_time', self.gf('django.db.models.fields.IntegerField')()), ('servings', self.gf('django.db.models.fields.IntegerField')()), ('directions', self.gf('django.db.models.fields.TextField')()), ('shared', self.gf('django.db.models.fields.IntegerField')(default=0)), ('related', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='RecipeRelated', unique=True, null=True, to=orm['recipe.Recipe'])), ('pub_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('update_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), ('rating_votes', self.gf('django.db.models.fields.PositiveIntegerField')(default=0, blank=True)), ('rating_score', self.gf('django.db.models.fields.IntegerField')(default=0, blank=True)), )) db.send_create_signal('recipe', ['Recipe']) # Adding model 'StoredRecipe' db.create_table('recipe_storedrecipe', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('recipe', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['recipe.Recipe'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), )) db.send_create_signal('recipe', ['StoredRecipe']) # Adding model 'NoteRecipe' db.create_table('recipe_noterecipe', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('recipe', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['recipe.Recipe'])), ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('text', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal('recipe', ['NoteRecipe'])
[ "def", "forwards", "(", "self", ",", "orm", ")", ":", "# Adding model 'Recipe'", "db", ".", "create_table", "(", "'recipe_recipe'", ",", "(", "(", "'id'", ",", "self", ".", "gf", "(", "'django.db.models.fields.AutoField'", ")", "(", "primary_key", "=", "True",...
https://github.com/qgriffith-zz/OpenEats/blob/9373ce65f838f19fead6f73c9491d2211e770769/recipe/migrations/0001_initial.py#L9-L48
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/Theano/theano/tensor/type.py
python
TensorType.__eq__
(self, other)
return type(self) == type(other) and other.dtype == self.dtype \ and other.broadcastable == self.broadcastable
Compare True iff other is the same kind of TensorType.
Compare True iff other is the same kind of TensorType.
[ "Compare", "True", "iff", "other", "is", "the", "same", "kind", "of", "TensorType", "." ]
def __eq__(self, other): """ Compare True iff other is the same kind of TensorType. """ return type(self) == type(other) and other.dtype == self.dtype \ and other.broadcastable == self.broadcastable
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "type", "(", "self", ")", "==", "type", "(", "other", ")", "and", "other", ".", "dtype", "==", "self", ".", "dtype", "and", "other", ".", "broadcastable", "==", "self", ".", "broadcastab...
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/tensor/type.py#L275-L281
Ecogenomics/GTDBTk
1e10c56530b4a15eadce519619a62584a490632d
gtdbtk/reroot_tree.py
python
RerootTree.root_with_outgroup
(self, input_tree: str, output_tree: str, outgroup: Set[str])
Reroot the tree using the given outgroup. Parameters ---------- input_tree File containing Newick tree to rerooted. output_tree Name of file for rerooted tree. outgroup Labels of taxa in outgroup.
Reroot the tree using the given outgroup.
[ "Reroot", "the", "tree", "using", "the", "given", "outgroup", "." ]
def root_with_outgroup(self, input_tree: str, output_tree: str, outgroup: Set[str]): """Reroot the tree using the given outgroup. Parameters ---------- input_tree File containing Newick tree to rerooted. output_tree Name of file for rerooted tree. outgroup Labels of taxa in outgroup. """ tree = dendropy.Tree.get_from_path(input_tree, schema='newick', rooting='force-rooted', preserve_underscores=True) outgroup = set(outgroup) outgroup_in_tree = set() ingroup_leaves = set() for n in tree.leaf_node_iter(): if n.taxon.label in outgroup: outgroup_in_tree.add(n.taxon) else: ingroup_leaves.add(n) self.logger.info(f'Identified {len(outgroup_in_tree):,} outgroup taxa in the tree.') self.logger.info(f'Identified {len(ingroup_leaves):,} ingroup taxa in the tree.') if len(outgroup_in_tree) == 0: self.logger.error('No outgroup taxa identified in the tree.') raise GTDBTkExit('Tree was not rerooted.') # Since finding the MRCA is a rooted tree operation, # the tree is first rerooted on an ingroup taxa. This # ensures the MRCA of the outgroup can be identified # so long as the outgroup is monophyletic. If the # outgroup is polyphyletic trying to root on it # is ill defined. To try and pick a "good" root for # polyphyletic outgroups, random ingroup taxa are # selected until two of them give the same size # lineage. This will, likely, be the smallest # bipartition possible for the given outgroup though # this is not guaranteed. mrca = tree.mrca(taxa=outgroup_in_tree) mrca_leaves = len(mrca.leaf_nodes()) while True: rnd_ingroup = random.sample(ingroup_leaves, 1)[0] tree.reroot_at_edge(rnd_ingroup.edge, length1=0.5 * rnd_ingroup.edge_length, length2=0.5 * rnd_ingroup.edge_length) mrca = tree.mrca(taxa=outgroup_in_tree) if len(mrca.leaf_nodes()) == mrca_leaves: break mrca_leaves = len(mrca.leaf_nodes()) if len(mrca.leaf_nodes()) != len(outgroup_in_tree): self.logger.info('Outgroup is not monophyletic. Tree will be ' 'rerooted at the MRCA of the outgroup.') self.logger.info(f'The outgroup consisted of ' f'{len(outgroup_in_tree):,} taxa, while the MRCA ' f'has {len(mrca.leaf_nodes()):,} leaf nodes.') if len(mrca.leaf_nodes()) == len(tree.leaf_nodes()): self.logger.warning('The MRCA spans all taxa in the tree.') self.logger.warning('This indicating the selected outgroup is ' 'likely polyphyletic in the current tree.') self.logger.warning('Polyphyletic outgroups are not suitable ' 'for rooting. Try another outgroup.') else: self.logger.info('Outgroup is monophyletic.') if mrca.edge_length is None: self.logger.info('Tree appears to already be rooted on this outgroup.') else: self.logger.info('Rerooting tree.') tree.reroot_at_edge(mrca.edge, length1=0.5 * mrca.edge_length, length2=0.5 * mrca.edge_length) tree.write_to_path(output_tree, schema='newick', suppress_rooting=True, unquoted_underscores=True) self.logger.info(f'Rerooted tree written to: {output_tree}')
[ "def", "root_with_outgroup", "(", "self", ",", "input_tree", ":", "str", ",", "output_tree", ":", "str", ",", "outgroup", ":", "Set", "[", "str", "]", ")", ":", "tree", "=", "dendropy", ".", "Tree", ".", "get_from_path", "(", "input_tree", ",", "schema",...
https://github.com/Ecogenomics/GTDBTk/blob/1e10c56530b4a15eadce519619a62584a490632d/gtdbtk/reroot_tree.py#L35-L118
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_gcloud/library/gcloud_dm_resource_builder.py
python
FirewallRule.network
(self)
return self._network
property for resource network
property for resource network
[ "property", "for", "resource", "network" ]
def network(self): '''property for resource network''' return self._network
[ "def", "network", "(", "self", ")", ":", "return", "self", ".", "_network" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_gcloud/library/gcloud_dm_resource_builder.py#L820-L822
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
reload_file
(*args)
return _idaapi.reload_file(*args)
reload_file(file, is_remote) -> int
reload_file(file, is_remote) -> int
[ "reload_file", "(", "file", "is_remote", ")", "-", ">", "int" ]
def reload_file(*args): """ reload_file(file, is_remote) -> int """ return _idaapi.reload_file(*args)
[ "def", "reload_file", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "reload_file", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L46781-L46785
cloudinary/pycloudinary
a61a9687c8933f23574c38e27f201358e540ee64
cloudinary/utils.py
python
download_backedup_asset
(asset_id, version_id, **options)
return base_api_url("download_backup", **options) + "?" + urlencode(bracketize_seq(cloudinary_params), True)
The returned url allows downloading the backedup asset based on the the asset ID and the version ID. Parameters asset_id and version_id are returned with api.resource(<PUBLIC_ID1>, versions=True) API call. :param asset_id: The asset ID of the asset. :type asset_id: str :param version_id: The version ID of the asset. :type version_id: str :param options: Additional options. :type options: dict, optional :return:The signed URL for downloading backup version of the asset. :rtype: str
The returned url allows downloading the backedup asset based on the the asset ID and the version ID.
[ "The", "returned", "url", "allows", "downloading", "the", "backedup", "asset", "based", "on", "the", "the", "asset", "ID", "and", "the", "version", "ID", "." ]
def download_backedup_asset(asset_id, version_id, **options): """ The returned url allows downloading the backedup asset based on the the asset ID and the version ID. Parameters asset_id and version_id are returned with api.resource(<PUBLIC_ID1>, versions=True) API call. :param asset_id: The asset ID of the asset. :type asset_id: str :param version_id: The version ID of the asset. :type version_id: str :param options: Additional options. :type options: dict, optional :return:The signed URL for downloading backup version of the asset. :rtype: str """ params = { "timestamp": options.get("timestamp", now()), "asset_id": asset_id, "version_id": version_id } cloudinary_params = sign_request(params, options) return base_api_url("download_backup", **options) + "?" + urlencode(bracketize_seq(cloudinary_params), True)
[ "def", "download_backedup_asset", "(", "asset_id", ",", "version_id", ",", "*", "*", "options", ")", ":", "params", "=", "{", "\"timestamp\"", ":", "options", ".", "get", "(", "\"timestamp\"", ",", "now", "(", ")", ")", ",", "\"asset_id\"", ":", "asset_id"...
https://github.com/cloudinary/pycloudinary/blob/a61a9687c8933f23574c38e27f201358e540ee64/cloudinary/utils.py#L945-L967
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/modeling/functional_models.py
python
Shift.fit_deriv
(x, *params)
return [d_offset]
One dimensional Shift model derivative with respect to parameter
One dimensional Shift model derivative with respect to parameter
[ "One", "dimensional", "Shift", "model", "derivative", "with", "respect", "to", "parameter" ]
def fit_deriv(x, *params): """One dimensional Shift model derivative with respect to parameter""" d_offset = np.ones_like(x) return [d_offset]
[ "def", "fit_deriv", "(", "x", ",", "*", "params", ")", ":", "d_offset", "=", "np", ".", "ones_like", "(", "x", ")", "return", "[", "d_offset", "]" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/modeling/functional_models.py#L491-L495
networkx/networkx
1620568e36702b1cfeaf1c0277b167b6cb93e48d
networkx/classes/function.py
python
is_frozen
(G)
Returns True if graph is frozen. Parameters ---------- G : graph A NetworkX graph See Also -------- freeze
Returns True if graph is frozen.
[ "Returns", "True", "if", "graph", "is", "frozen", "." ]
def is_frozen(G): """Returns True if graph is frozen. Parameters ---------- G : graph A NetworkX graph See Also -------- freeze """ try: return G.frozen except AttributeError: return False
[ "def", "is_frozen", "(", "G", ")", ":", "try", ":", "return", "G", ".", "frozen", "except", "AttributeError", ":", "return", "False" ]
https://github.com/networkx/networkx/blob/1620568e36702b1cfeaf1c0277b167b6cb93e48d/networkx/classes/function.py#L210-L225
prkumar/uplink
3472806f68a60a93f7cb555d36365551a5411cc5
uplink/decorators.py
python
MethodAnnotation._is_consumer_class
(c)
return utils.is_subclass(c, interfaces.Consumer)
[]
def _is_consumer_class(c): return utils.is_subclass(c, interfaces.Consumer)
[ "def", "_is_consumer_class", "(", "c", ")", ":", "return", "utils", ".", "is_subclass", "(", "c", ",", "interfaces", ".", "Consumer", ")" ]
https://github.com/prkumar/uplink/blob/3472806f68a60a93f7cb555d36365551a5411cc5/uplink/decorators.py#L71-L72
microsoft/debugpy
be8dd607f6837244e0b565345e497aff7a0c08bf
src/debugpy/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pytree.py
python
NodePattern.__init__
(self, type=None, content=None, name=None)
Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if not None, must be a sequence of Patterns that must match the node's children exactly. If the content is given, the type must not be None. If a name is given, the matching node is stored in the results dict under that key.
Initializer. Takes optional type, content, and name.
[ "Initializer", ".", "Takes", "optional", "type", "content", "and", "name", "." ]
def __init__(self, type=None, content=None, name=None): """ Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if not None, must be a sequence of Patterns that must match the node's children exactly. If the content is given, the type must not be None. If a name is given, the matching node is stored in the results dict under that key. """ if type is not None: assert type >= 256, type if content is not None: assert not isinstance(content, basestring), repr(content) content = list(content) for i, item in enumerate(content): assert isinstance(item, BasePattern), (i, item) if isinstance(item, WildcardPattern): self.wildcards = True self.type = type self.content = content self.name = name
[ "def", "__init__", "(", "self", ",", "type", "=", "None", ",", "content", "=", "None", ",", "name", "=", "None", ")", ":", "if", "type", "is", "not", "None", ":", "assert", "type", ">=", "256", ",", "type", "if", "content", "is", "not", "None", "...
https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pytree.py#L582-L609
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
api/views/workflow_data_text.py
python
WorkFlowDataText.put
(self, request, src, form, prg, nnid, ver, node)
This API is for set node parameters \n This node is for data extraction \n This node especially handles text type data \n You can set source server by set up parameters \n --- # Class Name : WorkFlowDataText # Description: 1. Modify selected data (use datamanager instead) 2. Modify params for data source, preprocess method and etc
This API is for set node parameters \n This node is for data extraction \n This node especially handles text type data \n You can set source server by set up parameters \n --- # Class Name : WorkFlowDataText
[ "This", "API", "is", "for", "set", "node", "parameters", "\\", "n", "This", "node", "is", "for", "data", "extraction", "\\", "n", "This", "node", "especially", "handles", "text", "type", "data", "\\", "n", "You", "can", "set", "source", "server", "by", ...
def put(self, request, src, form, prg, nnid, ver, node): """ This API is for set node parameters \n This node is for data extraction \n This node especially handles text type data \n You can set source server by set up parameters \n --- # Class Name : WorkFlowDataText # Description: 1. Modify selected data (use datamanager instead) 2. Modify params for data source, preprocess method and etc """ try: if (prg == 'source'): return_data = WfDataText().put_step_source(src, form, nnid, ver, node, request.data) elif (prg == 'pre'): return_data = WfDataText().put_step_preprocess(src, form, nnid, ver, node, request.data) elif (prg == 'store'): return_data = WfDataText().put_step_store(src, form, nnid, ver, node, request.data) return Response(json.dumps(return_data)) except Exception as e: return_data = {"status": "404", "result": str(e)} return Response(json.dumps(return_data))
[ "def", "put", "(", "self", ",", "request", ",", "src", ",", "form", ",", "prg", ",", "nnid", ",", "ver", ",", "node", ")", ":", "try", ":", "if", "(", "prg", "==", "'source'", ")", ":", "return_data", "=", "WfDataText", "(", ")", ".", "put_step_s...
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/api/views/workflow_data_text.py#L79-L102
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/synthDriverHandler.py
python
SynthDriver.pause
(self, switch)
Pause or resume speech output. @param switch: C{True} to pause, C{False} to resume (unpause). @type switch: bool
Pause or resume speech output.
[ "Pause", "or", "resume", "speech", "output", "." ]
def pause(self, switch): """Pause or resume speech output. @param switch: C{True} to pause, C{False} to resume (unpause). @type switch: bool """ pass
[ "def", "pause", "(", "self", ",", "switch", ")", ":", "pass" ]
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/synthDriverHandler.py#L296-L301
ninthDevilHAUNSTER/ArknightsAutoHelper
a27a930502d6e432368d9f62595a1d69a992f4e6
vendor/penguin_client/penguin_client/models/single_query.py
python
SingleQuery.end
(self, end)
Sets the end of this SingleQuery. The end time of the query time range. Nullable. # noqa: E501 :param end: The end of this SingleQuery. # noqa: E501 :type: int
Sets the end of this SingleQuery.
[ "Sets", "the", "end", "of", "this", "SingleQuery", "." ]
def end(self, end): """Sets the end of this SingleQuery. The end time of the query time range. Nullable. # noqa: E501 :param end: The end of this SingleQuery. # noqa: E501 :type: int """ self._end = end
[ "def", "end", "(", "self", ",", "end", ")", ":", "self", ".", "_end", "=", "end" ]
https://github.com/ninthDevilHAUNSTER/ArknightsAutoHelper/blob/a27a930502d6e432368d9f62595a1d69a992f4e6/vendor/penguin_client/penguin_client/models/single_query.py#L92-L101
dbt-labs/dbt-core
e943b9fc842535e958ef4fd0b8703adc91556bc6
core/dbt/task/debug.py
python
DebugTask._log_project_fail
(self)
[]
def _log_project_fail(self): if not self.project_fail_details: return self.any_failure = True if self.project_fail_details == FILE_NOT_FOUND: return msg = ( f'Project loading failed for the following reason:' f'\n{self.project_fail_details}' f'\n' ) self.messages.append(msg)
[ "def", "_log_project_fail", "(", "self", ")", ":", "if", "not", "self", ".", "project_fail_details", ":", "return", "self", ".", "any_failure", "=", "True", "if", "self", ".", "project_fail_details", "==", "FILE_NOT_FOUND", ":", "return", "msg", "=", "(", "f...
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/task/debug.py#L310-L322
CamDavidsonPilon/PyProcess
382da02d0f9732d75624538effa11caded161779
pyprocess/pyprocess.py
python
OU_process._sample_position
(self,t)
[]
def _sample_position(self,t): if not self.conditional: return self.get_mean_at(t)+np.sqrt(self.get_variance_at(t))*self.Normal.rvs() else: #this needs to be completed return super(OU_process,self)._generate_position_at(t)
[ "def", "_sample_position", "(", "self", ",", "t", ")", ":", "if", "not", "self", ".", "conditional", ":", "return", "self", ".", "get_mean_at", "(", "t", ")", "+", "np", ".", "sqrt", "(", "self", ".", "get_variance_at", "(", "t", ")", ")", "*", "se...
https://github.com/CamDavidsonPilon/PyProcess/blob/382da02d0f9732d75624538effa11caded161779/pyprocess/pyprocess.py#L825-L830
deepmind/acme
9880719d9def1d87a194377b394a414a17d11064
examples/control/run_d4pg_gym.py
python
make_networks
( action_spec: specs.BoundedArray, policy_layer_sizes: Sequence[int] = (256, 256, 256), critic_layer_sizes: Sequence[int] = (512, 512, 256), vmin: float = -150., vmax: float = 150., num_atoms: int = 51, )
return { 'policy': policy_network, 'critic': critic_network, 'observation': observation_network, }
Creates the networks used by the agent.
Creates the networks used by the agent.
[ "Creates", "the", "networks", "used", "by", "the", "agent", "." ]
def make_networks( action_spec: specs.BoundedArray, policy_layer_sizes: Sequence[int] = (256, 256, 256), critic_layer_sizes: Sequence[int] = (512, 512, 256), vmin: float = -150., vmax: float = 150., num_atoms: int = 51, ) -> Mapping[str, types.TensorTransformation]: """Creates the networks used by the agent.""" # Get total number of action dimensions from action spec. num_dimensions = np.prod(action_spec.shape, dtype=int) # Create the shared observation network; here simply a state-less operation. observation_network = tf2_utils.batch_concat # Create the policy network. policy_network = snt.Sequential([ networks.LayerNormMLP(policy_layer_sizes, activate_final=True), networks.NearZeroInitializedLinear(num_dimensions), networks.TanhToSpec(action_spec), ]) # Create the critic network. critic_network = snt.Sequential([ # The multiplexer concatenates the observations/actions. networks.CriticMultiplexer(), networks.LayerNormMLP(critic_layer_sizes, activate_final=True), networks.DiscreteValuedHead(vmin, vmax, num_atoms), ]) return { 'policy': policy_network, 'critic': critic_network, 'observation': observation_network, }
[ "def", "make_networks", "(", "action_spec", ":", "specs", ".", "BoundedArray", ",", "policy_layer_sizes", ":", "Sequence", "[", "int", "]", "=", "(", "256", ",", "256", ",", "256", ")", ",", "critic_layer_sizes", ":", "Sequence", "[", "int", "]", "=", "(...
https://github.com/deepmind/acme/blob/9880719d9def1d87a194377b394a414a17d11064/examples/control/run_d4pg_gym.py#L68-L103
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/cgi.py
python
FieldStorage.__init__
(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0)
Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.
Constructor. Read multipart/* until last part.
[ "Constructor", ".", "Read", "multipart", "/", "*", "until", "last", "part", "." ]
def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ method = 'GET' self.keep_blank_values = keep_blank_values self.strict_parsing = strict_parsing if 'REQUEST_METHOD' in environ: method = environ['REQUEST_METHOD'].upper() self.qs_on_post = None if method == 'GET' or method == 'HEAD': if 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] elif sys.argv[1:]: qs = sys.argv[1] else: qs = "" fp = StringIO(qs) if headers is None: headers = {'content-type': "application/x-www-form-urlencoded"} if headers is None: headers = {} if method == 'POST': # Set default content-type for POST to what's traditional headers['content-type'] = "application/x-www-form-urlencoded" if 'CONTENT_TYPE' in environ: headers['content-type'] = environ['CONTENT_TYPE'] if 'QUERY_STRING' in environ: self.qs_on_post = environ['QUERY_STRING'] if 'CONTENT_LENGTH' in environ: headers['content-length'] = environ['CONTENT_LENGTH'] self.fp = fp or sys.stdin self.headers = headers self.outerboundary = outerboundary # Process content-disposition header cdisp, pdict = "", {} if 'content-disposition' in self.headers: cdisp, pdict = parse_header(self.headers['content-disposition']) self.disposition = cdisp self.disposition_options = pdict self.name = None if 'name' in pdict: self.name = pdict['name'] self.filename = None if 'filename' in pdict: self.filename = pdict['filename'] # Process content-type header # # Honor any existing content-type header. But if there is no # content-type header, use some sensible defaults. Assume # outerboundary is "" at the outer level, but something non-false # inside a multi-part. The default for an inner part is text/plain, # but for an outer part it should be urlencoded. This should catch # bogus clients which erroneously forget to include a content-type # header. # # See below for what we do if there does exist a content-type header, # but it happens to be something we don't understand. if 'content-type' in self.headers: ctype, pdict = parse_header(self.headers['content-type']) elif self.outerboundary or method != 'POST': ctype, pdict = "text/plain", {} else: ctype, pdict = 'application/x-www-form-urlencoded', {} self.type = ctype self.type_options = pdict self.innerboundary = "" if 'boundary' in pdict: self.innerboundary = pdict['boundary'] clen = -1 if 'content-length' in self.headers: try: clen = int(self.headers['content-length']) except ValueError: pass if maxlen and clen > maxlen: raise ValueError, 'Maximum content length exceeded' self.length = clen self.list = self.file = None self.done = 0 if ctype == 'application/x-www-form-urlencoded': self.read_urlencoded() elif ctype[:10] == 'multipart/': self.read_multi(environ, keep_blank_values, strict_parsing) else: self.read_single()
[ "def", "__init__", "(", "self", ",", "fp", "=", "None", ",", "headers", "=", "None", ",", "outerboundary", "=", "\"\"", ",", "environ", "=", "os", ".", "environ", ",", "keep_blank_values", "=", "0", ",", "strict_parsing", "=", "0", ")", ":", "method", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/cgi.py#L394-L508
yuantiku/fairseq-gec
10aafebc482706346f768e4f18a9813153cb1ecc
fairseq/models/transformer.py
python
TransformerDecoder.get_normalized_probs
(self, net_output, log_probs, sample)
return result
Get normalized probabilities (or log probs) from a net's output.
Get normalized probabilities (or log probs) from a net's output.
[ "Get", "normalized", "probabilities", "(", "or", "log", "probs", ")", "from", "a", "net", "s", "output", "." ]
def get_normalized_probs(self, net_output, log_probs, sample): """Get normalized probabilities (or log probs) from a net's output.""" if not self.copy_attention: return super().get_normalized_probs(net_output, log_probs, sample) logits = net_output[0].float() copy_attn = net_output[1]['copy_attn'] copy_attn = torch.clamp(copy_attn, 0, 1) # fix neg loss bug copy_alpha = net_output[1]['copy_alpha'] src_tokens = net_output[1]['src_tokens'] src_len = src_tokens.size(1) is_incre = len(logits.size()) == 2 if is_incre: logits = logits.unsqueeze(1) src_tokens = src_tokens.unsqueeze(1).repeat(1, logits.size(1), 1) scores = F.softmax(logits, dim=-1) ext_scores = torch.zeros(scores.size(0), scores.size(1), src_len).float() if src_tokens.device.type == 'cuda': ext_scores = ext_scores.cuda() composite_scores = torch.cat([scores, ext_scores], dim=-1) # set copy_alpha to 0.5 half of the time #if self.training and torch.rand(1).item() < 0.8: # copy_alpha = 0.5 composite_scores = copy_alpha * composite_scores copy_scores = (1 - copy_alpha) * copy_attn composite_scores.scatter_add_(-1, src_tokens, copy_scores) if is_incre: composite_scores = composite_scores.squeeze(1) if log_probs: result = torch.log(composite_scores + 1e-12) else: result = composite_scores return result
[ "def", "get_normalized_probs", "(", "self", ",", "net_output", ",", "log_probs", ",", "sample", ")", ":", "if", "not", "self", ".", "copy_attention", ":", "return", "super", "(", ")", ".", "get_normalized_probs", "(", "net_output", ",", "log_probs", ",", "sa...
https://github.com/yuantiku/fairseq-gec/blob/10aafebc482706346f768e4f18a9813153cb1ecc/fairseq/models/transformer.py#L634-L677
DingGuodong/LinuxBashShellScriptForOps
d5727b985f920292a10698a3c9751d5dff5fc1a3
functions/net/icmp/another-ping.py
python
Ping.send_one_ping
(self, current_socket)
return send_time
Send one ICMP ECHO_REQUEST
Send one ICMP ECHO_REQUEST
[ "Send", "one", "ICMP", "ECHO_REQUEST" ]
def send_one_ping(self, current_socket): """ Send one ICMP ECHO_REQUEST """ # Header is type (8), code (8), checksum (16), id (16), sequence (16) checksum = 0 # Make a dummy header with a 0 checksum. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number ) padBytes = [] startVal = 0x42 for i in range(startVal, startVal + self.packet_size): padBytes += [(i & 0xff)] # Keep chars in the 0-255 range data = bytes(padBytes) # Calculate the checksum on the data and the dummy header. checksum = calculate_checksum(header + data) # Checksum is in network order # Now that we have the right checksum, we put that in. It's just easier # to make up a new header than to stuff it into the dummy. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number ) packet = header + data send_time = default_timer() try: current_socket.sendto(packet, (self.destination, 1)) # Port number is irrelevant for ICMP except socket.error as e: self.response.output.append("General failure (%s)" % (e.args[1])) current_socket.close() return return send_time
[ "def", "send_one_ping", "(", "self", ",", "current_socket", ")", ":", "# Header is type (8), code (8), checksum (16), id (16), sequence (16)", "checksum", "=", "0", "# Make a dummy header with a 0 checksum.", "header", "=", "struct", ".", "pack", "(", "\"!BBHHH\"", ",", "IC...
https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/d5727b985f920292a10698a3c9751d5dff5fc1a3/functions/net/icmp/another-ping.py#L380-L418
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/utilities/iterables.py
python
_partition
(seq, vector, m=None)
return p
Return the partition of seq as specified by the partition vector. Examples ======== >>> from sympy.utilities.iterables import _partition >>> _partition('abcde', [1, 0, 1, 2, 0]) [['b', 'e'], ['a', 'c'], ['d']] Specifying the number of bins in the partition is optional: >>> _partition('abcde', [1, 0, 1, 2, 0], 3) [['b', 'e'], ['a', 'c'], ['d']] The output of _set_partitions can be passed as follows: >>> output = (3, [1, 0, 1, 2, 0]) >>> _partition('abcde', *output) [['b', 'e'], ['a', 'c'], ['d']] See Also ======== combinatorics.partitions.Partition.from_rgs()
Return the partition of seq as specified by the partition vector.
[ "Return", "the", "partition", "of", "seq", "as", "specified", "by", "the", "partition", "vector", "." ]
def _partition(seq, vector, m=None): """ Return the partition of seq as specified by the partition vector. Examples ======== >>> from sympy.utilities.iterables import _partition >>> _partition('abcde', [1, 0, 1, 2, 0]) [['b', 'e'], ['a', 'c'], ['d']] Specifying the number of bins in the partition is optional: >>> _partition('abcde', [1, 0, 1, 2, 0], 3) [['b', 'e'], ['a', 'c'], ['d']] The output of _set_partitions can be passed as follows: >>> output = (3, [1, 0, 1, 2, 0]) >>> _partition('abcde', *output) [['b', 'e'], ['a', 'c'], ['d']] See Also ======== combinatorics.partitions.Partition.from_rgs() """ if m is None: m = max(vector) + 1 elif type(vector) is int: # entered as m, vector vector, m = m, vector p = [[] for i in range(m)] for i, v in enumerate(vector): p[v].append(seq[i]) return p
[ "def", "_partition", "(", "seq", ",", "vector", ",", "m", "=", "None", ")", ":", "if", "m", "is", "None", ":", "m", "=", "max", "(", "vector", ")", "+", "1", "elif", "type", "(", "vector", ")", "is", "int", ":", "# entered as m, vector", "vector", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/utilities/iterables.py#L1380-L1415
caternuson/rpi-weather
3a326b35514aa12a1b4ec4b3f7d61a6dba479712
rpi_weather.py
python
RpiWeather.set_pixel
(self, x, y, matrix=0, value=1)
Set pixel at position x, y for specified matrix to the given value.
Set pixel at position x, y for specified matrix to the given value.
[ "Set", "pixel", "at", "position", "x", "y", "for", "specified", "matrix", "to", "the", "given", "value", "." ]
def set_pixel(self, x, y, matrix=0, value=1): """Set pixel at position x, y for specified matrix to the given value.""" if not self.is_valid_matrix(matrix): return self.matrix[matrix].set_pixel(x, y, value) self.matrix[matrix].write_display()
[ "def", "set_pixel", "(", "self", ",", "x", ",", "y", ",", "matrix", "=", "0", ",", "value", "=", "1", ")", ":", "if", "not", "self", ".", "is_valid_matrix", "(", "matrix", ")", ":", "return", "self", ".", "matrix", "[", "matrix", "]", ".", "set_p...
https://github.com/caternuson/rpi-weather/blob/3a326b35514aa12a1b4ec4b3f7d61a6dba479712/rpi_weather.py#L42-L47
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_internal/utils/ui.py
python
NonInteractiveSpinner._update
(self, status)
[]
def _update(self, status): assert not self._finished self._rate_limiter.reset() logger.info("%s: %s", self._message, status)
[ "def", "_update", "(", "self", ",", "status", ")", ":", "assert", "not", "self", ".", "_finished", "self", ".", "_rate_limiter", ".", "reset", "(", ")", "logger", ".", "info", "(", "\"%s: %s\"", ",", "self", ".", "_message", ",", "status", ")" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_internal/utils/ui.py#L381-L384
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/libmproxy/tnetstring.py
python
dumps
(value,encoding=None)
return "".join(q)
dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring.
dumps(object,encoding=None) -> string
[ "dumps", "(", "object", "encoding", "=", "None", ")", "-", ">", "string" ]
def dumps(value,encoding=None): """dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring. """ # This uses a deque to collect output fragments in reverse order, # then joins them together at the end. It's measurably faster # than creating all the intermediate strings. # If you're reading this to get a handle on the tnetstring format, # consider the _gdumps() function instead; it's a standard top-down # generator that's simpler to understand but much less efficient. q = deque() _rdumpq(q,0,value,encoding) return "".join(q)
[ "def", "dumps", "(", "value", ",", "encoding", "=", "None", ")", ":", "# This uses a deque to collect output fragments in reverse order,", "# then joins them together at the end. It's measurably faster", "# than creating all the intermediate strings.", "# If you're reading this to get...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/libmproxy/tnetstring.py#L81-L94
nabeel-oz/qlik-py-tools
09d0cd232fadcaa926bb11cebb37d5ae3051bc86
core/_sklearn.py
python
SKLearnForQlik.set_param_grid
(self)
return self.response
Set a parameter grid that will be used to optimize hyperparameters for the estimator. The parameters are used in the fit method to do a grid search.
Set a parameter grid that will be used to optimize hyperparameters for the estimator. The parameters are used in the fit method to do a grid search.
[ "Set", "a", "parameter", "grid", "that", "will", "be", "used", "to", "optimize", "hyperparameters", "for", "the", "estimator", ".", "The", "parameters", "are", "used", "in", "the", "fit", "method", "to", "do", "a", "grid", "search", "." ]
def set_param_grid(self): """ Set a parameter grid that will be used to optimize hyperparameters for the estimator. The parameters are used in the fit method to do a grid search. """ # Interpret the request data based on the expected row and column structure row_template = ['strData', 'strData', 'strData'] col_headers = ['model_name', 'estimator_args', 'grid_search_args'] # Create a Pandas Data Frame for the request data self.request_df = utils.request_df(self.request, row_template, col_headers) # Initialize the persistent model self.model = PersistentModel() # Get the model name from the request dataframe self.model.name = self.request_df.loc[0, 'model_name'] # Get the estimator's hyperparameter grid from the request dataframe param_grid = self.request_df.loc[:, 'estimator_args'] # Get the grid search arguments from the request dataframe grid_search_args = self.request_df.loc[0, 'grid_search_args'] # Get the model from cache or disk self._get_model() # Debug information is printed to the terminal and logs if the paramater debug = true if self.model.debug: self._print_log(3) self._set_grid_params(param_grid, grid_search_args) # Persist the model to disk self.model = self.model.save(self.model.name, self.path, overwrite=self.model.overwrite, compress=self.model.compress) # Update the cache to keep this model in memory self._update_cache() # Prepare the output message = [[self.model.name, 'Hyperparameter grid successfully saved to disk',\ time.strftime('%X %x %Z', time.localtime(self.model.state_timestamp))]] self.response = pd.DataFrame(message, columns=['model_name', 'result', 'time_stamp']) # Send the reponse table description to Qlik self._send_table_description("setup") # Debug information is printed to the terminal and logs if the paramater debug = true if self.model.debug: self._print_log(4) # Finally send the response return self.response
[ "def", "set_param_grid", "(", "self", ")", ":", "# Interpret the request data based on the expected row and column structure", "row_template", "=", "[", "'strData'", ",", "'strData'", ",", "'strData'", "]", "col_headers", "=", "[", "'model_name'", ",", "'estimator_args'", ...
https://github.com/nabeel-oz/qlik-py-tools/blob/09d0cd232fadcaa926bb11cebb37d5ae3051bc86/core/_sklearn.py#L273-L326
sdispater/orator
0666e522be914db285b6936e3c36801fc1a9c2e7
orator/orm/relations/morph_to.py
python
MorphTo.__init__
(self, query, parent, foreign_key, other_key, type, relation)
:type query: orator.orm.Builder :param parent: The parent model :type parent: Model :param query: :param parent: :param foreign_key: The foreign key of the parent model :type foreign_key: str :param other_key: The local key of the parent model :type other_key: str :param type: The morph type :type type: str :param relation: The relation name :type relation: str
:type query: orator.orm.Builder
[ ":", "type", "query", ":", "orator", ".", "orm", ".", "Builder" ]
def __init__(self, query, parent, foreign_key, other_key, type, relation): """ :type query: orator.orm.Builder :param parent: The parent model :type parent: Model :param query: :param parent: :param foreign_key: The foreign key of the parent model :type foreign_key: str :param other_key: The local key of the parent model :type other_key: str :param type: The morph type :type type: str :param relation: The relation name :type relation: str """ self._morph_type = type self._models = Collection() self._dictionary = {} self._with_trashed = False super(MorphTo, self).__init__(query, parent, foreign_key, other_key, relation)
[ "def", "__init__", "(", "self", ",", "query", ",", "parent", ",", "foreign_key", ",", "other_key", ",", "type", ",", "relation", ")", ":", "self", ".", "_morph_type", "=", "type", "self", ".", "_models", "=", "Collection", "(", ")", "self", ".", "_dict...
https://github.com/sdispater/orator/blob/0666e522be914db285b6936e3c36801fc1a9c2e7/orator/orm/relations/morph_to.py#L10-L38
lxdock/lxdock
f71006d130bc8b53603eea36a546003495437493
lxdock/guests/centos.py
python
CentosGuest.install_packages
(self, packages)
[]
def install_packages(self, packages): self.run(['yum', '-y', 'install'] + packages)
[ "def", "install_packages", "(", "self", ",", "packages", ")", ":", "self", ".", "run", "(", "[", "'yum'", ",", "'-y'", ",", "'install'", "]", "+", "packages", ")" ]
https://github.com/lxdock/lxdock/blob/f71006d130bc8b53603eea36a546003495437493/lxdock/guests/centos.py#L9-L10
mandiant/capa
c0851fc643793c012f5dd764482133c25c3216c8
capa/features/extractors/loops.py
python
has_loop
(edges, threshold=2)
return any(len(comp) >= threshold for comp in strongly_connected_components(g))
check if a list of edges representing a directed graph contains a loop args: edges: list of edge sets representing a directed graph i.e. [(1, 2), (2, 1)] threshold: min number of nodes contained in loop returns: bool
check if a list of edges representing a directed graph contains a loop
[ "check", "if", "a", "list", "of", "edges", "representing", "a", "directed", "graph", "contains", "a", "loop" ]
def has_loop(edges, threshold=2): """check if a list of edges representing a directed graph contains a loop args: edges: list of edge sets representing a directed graph i.e. [(1, 2), (2, 1)] threshold: min number of nodes contained in loop returns: bool """ g = networkx.DiGraph() g.add_edges_from(edges) return any(len(comp) >= threshold for comp in strongly_connected_components(g))
[ "def", "has_loop", "(", "edges", ",", "threshold", "=", "2", ")", ":", "g", "=", "networkx", ".", "DiGraph", "(", ")", "g", ".", "add_edges_from", "(", "edges", ")", "return", "any", "(", "len", "(", "comp", ")", ">=", "threshold", "for", "comp", "...
https://github.com/mandiant/capa/blob/c0851fc643793c012f5dd764482133c25c3216c8/capa/features/extractors/loops.py#L13-L25
cisco/mindmeld
809c36112e9ea8019fe29d54d136ca14eb4fd8db
mindmeld/components/_config.py
python
get_classifier_config
( clf_type, app_path=None, domain=None, intent=None, entity=None )
return _get_default_classifier_config(clf_type)
Returns the config for the specified classifier, with the following order of precedence. If the application contains a config.py file: - Return the response from the get_*_model_config function in config.py for the specified classifier type. E.g. `get_intent_model_config`. - If the function does not exist, or raise an exception, return the config specified by *_MODEL_CONFIG in config.py, e.g. INTENT_MODEL_CONFIG. Otherwise, use the MindMeld default config for the classifier type Args: clf_type (str): The type of the classifier. One of 'domain', 'intent', 'entity', 'entity_resolution', or 'role'. app_path (str, optional): The location of the app domain (str, optional): The domain of the classifier intent (str, optional): The intent of the classifier entity (str, optional): The entity type of the classifier Returns: dict: A classifier config
Returns the config for the specified classifier, with the following order of precedence.
[ "Returns", "the", "config", "for", "the", "specified", "classifier", "with", "the", "following", "order", "of", "precedence", "." ]
def get_classifier_config( clf_type, app_path=None, domain=None, intent=None, entity=None ): """Returns the config for the specified classifier, with the following order of precedence. If the application contains a config.py file: - Return the response from the get_*_model_config function in config.py for the specified classifier type. E.g. `get_intent_model_config`. - If the function does not exist, or raise an exception, return the config specified by *_MODEL_CONFIG in config.py, e.g. INTENT_MODEL_CONFIG. Otherwise, use the MindMeld default config for the classifier type Args: clf_type (str): The type of the classifier. One of 'domain', 'intent', 'entity', 'entity_resolution', or 'role'. app_path (str, optional): The location of the app domain (str, optional): The domain of the classifier intent (str, optional): The intent of the classifier entity (str, optional): The entity type of the classifier Returns: dict: A classifier config """ try: module_conf = _get_config_module(app_path) except (TypeError, OSError, IOError): logger.info( "No app configuration file found. Using default %s model configuration", clf_type, ) return _get_default_classifier_config(clf_type) func_name = { "intent": "get_intent_classifier_config", "entity": "get_entity_recognizer_config", "entity_resolution": "get_entity_resolver_config", "role": "get_role_classifier_config", }.get(clf_type) func_args = { "intent": ("domain",), "entity": ("domain", "intent"), "entity_resolution": ("domain", "intent", "entity"), "role": ("domain", "intent", "entity"), }.get(clf_type) if func_name: func = None try: func = getattr(module_conf, func_name) except AttributeError: try: func = getattr(module_conf, CONFIG_DEPRECATION_MAPPING[func_name]) msg = ( "%s config key is deprecated. Please use the equivalent %s config " "key" % (CONFIG_DEPRECATION_MAPPING[func_name], func_name) ) warnings.warn(msg, DeprecationWarning) except AttributeError: pass if func: try: raw_args = {"domain": domain, "intent": intent, "entity": entity} args = {k: raw_args[k] for k in func_args} return copy.deepcopy(func(**args)) except Exception as exc: # pylint: disable=broad-except # Note: this is intentionally broad -- provider could raise any exception logger.warning( "%r configuration provider raised exception: %s", clf_type, exc ) attr_name = { "domain": "DOMAIN_CLASSIFIER_CONFIG", "intent": "INTENT_CLASSIFIER_CONFIG", "entity": "ENTITY_RECOGNIZER_CONFIG", "entity_resolution": "ENTITY_RESOLVER_CONFIG", "role": "ROLE_CLASSIFIER_CONFIG", "question_answering": "QUESTION_ANSWERER_CONFIG", }[clf_type] try: return copy.deepcopy(getattr(module_conf, attr_name)) except AttributeError: try: result = copy.deepcopy( getattr(module_conf, CONFIG_DEPRECATION_MAPPING[attr_name]) ) msg = ( "%s config is deprecated. Please use the equivalent %s config " "key" % (CONFIG_DEPRECATION_MAPPING[attr_name], attr_name) ) warnings.warn(msg, DeprecationWarning) return result except AttributeError: logger.info("No %s model configuration set. Using default.", clf_type) return _get_default_classifier_config(clf_type)
[ "def", "get_classifier_config", "(", "clf_type", ",", "app_path", "=", "None", ",", "domain", "=", "None", ",", "intent", "=", "None", ",", "entity", "=", "None", ")", ":", "try", ":", "module_conf", "=", "_get_config_module", "(", "app_path", ")", "except...
https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/components/_config.py#L671-L771
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/multiprocessing/context.py
python
assert_spawning
(obj)
[]
def assert_spawning(obj): if get_spawning_popen() is None: raise RuntimeError( '%s objects should only be shared between processes' ' through inheritance' % type(obj).__name__ )
[ "def", "assert_spawning", "(", "obj", ")", ":", "if", "get_spawning_popen", "(", ")", "is", "None", ":", "raise", "RuntimeError", "(", "'%s objects should only be shared between processes'", "' through inheritance'", "%", "type", "(", "obj", ")", ".", "__name__", ")...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/multiprocessing/context.py#L357-L362
menpo/lsfm
0a256c6c59deebc97b47398b22f419c15bcb9c39
lsfm/_version.py
python
render_git_describe_long
(pieces)
return rendered
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
TAG-DISTANCE-gHEX[-dirty].
[ "TAG", "-", "DISTANCE", "-", "gHEX", "[", "-", "dirty", "]", "." ]
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered
[ "def", "render_git_describe_long", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "rendered", "+=", "\"-%d-g%s\"", "%", "(", "pieces", "[", "\"distance\"", "]", ",", "pieces", ...
https://github.com/menpo/lsfm/blob/0a256c6c59deebc97b47398b22f419c15bcb9c39/lsfm/_version.py#L392-L409
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/commonlib/datastore.py
python
read
(calc_id, mode='r', datadir=None, parentdir=None, read_parent=True)
return dstore.open(mode)
:param calc_id: calculation ID or filename :param mode: 'r' or 'w' :param datadir: the directory where to look :param parentdir: the datadir of the parent calculation :param read_parent: read the parent calculation if it is there :returns: the corresponding DataStore instance Read the datastore, if it exists and it is accessible.
:param calc_id: calculation ID or filename :param mode: 'r' or 'w' :param datadir: the directory where to look :param parentdir: the datadir of the parent calculation :param read_parent: read the parent calculation if it is there :returns: the corresponding DataStore instance
[ ":", "param", "calc_id", ":", "calculation", "ID", "or", "filename", ":", "param", "mode", ":", "r", "or", "w", ":", "param", "datadir", ":", "the", "directory", "where", "to", "look", ":", "param", "parentdir", ":", "the", "datadir", "of", "the", "par...
def read(calc_id, mode='r', datadir=None, parentdir=None, read_parent=True): """ :param calc_id: calculation ID or filename :param mode: 'r' or 'w' :param datadir: the directory where to look :param parentdir: the datadir of the parent calculation :param read_parent: read the parent calculation if it is there :returns: the corresponding DataStore instance Read the datastore, if it exists and it is accessible. """ if isinstance(calc_id, str): # pathname dstore = DataStore(calc_id, mode=mode) else: dstore = _read(calc_id, datadir, mode) try: hc_id = dstore['oqparam'].hazard_calculation_id except KeyError: # no oqparam hc_id = None if read_parent and hc_id and parentdir: dstore.ppath = os.path.join(parentdir, 'calc_%d.hdf5' % hc_id) dstore.parent = DataStore(dstore.ppath, mode='r') elif read_parent and hc_id: dstore.parent = _read(hc_id, datadir, 'r') dstore.ppath = dstore.parent.filename return dstore.open(mode)
[ "def", "read", "(", "calc_id", ",", "mode", "=", "'r'", ",", "datadir", "=", "None", ",", "parentdir", "=", "None", ",", "read_parent", "=", "True", ")", ":", "if", "isinstance", "(", "calc_id", ",", "str", ")", ":", "# pathname", "dstore", "=", "Dat...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/commonlib/datastore.py#L104-L129
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/html5lib/treebuilders/_base.py
python
Node.cloneNode
(self)
Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes
Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes
[ "Return", "a", "shallow", "copy", "of", "the", "current", "node", "i", ".", "e", ".", "a", "node", "with", "the", "same", "name", "and", "attributes", "but", "with", "no", "parent", "or", "child", "nodes" ]
def cloneNode(self): """Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes """ raise NotImplementedError
[ "def", "cloneNode", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/html5lib/treebuilders/_base.py#L86-L90
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
tools/manual/manual.py
python
TkGlobals.tk_faces_size
(self)
return self._tk_vars["faces_size"]
:class:`tkinter.StringVar`: The variable holding the currently selected Faces Viewer thumbnail size.
:class:`tkinter.StringVar`: The variable holding the currently selected Faces Viewer thumbnail size.
[ ":", "class", ":", "tkinter", ".", "StringVar", ":", "The", "variable", "holding", "the", "currently", "selected", "Faces", "Viewer", "thumbnail", "size", "." ]
def tk_faces_size(self): """ :class:`tkinter.StringVar`: The variable holding the currently selected Faces Viewer thumbnail size. """ return self._tk_vars["faces_size"]
[ "def", "tk_faces_size", "(", "self", ")", ":", "return", "self", ".", "_tk_vars", "[", "\"faces_size\"", "]" ]
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/tools/manual/manual.py#L513-L516
gregwchase/eyenet
1177eddfea761ddf7973fdcc6c46fdec9cc26f6e
src/eda.py
python
change_labels
(df, category)
return [1 if l > 0 else 0 for l in df[category]]
Changes the labels for a binary classification. Either the person has a degree of retinopathy, or they don't. INPUT df: Pandas DataFrame of the image name and labels category: column of the labels OUTPUT Column containing a binary classification of 0 or 1
Changes the labels for a binary classification. Either the person has a degree of retinopathy, or they don't.
[ "Changes", "the", "labels", "for", "a", "binary", "classification", ".", "Either", "the", "person", "has", "a", "degree", "of", "retinopathy", "or", "they", "don", "t", "." ]
def change_labels(df, category): ''' Changes the labels for a binary classification. Either the person has a degree of retinopathy, or they don't. INPUT df: Pandas DataFrame of the image name and labels category: column of the labels OUTPUT Column containing a binary classification of 0 or 1 ''' return [1 if l > 0 else 0 for l in df[category]]
[ "def", "change_labels", "(", "df", ",", "category", ")", ":", "return", "[", "1", "if", "l", ">", "0", "else", "0", "for", "l", "in", "df", "[", "category", "]", "]" ]
https://github.com/gregwchase/eyenet/blob/1177eddfea761ddf7973fdcc6c46fdec9cc26f6e/src/eda.py#L9-L21
renatoviolin/Question-Answering-Albert-Electra
8ca885c27c89af16bb2484ea0e6aeb960801259a
electra/util/utils.py
python
log_config
(config)
[]
def log_config(config): for key, value in sorted(config.__dict__.items()): log(key, value) log()
[ "def", "log_config", "(", "config", ")", ":", "for", "key", ",", "value", "in", "sorted", "(", "config", ".", "__dict__", ".", "items", "(", ")", ")", ":", "log", "(", "key", ",", "value", ")", "log", "(", ")" ]
https://github.com/renatoviolin/Question-Answering-Albert-Electra/blob/8ca885c27c89af16bb2484ea0e6aeb960801259a/electra/util/utils.py#L75-L78
tav/pylibs
3c16b843681f54130ee6a022275289cadb2f2a69
wafadmin/3rdparty/boost.py
python
check_boost
(self, *k, **kw)
return ret
This should be the main entry point - min_version - max_version - version - include_path - lib_path - lib - toolsettag - None or a regexp - threadingtag - None or a regexp - abitag - None or a regexp - versiontag - WARNING: you should rather use version or min_version/max_version - static - look for static libs (values: 'nostatic' or STATIC_NOSTATIC - ignore static libs (default) 'both' or STATIC_BOTH - find static libs, too 'onlystatic' or STATIC_ONLYSTATIC - find only static libs - score_version - score_abi - scores_threading - score_toolset * the scores are tuples (match_score, nomatch_score) match_score is the added to the score if the tag is matched nomatch_score is added when a tag is found and does not match - min_score
This should be the main entry point
[ "This", "should", "be", "the", "main", "entry", "point" ]
def check_boost(self, *k, **kw): """ This should be the main entry point - min_version - max_version - version - include_path - lib_path - lib - toolsettag - None or a regexp - threadingtag - None or a regexp - abitag - None or a regexp - versiontag - WARNING: you should rather use version or min_version/max_version - static - look for static libs (values: 'nostatic' or STATIC_NOSTATIC - ignore static libs (default) 'both' or STATIC_BOTH - find static libs, too 'onlystatic' or STATIC_ONLYSTATIC - find only static libs - score_version - score_abi - scores_threading - score_toolset * the scores are tuples (match_score, nomatch_score) match_score is the added to the score if the tag is matched nomatch_score is added when a tag is found and does not match - min_score """ if not self.env['CXX']: self.fatal('load a c++ compiler tool first, for example conf.check_tool("g++")') self.validate_boost(kw) ret = None try: if not kw.get('found_includes', None): self.check_message_1(kw.get('msg_includes', 'boost headers')) ret = self.find_boost_includes(kw) except Configure.ConfigurationError, e: if 'errmsg' in kw: self.check_message_2(kw['errmsg'], 'YELLOW') if 'mandatory' in kw: if Logs.verbose > 1: raise else: self.fatal('the configuration failed (see %r)' % self.log.name) else: if 'okmsg' in kw: self.check_message_2(kw.get('okmsg_includes', ret)) for lib in kw['lib']: self.check_message_1('library boost_'+lib) try: self.find_boost_library(lib, kw) except Configure.ConfigurationError, e: ret = False if 'errmsg' in kw: self.check_message_2(kw['errmsg'], 'YELLOW') if 'mandatory' in kw: if Logs.verbose > 1: raise else: self.fatal('the configuration failed (see %r)' % self.log.name) else: if 'okmsg' in kw: self.check_message_2(kw['okmsg']) return ret
[ "def", "check_boost", "(", "self", ",", "*", "k", ",", "*", "*", "kw", ")", ":", "if", "not", "self", ".", "env", "[", "'CXX'", "]", ":", "self", ".", "fatal", "(", "'load a c++ compiler tool first, for example conf.check_tool(\"g++\")'", ")", "self", ".", ...
https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/wafadmin/3rdparty/boost.py#L275-L341
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/widgets/collectionseditor.py
python
BaseTableView.dragEnterEvent
(self, event)
Allow user to drag files
Allow user to drag files
[ "Allow", "user", "to", "drag", "files" ]
def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore()
[ "def", "dragEnterEvent", "(", "self", ",", "event", ")", ":", "if", "mimedata2url", "(", "event", ".", "mimeData", "(", ")", ")", ":", "event", ".", "accept", "(", ")", "else", ":", "event", ".", "ignore", "(", ")" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/widgets/collectionseditor.py#L865-L870
adamrehn/ue4-docker
4ad926620fb7ee86dbaa2b80c22a78ecdf5e5287
ue4docker/infrastructure/Logger.py
python
Logger.error
(self, output, newline=False)
Prints information about an error that has occurred
Prints information about an error that has occurred
[ "Prints", "information", "about", "an", "error", "that", "has", "occurred" ]
def error(self, output, newline=False): """ Prints information about an error that has occurred """ self._print("red", output, newline)
[ "def", "error", "(", "self", ",", "output", ",", "newline", "=", "False", ")", ":", "self", ".", "_print", "(", "\"red\"", ",", "output", ",", "newline", ")" ]
https://github.com/adamrehn/ue4-docker/blob/4ad926620fb7ee86dbaa2b80c22a78ecdf5e5287/ue4docker/infrastructure/Logger.py#L19-L23
Tencent/bk-bcs-saas
2b437bf2f5fd5ce2078f7787c3a12df609f7679d
bcs-app/backend/web_console/utils.py
python
clean_bash_escape
(text)
return text
删除bash转义字符
删除bash转义字符
[ "删除bash转义字符" ]
def clean_bash_escape(text): """删除bash转义字符""" # 删除转移字符 text = constants.ANSI_ESCAPE.sub('', text) # 再删除\x01字符 text = text.replace(chr(constants.STDOUT_CHANNEL), '') return text
[ "def", "clean_bash_escape", "(", "text", ")", ":", "# 删除转移字符", "text", "=", "constants", ".", "ANSI_ESCAPE", ".", "sub", "(", "''", ",", "text", ")", "# 再删除\\x01字符", "text", "=", "text", ".", "replace", "(", "chr", "(", "constants", ".", "STDOUT_CHANNEL", ...
https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/web_console/utils.py#L80-L86
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/base/stdmods.py
python
python_modules
()
return result
[]
def python_modules(): result = set() lib_path = _stdlib_path() if os.path.exists(lib_path): for name in os.listdir(lib_path): path = os.path.join(lib_path, name) if os.path.isdir(path): if '-' not in name: result.add(name) else: if name.endswith('.py'): result.add(name[:-3]) return result
[ "def", "python_modules", "(", ")", ":", "result", "=", "set", "(", ")", "lib_path", "=", "_stdlib_path", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "lib_path", ")", ":", "for", "name", "in", "os", ".", "listdir", "(", "lib_path", ")", "...
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/base/stdmods.py#L16-L28
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/conch/ssh/userauth.py
python
SSHUserAuthServer._ebBadAuth
(self, reason)
The final errback in the authentication chain. If the reason is error.IgnoreAuthentication, we simply return; the authentication method has sent its own response. Otherwise, send a failure message and (if the method is not 'none') increment the number of login attempts. @type reason: L{twisted.python.failure.Failure}
The final errback in the authentication chain. If the reason is error.IgnoreAuthentication, we simply return; the authentication method has sent its own response. Otherwise, send a failure message and (if the method is not 'none') increment the number of login attempts.
[ "The", "final", "errback", "in", "the", "authentication", "chain", ".", "If", "the", "reason", "is", "error", ".", "IgnoreAuthentication", "we", "simply", "return", ";", "the", "authentication", "method", "has", "sent", "its", "own", "response", ".", "Otherwis...
def _ebBadAuth(self, reason): """ The final errback in the authentication chain. If the reason is error.IgnoreAuthentication, we simply return; the authentication method has sent its own response. Otherwise, send a failure message and (if the method is not 'none') increment the number of login attempts. @type reason: L{twisted.python.failure.Failure} """ if reason.check(error.IgnoreAuthentication): return if self.method != 'none': log.msg('%s failed auth %s' % (self.user, self.method)) if reason.check(UnauthorizedLogin): log.msg('unauthorized login: %s' % reason.getErrorMessage()) elif reason.check(error.ConchError): log.msg('reason: %s' % reason.getErrorMessage()) else: log.msg(reason.getTraceback()) self.loginAttempts += 1 if self.loginAttempts > self.attemptsBeforeDisconnect: self.transport.sendDisconnect( transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE, 'too many bad auths') return self.transport.sendPacket( MSG_USERAUTH_FAILURE, NS(','.join(self.supportedAuthentications)) + '\x00')
[ "def", "_ebBadAuth", "(", "self", ",", "reason", ")", ":", "if", "reason", ".", "check", "(", "error", ".", "IgnoreAuthentication", ")", ":", "return", "if", "self", ".", "method", "!=", "'none'", ":", "log", ".", "msg", "(", "'%s failed auth %s'", "%", ...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/conch/ssh/userauth.py#L222-L250
AntonKueltz/fastecdsa
9bf593cd29cc497051b45f7271e95fd019e917bd
fastecdsa/point.py
python
Point.__rmul__
(self, scalar: int)
return self.__mul__(scalar)
Multiply a :class:`Point` on an elliptic curve by an integer. Args: | self (:class:`Point`): a point :math:`P` on the curve | other (long): an integer :math:`d \in \mathbb{Z_q}` where :math:`q` is the order of the curve that :math:`P` is on Returns: :class:`Point`: A point :math:`R` such that :math:`R = d * P`
Multiply a :class:`Point` on an elliptic curve by an integer.
[ "Multiply", "a", ":", "class", ":", "Point", "on", "an", "elliptic", "curve", "by", "an", "integer", "." ]
def __rmul__(self, scalar: int): """Multiply a :class:`Point` on an elliptic curve by an integer. Args: | self (:class:`Point`): a point :math:`P` on the curve | other (long): an integer :math:`d \in \mathbb{Z_q}` where :math:`q` is the order of the curve that :math:`P` is on Returns: :class:`Point`: A point :math:`R` such that :math:`R = d * P` """ return self.__mul__(scalar)
[ "def", "__rmul__", "(", "self", ",", "scalar", ":", "int", ")", ":", "return", "self", ".", "__mul__", "(", "scalar", ")" ]
https://github.com/AntonKueltz/fastecdsa/blob/9bf593cd29cc497051b45f7271e95fd019e917bd/fastecdsa/point.py#L163-L174
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/dominate/dom_tag.py
python
dom_tag.get
(self, tag=None, **kwargs)
return results
Recursively searches children for tags of a certain type with matching attributes.
Recursively searches children for tags of a certain type with matching attributes.
[ "Recursively", "searches", "children", "for", "tags", "of", "a", "certain", "type", "with", "matching", "attributes", "." ]
def get(self, tag=None, **kwargs): ''' Recursively searches children for tags of a certain type with matching attributes. ''' # Stupid workaround since we can not use dom_tag in the method declaration if tag is None: tag = dom_tag attrs = [(dom_tag.clean_attribute(attr), value) for attr, value in kwargs.items()] results = [] for child in self.children: if (isinstance(tag, basestring) and type(child).__name__ == tag) or \ (not isinstance(tag, basestring) and isinstance(child, tag)): if all(child.attributes.get(attribute) == value for attribute, value in attrs): # If the child is of correct type and has all attributes and values # in kwargs add as a result results.append(child) if isinstance(child, dom_tag): # If the child is a dom_tag extend the search down through its children results.extend(child.get(tag, **kwargs)) return results
[ "def", "get", "(", "self", ",", "tag", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Stupid workaround since we can not use dom_tag in the method declaration", "if", "tag", "is", "None", ":", "tag", "=", "dom_tag", "attrs", "=", "[", "(", "dom_tag", ".", ...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/dominate/dom_tag.py#L223-L247
BindsNET/bindsnet
f2eabd77793831c1391fccf5b22e2e4e4564ae7c
bindsnet/network/nodes.py
python
CurrentLIFNodes.set_batch_size
(self, batch_size)
Sets mini-batch size. Called when layer is added to a network. :param batch_size: Mini-batch size.
Sets mini-batch size. Called when layer is added to a network.
[ "Sets", "mini", "-", "batch", "size", ".", "Called", "when", "layer", "is", "added", "to", "a", "network", "." ]
def set_batch_size(self, batch_size) -> None: # language=rst """ Sets mini-batch size. Called when layer is added to a network. :param batch_size: Mini-batch size. """ super().set_batch_size(batch_size=batch_size) self.v = self.rest * torch.ones(batch_size, *self.shape, device=self.v.device) self.i = torch.zeros_like(self.v, device=self.i.device) self.refrac_count = torch.zeros_like(self.v, device=self.refrac_count.device)
[ "def", "set_batch_size", "(", "self", ",", "batch_size", ")", "->", "None", ":", "# language=rst", "super", "(", ")", ".", "set_batch_size", "(", "batch_size", "=", "batch_size", ")", "self", ".", "v", "=", "self", ".", "rest", "*", "torch", ".", "ones",...
https://github.com/BindsNET/bindsnet/blob/f2eabd77793831c1391fccf5b22e2e4e4564ae7c/bindsnet/network/nodes.py#L816-L826
nkolot/GraphCMR
4e57dca4e9da305df99383ea6312e2b3de78c321
train/trainer.py
python
Trainer.train_summaries
(self, input_batch, pred_vertices, pred_vertices_smpl, pred_camera, pred_keypoints_2d, pred_keypoints_2d_smpl, loss_shape, loss_shape_smpl, loss_keypoints, loss_keypoints_smpl, loss_keypoints_3d, loss_keypoints_3d_smpl, loss_regr_pose, loss_regr_betas, loss)
Tensorboard logging.
Tensorboard logging.
[ "Tensorboard", "logging", "." ]
def train_summaries(self, input_batch, pred_vertices, pred_vertices_smpl, pred_camera, pred_keypoints_2d, pred_keypoints_2d_smpl, loss_shape, loss_shape_smpl, loss_keypoints, loss_keypoints_smpl, loss_keypoints_3d, loss_keypoints_3d_smpl, loss_regr_pose, loss_regr_betas, loss): """Tensorboard logging.""" gt_keypoints_2d = input_batch['keypoints'].cpu().numpy() rend_imgs = [] rend_imgs_smpl = [] batch_size = pred_vertices.shape[0] # Do visualization for the first 4 images of the batch for i in range(min(batch_size, 4)): img = input_batch['img_orig'][i].cpu().numpy().transpose(1,2,0) # Get LSP keypoints from the full list of keypoints gt_keypoints_2d_ = gt_keypoints_2d[i, self.to_lsp] pred_keypoints_2d_ = pred_keypoints_2d.cpu().numpy()[i, self.to_lsp] pred_keypoints_2d_smpl_ = pred_keypoints_2d_smpl.cpu().numpy()[i, self.to_lsp] # Get GraphCNN and SMPL vertices for the particular example vertices = pred_vertices[i].cpu().numpy() vertices_smpl = pred_vertices_smpl[i].cpu().numpy() cam = pred_camera[i].cpu().numpy() cam = pred_camera[i].cpu().numpy() # Visualize reconstruction and detected pose rend_img = visualize_reconstruction(img, self.options.img_res, gt_keypoints_2d_, vertices, pred_keypoints_2d_, cam, self.renderer) rend_img_smpl = visualize_reconstruction(img, self.options.img_res, gt_keypoints_2d_, vertices_smpl, pred_keypoints_2d_smpl_, cam, self.renderer) rend_img = rend_img.transpose(2,0,1) rend_img_smpl = rend_img_smpl.transpose(2,0,1) rend_imgs.append(torch.from_numpy(rend_img)) rend_imgs_smpl.append(torch.from_numpy(rend_img_smpl)) rend_imgs = make_grid(rend_imgs, nrow=1) rend_imgs_smpl = make_grid(rend_imgs_smpl, nrow=1) # Save results in Tensorboard self.summary_writer.add_image('imgs', rend_imgs, self.step_count) self.summary_writer.add_image('imgs_smpl', rend_imgs_smpl, self.step_count) self.summary_writer.add_scalar('loss_shape', loss_shape, self.step_count) self.summary_writer.add_scalar('loss_shape_smpl', loss_shape_smpl, self.step_count) self.summary_writer.add_scalar('loss_regr_pose', loss_regr_pose, self.step_count) self.summary_writer.add_scalar('loss_regr_betas', loss_regr_betas, self.step_count) self.summary_writer.add_scalar('loss_keypoints', loss_keypoints, self.step_count) self.summary_writer.add_scalar('loss_keypoints_smpl', loss_keypoints_smpl, self.step_count) self.summary_writer.add_scalar('loss_keypoints_3d', loss_keypoints_3d, self.step_count) self.summary_writer.add_scalar('loss_keypoints_3d_smpl', loss_keypoints_3d_smpl, self.step_count) self.summary_writer.add_scalar('loss', loss, self.step_count)
[ "def", "train_summaries", "(", "self", ",", "input_batch", ",", "pred_vertices", ",", "pred_vertices_smpl", ",", "pred_camera", ",", "pred_keypoints_2d", ",", "pred_keypoints_2d_smpl", ",", "loss_shape", ",", "loss_shape_smpl", ",", "loss_keypoints", ",", "loss_keypoint...
https://github.com/nkolot/GraphCMR/blob/4e57dca4e9da305df99383ea6312e2b3de78c321/train/trainer.py#L191-L236
PolyAI-LDN/conversational-datasets
50f626ad0d0e825835bd054f6a58006afa95a8e5
opensubtitles/create_data.py
python
run
(argv=None)
Run the beam pipeline.
Run the beam pipeline.
[ "Run", "the", "beam", "pipeline", "." ]
def run(argv=None): """Run the beam pipeline.""" args, pipeline_args = _parse_args(argv) pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True p = beam.Pipeline(options=pipeline_options) sentence_files_match = FileSystems.match([args.sentence_files])[0] sentence_files = [ file_metadata.path for file_metadata in sentence_files_match.metadata_list] logging.info("Reading %i files from %s.", len(sentence_files), args.sentence_files) assert len(sentence_files) > 0 sentence_files = p | beam.Create(sentence_files) examples = sentence_files | "create examples" >> beam.FlatMap( partial(_create_examples_from_file, min_length=args.min_length, max_length=args.max_length, num_extra_contexts=args.num_extra_contexts) ) examples = _shuffle_examples(examples) examples |= "split train and test" >> beam.ParDo( _TrainTestSplitFn(args.train_split)).with_outputs( _TrainTestSplitFn.TEST_TAG, _TrainTestSplitFn.TRAIN_TAG) if args.dataset_format == _JSON_FORMAT: write_sink = WriteToText file_name_suffix = ".json" serialize_fn = json.dumps else: assert args.dataset_format == _TF_FORMAT write_sink = WriteToTFRecord file_name_suffix = ".tfrecord" serialize_fn = _features_to_serialized_tf_example for name, tag in [("train", _TrainTestSplitFn.TRAIN_TAG), ("test", _TrainTestSplitFn.TEST_TAG)]: serialized_examples = examples[tag] | ( "serialize {} examples".format(name) >> beam.Map(serialize_fn)) ( serialized_examples | ("write " + name) >> write_sink( os.path.join(args.output_dir, name), file_name_suffix=file_name_suffix, num_shards=args.num_shards_train, ) ) result = p.run() result.wait_until_finish()
[ "def", "run", "(", "argv", "=", "None", ")", ":", "args", ",", "pipeline_args", "=", "_parse_args", "(", "argv", ")", "pipeline_options", "=", "PipelineOptions", "(", "pipeline_args", ")", "pipeline_options", ".", "view_as", "(", "SetupOptions", ")", ".", "s...
https://github.com/PolyAI-LDN/conversational-datasets/blob/50f626ad0d0e825835bd054f6a58006afa95a8e5/opensubtitles/create_data.py#L215-L269
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/billiard/reduction.py
python
_reduce_method_descriptor
(m)
return getattr, (m.__objclass__, m.__name__)
[]
def _reduce_method_descriptor(m): return getattr, (m.__objclass__, m.__name__)
[ "def", "_reduce_method_descriptor", "(", "m", ")", ":", "return", "getattr", ",", "(", "m", ".", "__objclass__", ",", "m", ".", "__name__", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/billiard/reduction.py#L257-L258
arviz-devs/arviz
17b1a48b577ba9776a31e7e57a8a8af63e826901
arviz/data/io_dict.py
python
DictConverter.sample_stats_prior_to_xarray
(self)
return dict_to_dataset( data, library=None, coords=self.coords, dims=self.dims, attrs=self.attrs, index_origin=self.index_origin, )
Convert sample_stats_prior samples to xarray.
Convert sample_stats_prior samples to xarray.
[ "Convert", "sample_stats_prior", "samples", "to", "xarray", "." ]
def sample_stats_prior_to_xarray(self): """Convert sample_stats_prior samples to xarray.""" data = self.sample_stats_prior if not isinstance(data, dict): raise TypeError("DictConverter.sample_stats_prior is not a dictionary") return dict_to_dataset( data, library=None, coords=self.coords, dims=self.dims, attrs=self.attrs, index_origin=self.index_origin, )
[ "def", "sample_stats_prior_to_xarray", "(", "self", ")", ":", "data", "=", "self", ".", "sample_stats_prior", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"DictConverter.sample_stats_prior is not a dictionary\"", ")", "...
https://github.com/arviz-devs/arviz/blob/17b1a48b577ba9776a31e7e57a8a8af63e826901/arviz/data/io_dict.py#L256-L269
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/train_extensions/roc_auc.py
python
RocAucChannel.setup
(self, model, dataset, algorithm)
Add ROC AUC channels for monitoring dataset(s) to model.monitor. Parameters ---------- model : object The model being trained. dataset : object Training dataset. algorithm : object Training algorithm.
Add ROC AUC channels for monitoring dataset(s) to model.monitor.
[ "Add", "ROC", "AUC", "channels", "for", "monitoring", "dataset", "(", "s", ")", "to", "model", ".", "monitor", "." ]
def setup(self, model, dataset, algorithm): """ Add ROC AUC channels for monitoring dataset(s) to model.monitor. Parameters ---------- model : object The model being trained. dataset : object Training dataset. algorithm : object Training algorithm. """ m_space, m_source = model.get_monitoring_data_specs() state, target = m_space.make_theano_batch() y = T.argmax(target, axis=1) y_hat = model.fprop(state)[:, self.positive_class_index] # one vs. the rest if self.negative_class_index is None: y = T.eq(y, self.positive_class_index) # one vs. one else: pos = T.eq(y, self.positive_class_index) neg = T.eq(y, self.negative_class_index) keep = T.add(pos, neg).nonzero() y = T.eq(y[keep], self.positive_class_index) y_hat = y_hat[keep] roc_auc = RocAucScoreOp(self.channel_name_suffix)(y, y_hat) roc_auc = T.cast(roc_auc, config.floatX) for dataset_name, dataset in algorithm.monitoring_dataset.items(): if dataset_name: channel_name = '{0}_{1}'.format(dataset_name, self.channel_name_suffix) else: channel_name = self.channel_name_suffix model.monitor.add_channel(name=channel_name, ipt=(state, target), val=roc_auc, data_specs=(m_space, m_source), dataset=dataset)
[ "def", "setup", "(", "self", ",", "model", ",", "dataset", ",", "algorithm", ")", ":", "m_space", ",", "m_source", "=", "model", ".", "get_monitoring_data_specs", "(", ")", "state", ",", "target", "=", "m_space", ".", "make_theano_batch", "(", ")", "y", ...
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/train_extensions/roc_auc.py#L101-L144
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_openshift_3.2/build/ansible/oadm_project.py
python
main
()
ansible oc module for project
ansible oc module for project
[ "ansible", "oc", "module", "for", "project" ]
def main(): ''' ansible oc module for project ''' module = AnsibleModule( argument_spec=dict( kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'absent', 'list']), debug=dict(default=False, type='bool'), name=dict(default=None, require=True, type='str'), display_name=dict(default=None, type='str'), node_selector=dict(default=None, type='str'), description=dict(default=None, type='str'), admin=dict(default=None, type='str'), admin_role=dict(default=None, type='str'), ), supports_check_mode=True, ) pconfig = ProjectConfig(module.params['name'], module.params['name'], module.params['kubeconfig'], {'admin': {'value': module.params['admin'], 'include': True}, 'admin_role': {'value': module.params['admin_role'], 'include': True}, 'description': {'value': module.params['description'], 'include': True}, 'display_name': {'value': module.params['display_name'], 'include': True}, 'node_selector': {'value': module.params['node_selector'], 'include': True}, }) oadm_project = OadmProject(pconfig, verbose=module.params['debug']) state = module.params['state'] api_rval = oadm_project.get() ##### # Get ##### if state == 'list': module.exit_json(changed=False, results=api_rval['results'], state="list") ######## # Delete ######## if state == 'absent': if oadm_project.exists(): if module.check_mode: module.exit_json(changed=False, msg='Would have performed a delete.') api_rval = oadm_project.delete() module.exit_json(changed=True, results=api_rval, state="absent") module.exit_json(changed=False, state="absent") if state == 'present': ######## # Create ######## if not oadm_project.exists(): if module.check_mode: module.exit_json(changed=False, msg='Would have performed a create.') # Create it here api_rval = oadm_project.create() # return the created object api_rval = oadm_project.get() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) module.exit_json(changed=True, results=api_rval, state="present") ######## # Update ######## if oadm_project.needs_update(): api_rval = oadm_project.update() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) # return the created object api_rval = oadm_project.get() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) module.exit_json(changed=True, results=api_rval, state="present") module.exit_json(changed=False, results=api_rval, state="present") module.exit_json(failed=True, changed=False, results='Unknown state passed. %s' % state, state="unknown")
[ "def", "main", "(", ")", ":", "module", "=", "AnsibleModule", "(", "argument_spec", "=", "dict", "(", "kubeconfig", "=", "dict", "(", "default", "=", "'/etc/origin/master/admin.kubeconfig'", ",", "type", "=", "'str'", ")", ",", "state", "=", "dict", "(", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/build/ansible/oadm_project.py#L3-L102
NTMC-Community/MatchZoo-py
0e5c04e1e948aa9277abd5c85ff99d9950d8527f
matchzoo/trainers/trainer.py
python
Trainer._run_scheduler
(self)
Run scheduler.
Run scheduler.
[ "Run", "scheduler", "." ]
def _run_scheduler(self): """Run scheduler.""" if self._scheduler: self._scheduler.step()
[ "def", "_run_scheduler", "(", "self", ")", ":", "if", "self", ".", "_scheduler", ":", "self", ".", "_scheduler", ".", "step", "(", ")" ]
https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/trainers/trainer.py#L210-L213
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/idlelib/macosxSupport.py
python
overrideRootMenu
(root, flist)
Replace the Tk root menu by something that is more appropriate for IDLE with an Aqua Tk.
Replace the Tk root menu by something that is more appropriate for IDLE with an Aqua Tk.
[ "Replace", "the", "Tk", "root", "menu", "by", "something", "that", "is", "more", "appropriate", "for", "IDLE", "with", "an", "Aqua", "Tk", "." ]
def overrideRootMenu(root, flist): """ Replace the Tk root menu by something that is more appropriate for IDLE with an Aqua Tk. """ # The menu that is attached to the Tk root (".") is also used by AquaTk for # all windows that don't specify a menu of their own. The default menubar # contains a number of menus, none of which are appropriate for IDLE. The # Most annoying of those is an 'About Tck/Tk...' menu in the application # menu. # # This function replaces the default menubar by a mostly empty one, it # should only contain the correct application menu and the window menu. # # Due to a (mis-)feature of TkAqua the user will also see an empty Help # menu. from tkinter import Menu from idlelib import Bindings from idlelib import WindowList closeItem = Bindings.menudefs[0][1][-2] # Remove the last 3 items of the file menu: a separator, close window and # quit. Close window will be reinserted just above the save item, where # it should be according to the HIG. Quit is in the application menu. del Bindings.menudefs[0][1][-3:] Bindings.menudefs[0][1].insert(6, closeItem) # Remove the 'About' entry from the help menu, it is in the application # menu del Bindings.menudefs[-1][1][0:2] # Remove the 'Configure Idle' entry from the options menu, it is in the # application menu as 'Preferences' del Bindings.menudefs[-2][1][0] menubar = Menu(root) root.configure(menu=menubar) menudict = {} menudict['windows'] = menu = Menu(menubar, name='windows', tearoff=0) menubar.add_cascade(label='Window', menu=menu, underline=0) def postwindowsmenu(menu=menu): end = menu.index('end') if end is None: end = -1 if end > 0: menu.delete(0, end) WindowList.add_windows_to_menu(menu) WindowList.register_callback(postwindowsmenu) def about_dialog(event=None): "Handle Help 'About IDLE' event." # Synchronize with EditorWindow.EditorWindow.about_dialog. from idlelib import aboutDialog aboutDialog.AboutDialog(root, 'About IDLE') def config_dialog(event=None): "Handle Options 'Configure IDLE' event." # Synchronize with EditorWindow.EditorWindow.config_dialog. from idlelib import configDialog # Ensure that the root object has an instance_dict attribute, # mirrors code in EditorWindow (although that sets the attribute # on an EditorWindow instance that is then passed as the first # argument to ConfigDialog) root.instance_dict = flist.inversedict configDialog.ConfigDialog(root, 'Settings') def help_dialog(event=None): "Handle Help 'IDLE Help' event." # Synchronize with EditorWindow.EditorWindow.help_dialog. from idlelib import help help.show_idlehelp(root) root.bind('<<about-idle>>', about_dialog) root.bind('<<open-config-dialog>>', config_dialog) root.createcommand('::tk::mac::ShowPreferences', config_dialog) if flist: root.bind('<<close-all-windows>>', flist.close_all_callback) # The binding above doesn't reliably work on all versions of Tk # on MacOSX. Adding command definition below does seem to do the # right thing for now. root.createcommand('exit', flist.close_all_callback) if isCarbonTk(): # for Carbon AquaTk, replace the default Tk apple menu menudict['application'] = menu = Menu(menubar, name='apple', tearoff=0) menubar.add_cascade(label='IDLE', menu=menu) Bindings.menudefs.insert(0, ('application', [ ('About IDLE', '<<about-idle>>'), None, ])) tkversion = root.tk.eval('info patchlevel') if tuple(map(int, tkversion.split('.'))) < (8, 4, 14): # for earlier AquaTk versions, supply a Preferences menu item Bindings.menudefs[0][1].append( ('_Preferences....', '<<open-config-dialog>>'), ) if isCocoaTk(): # replace default About dialog with About IDLE one root.createcommand('tkAboutDialog', about_dialog) # replace default "Help" item in Help menu root.createcommand('::tk::mac::ShowHelp', help_dialog) # remove redundant "IDLE Help" from menu del Bindings.menudefs[-1][1][0]
[ "def", "overrideRootMenu", "(", "root", ",", "flist", ")", ":", "# The menu that is attached to the Tk root (\".\") is also used by AquaTk for", "# all windows that don't specify a menu of their own. The default menubar", "# contains a number of menus, none of which are appropriate for IDLE. The...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/idlelib/macosxSupport.py#L109-L217
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/system/device.py
python
Device.tcpip_hostname
(self)
return val.value.decode('ascii')
str: Indicates the IPv4 hostname of the device.
str: Indicates the IPv4 hostname of the device.
[ "str", ":", "Indicates", "the", "IPv4", "hostname", "of", "the", "device", "." ]
def tcpip_hostname(self): """ str: Indicates the IPv4 hostname of the device. """ cfunc = lib_importer.windll.DAQmxGetDevTCPIPHostname if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ ctypes_byte_str, ctypes.c_char_p, ctypes.c_uint] temp_size = 0 while True: val = ctypes.create_string_buffer(temp_size) size_or_code = cfunc( self._name, val, temp_size) if is_string_buffer_too_small(size_or_code): # Buffer size must have changed between calls; check again. temp_size = 0 elif size_or_code > 0 and temp_size == 0: # Buffer size obtained, use to retrieve data. temp_size = size_or_code else: break check_for_error(size_or_code) return val.value.decode('ascii')
[ "def", "tcpip_hostname", "(", "self", ")", ":", "cfunc", "=", "lib_importer", ".", "windll", ".", "DAQmxGetDevTCPIPHostname", "if", "cfunc", ".", "argtypes", "is", "None", ":", "with", "cfunc", ".", "arglock", ":", "if", "cfunc", ".", "argtypes", "is", "No...
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/system/device.py#L2084-L2113
facebookarchive/augmented-traffic-control
575720854de4f609b6209028857ec8d81efcf654
atc/atc_thrift/atc_thrift/Atcd.py
python
Client.getCurrentShaping
(self, device)
return self.recv_getCurrentShaping()
Parameters: - device
Parameters: - device
[ "Parameters", ":", "-", "device" ]
def getCurrentShaping(self, device): """ Parameters: - device """ self.send_getCurrentShaping(device) return self.recv_getCurrentShaping()
[ "def", "getCurrentShaping", "(", "self", ",", "device", ")", ":", "self", ".", "send_getCurrentShaping", "(", "device", ")", "return", "self", ".", "recv_getCurrentShaping", "(", ")" ]
https://github.com/facebookarchive/augmented-traffic-control/blob/575720854de4f609b6209028857ec8d81efcf654/atc/atc_thrift/atc_thrift/Atcd.py#L182-L188
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/chardet/chardistribution.py
python
EUCJPDistributionAnalysis.get_order
(self, byte_str)
[]
def get_order(self, byte_str): # for euc-JP encoding, we are interested # first byte range: 0xa0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that char = byte_str[0] if char >= 0xA0: return 94 * (char - 0xA1) + byte_str[1] - 0xa1 else: return -1
[ "def", "get_order", "(", "self", ",", "byte_str", ")", ":", "# for euc-JP encoding, we are interested", "# first byte range: 0xa0 -- 0xfe", "# second byte range: 0xa1 -- 0xfe", "# no validation needed here. State machine has done that", "char", "=", "byte_str", "[", "0", "]", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/chardet/chardistribution.py#L224-L233
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/cloudsearch2/layer2.py
python
Layer2.list_domains
(self, domain_names=None)
return [Domain(self.layer1, data) for data in domain_data]
Return a list of objects for each domain defined in the current account. :rtype: list of :class:`boto.cloudsearch2.domain.Domain`
Return a list of objects for each domain defined in the current account. :rtype: list of :class:`boto.cloudsearch2.domain.Domain`
[ "Return", "a", "list", "of", "objects", "for", "each", "domain", "defined", "in", "the", "current", "account", ".", ":", "rtype", ":", "list", "of", ":", "class", ":", "boto", ".", "cloudsearch2", ".", "domain", ".", "Domain" ]
def list_domains(self, domain_names=None): """ Return a list of objects for each domain defined in the current account. :rtype: list of :class:`boto.cloudsearch2.domain.Domain` """ domain_data = self.layer1.describe_domains(domain_names) domain_data = (domain_data['DescribeDomainsResponse'] ['DescribeDomainsResult'] ['DomainStatusList']) return [Domain(self.layer1, data) for data in domain_data]
[ "def", "list_domains", "(", "self", ",", "domain_names", "=", "None", ")", ":", "domain_data", "=", "self", ".", "layer1", ".", "describe_domains", "(", "domain_names", ")", "domain_data", "=", "(", "domain_data", "[", "'DescribeDomainsResponse'", "]", "[", "'...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/cloudsearch2/layer2.py#L58-L70
ZSAIm/iqiyi-parser
147f506b11d7dfc358a2c5c408337b46bca6676d
nbdler/DLAllotter.py
python
Allotter.getUrlsHealth
(self)
return speed_table
return: [(Urlid, AvgSpeed), ...]
return: [(Urlid, AvgSpeed), ...]
[ "return", ":", "[", "(", "Urlid", "AvgSpeed", ")", "...", "]" ]
def getUrlsHealth(self): """return: [(Urlid, AvgSpeed), ...]""" urlspeed = {} for i in self.globalprog.progresses.values(): if not i.isEnd(): urlspeed[i.urlid] = (urlspeed.get(i.urlid, (0, 0))[0] + 1, urlspeed.get(i.urlid, (0, 0))[1] + i.getAvgSpeed()) for i, j in urlspeed.items(): urlspeed[i] = j[1] / j[0] speed_table = sorted(urlspeed.items(), key=lambda x: x[1]) return speed_table
[ "def", "getUrlsHealth", "(", "self", ")", ":", "urlspeed", "=", "{", "}", "for", "i", "in", "self", ".", "globalprog", ".", "progresses", ".", "values", "(", ")", ":", "if", "not", "i", ".", "isEnd", "(", ")", ":", "urlspeed", "[", "i", ".", "url...
https://github.com/ZSAIm/iqiyi-parser/blob/147f506b11d7dfc358a2c5c408337b46bca6676d/nbdler/DLAllotter.py#L133-L149
accel-brain/accel-brain-code
86f489dc9be001a3bae6d053f48d6b57c0bedb95
Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/function_approximator.py
python
FunctionApproximator.learn
(self, iteratable_data)
Learn the observed data points for vector representation of the input images. Args: iteratable_data: is-a `IteratableData`.
Learn the observed data points for vector representation of the input images.
[ "Learn", "the", "observed", "data", "points", "for", "vector", "representation", "of", "the", "input", "images", "." ]
def learn(self, iteratable_data): ''' Learn the observed data points for vector representation of the input images. Args: iteratable_data: is-a `IteratableData`. ''' self.model.learn(iteratable_data)
[ "def", "learn", "(", "self", ",", "iteratable_data", ")", ":", "self", ".", "model", ".", "learn", "(", "iteratable_data", ")" ]
https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/function_approximator.py#L35-L44
pycollada/pycollada
5b2d53333f03047b0fdfc25e394f8b77b57b62fc
collada/geometry.py
python
Geometry.save
(self)
Saves the geometry back to :attr:`xmlnode`
Saves the geometry back to :attr:`xmlnode`
[ "Saves", "the", "geometry", "back", "to", ":", "attr", ":", "xmlnode" ]
def save(self): """Saves the geometry back to :attr:`xmlnode`""" meshnode = self.xmlnode.find(tag('mesh')) for src in self.sourceById.values(): if isinstance(src, source.Source): src.save() if src.xmlnode not in meshnode: meshnode.insert(0, src.xmlnode) deletenodes = [] for oldsrcnode in meshnode.findall(tag('source')): if oldsrcnode not in [src.xmlnode for src in self.sourceById.values() if isinstance(src, source.Source)]: deletenodes.append(oldsrcnode) for d in deletenodes: meshnode.remove(d) #Look through primitives to find a vertex source vnode = self.xmlnode.find(tag('mesh')).find(tag('vertices')) #delete any inputs in vertices tag that no longer exist and find the vertex input delete_inputs = [] for input_node in vnode.findall(tag('input')): if input_node.get('semantic') == 'POSITION': input_vnode = input_node else: srcid = input_node.get('source')[1:] if srcid not in self.sourceById: delete_inputs.append(input_node) for node in delete_inputs: vnode.remove(node) vert_sources = [] for prim in self.primitives: for src in prim.sources['VERTEX']: vert_sources.append(src[2][1:]) vert_src = vnode.get('id') vert_ref = input_vnode.get('source')[1:] if not(vert_src in vert_sources or vert_ref in vert_sources) and len(vert_sources) > 0: if vert_ref in self.sourceById and vert_ref in vert_sources: new_source = vert_ref else: new_source = vert_sources[0] self.sourceById[new_source + '-vertices'] = self.sourceById[new_source] input_vnode.set('source', '#' + new_source) vnode.set('id', new_source + '-vertices') #any source references in primitives that are pointing to the # same source that the vertices tag is pointing to to instead # point to the vertices id vert_src = vnode.get('id') vert_ref = input_vnode.get('source')[1:] for prim in self.primitives: for node in prim.xmlnode.findall(tag('input')): src = node.get('source')[1:] if src == vert_ref: node.set('source', '#%s' % vert_src) self.xmlnode.set('id', self.id) self.xmlnode.set('name', self.name) for prim in self.primitives: if type(prim) is triangleset.TriangleSet and prim.xmlnode.tag != tag('triangles'): prim._recreateXmlNode() if prim.xmlnode not in meshnode: meshnode.append(prim.xmlnode) deletenodes = [] primnodes = [prim.xmlnode for prim in self.primitives] for child in meshnode: if child.tag != tag('vertices') and child.tag != tag('source') and child not in primnodes: deletenodes.append(child) for d in deletenodes: meshnode.remove(d)
[ "def", "save", "(", "self", ")", ":", "meshnode", "=", "self", ".", "xmlnode", ".", "find", "(", "tag", "(", "'mesh'", ")", ")", "for", "src", "in", "self", ".", "sourceById", ".", "values", "(", ")", ":", "if", "isinstance", "(", "src", ",", "so...
https://github.com/pycollada/pycollada/blob/5b2d53333f03047b0fdfc25e394f8b77b57b62fc/collada/geometry.py#L226-L303
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/corpus/reader/wordnet.py
python
Synset.path_similarity
(self, other, verbose=False, simulate_root=True)
Path Distance Similarity: Return a score denoting how similar two word senses are, based on the shortest path that connects the senses in the is-a (hypernym/hypnoym) taxonomy. The score is in the range 0 to 1, except in those cases where a path cannot be found (will only be true for verbs as there are many distinct verb taxonomies), in which case None is returned. A score of 1 represents identity i.e. comparing a sense with itself will return 1. :type other: Synset :param other: The ``Synset`` that this ``Synset`` is being compared to. :type simulate_root: bool :param simulate_root: The various verb taxonomies do not share a single root which disallows this metric from working for synsets that are not connected. This flag (True by default) creates a fake root that connects all the taxonomies. Set it to false to disable this behavior. For the noun taxonomy, there is usually a default root except for WordNet version 1.6. If you are using wordnet 1.6, a fake root will be added for nouns as well. :return: A score denoting the similarity of the two ``Synset`` objects, normally between 0 and 1. None is returned if no connecting path could be found. 1 is returned if a ``Synset`` is compared with itself.
Path Distance Similarity: Return a score denoting how similar two word senses are, based on the shortest path that connects the senses in the is-a (hypernym/hypnoym) taxonomy. The score is in the range 0 to 1, except in those cases where a path cannot be found (will only be true for verbs as there are many distinct verb taxonomies), in which case None is returned. A score of 1 represents identity i.e. comparing a sense with itself will return 1.
[ "Path", "Distance", "Similarity", ":", "Return", "a", "score", "denoting", "how", "similar", "two", "word", "senses", "are", "based", "on", "the", "shortest", "path", "that", "connects", "the", "senses", "in", "the", "is", "-", "a", "(", "hypernym", "/", ...
def path_similarity(self, other, verbose=False, simulate_root=True): """ Path Distance Similarity: Return a score denoting how similar two word senses are, based on the shortest path that connects the senses in the is-a (hypernym/hypnoym) taxonomy. The score is in the range 0 to 1, except in those cases where a path cannot be found (will only be true for verbs as there are many distinct verb taxonomies), in which case None is returned. A score of 1 represents identity i.e. comparing a sense with itself will return 1. :type other: Synset :param other: The ``Synset`` that this ``Synset`` is being compared to. :type simulate_root: bool :param simulate_root: The various verb taxonomies do not share a single root which disallows this metric from working for synsets that are not connected. This flag (True by default) creates a fake root that connects all the taxonomies. Set it to false to disable this behavior. For the noun taxonomy, there is usually a default root except for WordNet version 1.6. If you are using wordnet 1.6, a fake root will be added for nouns as well. :return: A score denoting the similarity of the two ``Synset`` objects, normally between 0 and 1. None is returned if no connecting path could be found. 1 is returned if a ``Synset`` is compared with itself. """ distance = self.shortest_path_distance(other, simulate_root=simulate_root and self._needs_root()) if distance >= 0: return 1.0 / (distance + 1) else: return None
[ "def", "path_similarity", "(", "self", ",", "other", ",", "verbose", "=", "False", ",", "simulate_root", "=", "True", ")", ":", "distance", "=", "self", ".", "shortest_path_distance", "(", "other", ",", "simulate_root", "=", "simulate_root", "and", "self", "...
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/corpus/reader/wordnet.py#L575-L606
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/plugins/dbms/sqlite/fingerprint.py
python
Fingerprint.checkDbms
(self)
References for fingerprint: * http://www.sqlite.org/lang_corefunc.html * http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions
References for fingerprint:
[ "References", "for", "fingerprint", ":" ]
def checkDbms(self): """ References for fingerprint: * http://www.sqlite.org/lang_corefunc.html * http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions """ if not conf.extensiveFp and (Backend.isDbmsWithin(SQLITE_ALIASES) or (conf.dbms or "").lower() in SQLITE_ALIASES): setDbms(DBMS.SQLITE) self.getBanner() return True infoMsg = "testing %s" % DBMS.SQLITE logger.info(infoMsg) result = inject.checkBooleanExpression("LAST_INSERT_ROWID()=LAST_INSERT_ROWID()") if result: infoMsg = "confirming %s" % DBMS.SQLITE logger.info(infoMsg) result = inject.checkBooleanExpression("SQLITE_VERSION()=SQLITE_VERSION()") if not result: warnMsg = "the back-end DBMS is not %s" % DBMS.SQLITE logger.warn(warnMsg) return False else: infoMsg = "actively fingerprinting %s" % DBMS.SQLITE logger.info(infoMsg) result = inject.checkBooleanExpression("RANDOMBLOB(-1)>0") version = '3' if result else '2' Backend.setVersion(version) setDbms(DBMS.SQLITE) self.getBanner() return True else: warnMsg = "the back-end DBMS is not %s" % DBMS.SQLITE logger.warn(warnMsg) return False
[ "def", "checkDbms", "(", "self", ")", ":", "if", "not", "conf", ".", "extensiveFp", "and", "(", "Backend", ".", "isDbmsWithin", "(", "SQLITE_ALIASES", ")", "or", "(", "conf", ".", "dbms", "or", "\"\"", ")", ".", "lower", "(", ")", "in", "SQLITE_ALIASES...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/plugins/dbms/sqlite/fingerprint.py#L59-L107
allegroai/clearml
5953dc6eefadcdfcc2bdbb6a0da32be58823a5af
clearml/storage/util.py
python
crc32text
(text, seed=1337)
return '{:08x}'.format(crc32((str(seed)+str(text)).encode('utf-8')))
Return crc32 hash of a string Do not use this hash for security, if needed use something stronger like SHA2 :param text: string to hash :param seed: use prefix seed for hashing :return: crc32 hex in string (32bits = 8 characters in hex)
Return crc32 hash of a string Do not use this hash for security, if needed use something stronger like SHA2
[ "Return", "crc32", "hash", "of", "a", "string", "Do", "not", "use", "this", "hash", "for", "security", "if", "needed", "use", "something", "stronger", "like", "SHA2" ]
def crc32text(text, seed=1337): # type: (str, Union[int, str]) -> str """ Return crc32 hash of a string Do not use this hash for security, if needed use something stronger like SHA2 :param text: string to hash :param seed: use prefix seed for hashing :return: crc32 hex in string (32bits = 8 characters in hex) """ return '{:08x}'.format(crc32((str(seed)+str(text)).encode('utf-8')))
[ "def", "crc32text", "(", "text", ",", "seed", "=", "1337", ")", ":", "# type: (str, Union[int, str]) -> str", "return", "'{:08x}'", ".", "format", "(", "crc32", "(", "(", "str", "(", "seed", ")", "+", "str", "(", "text", ")", ")", ".", "encode", "(", "...
https://github.com/allegroai/clearml/blob/5953dc6eefadcdfcc2bdbb6a0da32be58823a5af/clearml/storage/util.py#L92-L102
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/wsgiserver/wsgiserver2.py
python
ChunkedRFile.__init__
(self, rfile, maxlen, bufsize=8192)
[]
def __init__(self, rfile, maxlen, bufsize=8192): self.rfile = rfile self.maxlen = maxlen self.bytes_read = 0 self.buffer = EMPTY self.bufsize = bufsize self.closed = False
[ "def", "__init__", "(", "self", ",", "rfile", ",", "maxlen", ",", "bufsize", "=", "8192", ")", ":", "self", ".", "rfile", "=", "rfile", "self", ".", "maxlen", "=", "maxlen", "self", ".", "bytes_read", "=", "0", "self", ".", "buffer", "=", "EMPTY", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/wsgiserver/wsgiserver2.py#L409-L415
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
pypy3.7/multiprocess/reduction.py
python
ForkingPickler.register
(cls, type, reduce)
Register a reduce function for a type.
Register a reduce function for a type.
[ "Register", "a", "reduce", "function", "for", "a", "type", "." ]
def register(cls, type, reduce): '''Register a reduce function for a type.''' cls._extra_reducers[type] = reduce
[ "def", "register", "(", "cls", ",", "type", ",", "reduce", ")", ":", "cls", ".", "_extra_reducers", "[", "type", "]", "=", "reduce" ]
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/pypy3.7/multiprocess/reduction.py#L47-L49
pvlib/pvlib-python
1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a
versioneer.py
python
get_version
()
return get_versions()["version"]
Get the short version string for this project.
Get the short version string for this project.
[ "Get", "the", "short", "version", "string", "for", "this", "project", "." ]
def get_version(): """Get the short version string for this project.""" return get_versions()["version"]
[ "def", "get_version", "(", ")", ":", "return", "get_versions", "(", ")", "[", "\"version\"", "]" ]
https://github.com/pvlib/pvlib-python/blob/1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a/versioneer.py#L1471-L1473
Dman95/SASM
7e3ae6da1c219a68e26d38939338567e5c27151a
Windows/MinGW64/opt/lib/python2.7/codecs.py
python
StreamRecoder.readline
(self, size=None)
return data
[]
def readline(self, size=None): if size is None: data = self.reader.readline() else: data = self.reader.readline(size) data, bytesencoded = self.encode(data, self.errors) return data
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "data", "=", "self", ".", "reader", ".", "readline", "(", ")", "else", ":", "data", "=", "self", ".", "reader", ".", "readline", "(", "size", ")"...
https://github.com/Dman95/SASM/blob/7e3ae6da1c219a68e26d38939338567e5c27151a/Windows/MinGW64/opt/lib/python2.7/codecs.py#L785-L792
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/webchecker/webchecker.py
python
Checker.setflags
(self, **kw)
[]
def setflags(self, **kw): for key in kw.keys(): if key not in self.validflags: raise NameError, "invalid keyword argument: %s" % str(key) for key, value in kw.items(): setattr(self, key, value)
[ "def", "setflags", "(", "self", ",", "*", "*", "kw", ")", ":", "for", "key", "in", "kw", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "self", ".", "validflags", ":", "raise", "NameError", ",", "\"invalid keyword argument: %s\"", "%", "str", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/webchecker/webchecker.py#L267-L272
geometalab/Vector-Tiles-Reader-QGIS-Plugin
a31ae86959c8f3b7d6f332f84191cd7ca4683e1d
plugin/util/tile_source.py
python
AbstractSource.load_tiles
(self, zoom_level, tiles_to_load, max_tiles=None)
* Loads the tiles for the specified zoom_level and bounds from the web service, this source has been created with :param tiles_to_load: All tile coordinates which shall be loaded :param zoom_level: The zoom level which will be loaded :param max_tiles: The maximum number of tiles to be loaded :return:
* Loads the tiles for the specified zoom_level and bounds from the web service, this source has been created with :param tiles_to_load: All tile coordinates which shall be loaded :param zoom_level: The zoom level which will be loaded :param max_tiles: The maximum number of tiles to be loaded :return:
[ "*", "Loads", "the", "tiles", "for", "the", "specified", "zoom_level", "and", "bounds", "from", "the", "web", "service", "this", "source", "has", "been", "created", "with", ":", "param", "tiles_to_load", ":", "All", "tile", "coordinates", "which", "shall", "...
def load_tiles(self, zoom_level, tiles_to_load, max_tiles=None): """ * Loads the tiles for the specified zoom_level and bounds from the web service, this source has been created with :param tiles_to_load: All tile coordinates which shall be loaded :param zoom_level: The zoom level which will be loaded :param max_tiles: The maximum number of tiles to be loaded :return: """ raise NotImplementedError
[ "def", "load_tiles", "(", "self", ",", "zoom_level", ",", "tiles_to_load", ",", "max_tiles", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/geometalab/Vector-Tiles-Reader-QGIS-Plugin/blob/a31ae86959c8f3b7d6f332f84191cd7ca4683e1d/plugin/util/tile_source.py#L84-L93
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/campaign_asset_service/client.py
python
CampaignAssetServiceClientMeta.get_transport_class
( cls, label: str = None, )
return next(iter(cls._transport_registry.values()))
Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use.
Return an appropriate transport class.
[ "Return", "an", "appropriate", "transport", "class", "." ]
def get_transport_class( cls, label: str = None, ) -> Type[CampaignAssetServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values()))
[ "def", "get_transport_class", "(", "cls", ",", "label", ":", "str", "=", "None", ",", ")", "->", "Type", "[", "CampaignAssetServiceTransport", "]", ":", "# If a specific transport is requested, return that one.", "if", "label", ":", "return", "cls", ".", "_transport...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/campaign_asset_service/client.py#L55-L73
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/db/sqlalchemy/api.py
python
storage_glance_metadata_copy_to_snapshot
(context, snapshot_id, storage_id, session=None)
Update the Glance metadata for a snapshot by copying all of the key:value pairs from the originating storage. This is so that a storage created from the snapshot will retain the original metadata.
Update the Glance metadata for a snapshot by copying all of the key:value pairs from the originating storage. This is so that a storage created from the snapshot will retain the original metadata.
[ "Update", "the", "Glance", "metadata", "for", "a", "snapshot", "by", "copying", "all", "of", "the", "key", ":", "value", "pairs", "from", "the", "originating", "storage", ".", "This", "is", "so", "that", "a", "storage", "created", "from", "the", "snapshot"...
def storage_glance_metadata_copy_to_snapshot(context, snapshot_id, storage_id, session=None): """ Update the Glance metadata for a snapshot by copying all of the key:value pairs from the originating storage. This is so that a storage created from the snapshot will retain the original metadata. """ if session is None: session = get_session() metadata = storage_glance_metadata_get(context, storage_id, session=session) with session.begin(): for meta in metadata: vol_glance_metadata = models.HardwareGlanceMetadata() vol_glance_metadata.snapshot_id = snapshot_id vol_glance_metadata.key = meta['key'] vol_glance_metadata.value = meta['value'] vol_glance_metadata.save(session=session)
[ "def", "storage_glance_metadata_copy_to_snapshot", "(", "context", ",", "snapshot_id", ",", "storage_id", ",", "session", "=", "None", ")", ":", "if", "session", "is", "None", ":", "session", "=", "get_session", "(", ")", "metadata", "=", "storage_glance_metadata_...
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/db/sqlalchemy/api.py#L1581-L1599
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_internal/pep425tags.py
python
get_darwin_arches
(major, minor, machine)
return arches
Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine.
Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine.
[ "Return", "a", "list", "of", "supported", "arches", "(", "including", "group", "arches", ")", "for", "the", "given", "major", "minor", "and", "machine", "architecture", "of", "an", "macOS", "machine", "." ]
def get_darwin_arches(major, minor, machine): """Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine. """ arches = [] def _supports_arch(major, minor, arch): # Looking at the application support for macOS versions in the chart # provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears # our timeline looks roughly like: # # 10.0 - Introduces ppc support. # 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64 # and x86_64 support is CLI only, and cannot be used for GUI # applications. # 10.5 - Extends ppc64 and x86_64 support to cover GUI applications. # 10.6 - Drops support for ppc64 # 10.7 - Drops support for ppc # # Given that we do not know if we're installing a CLI or a GUI # application, we must be conservative and assume it might be a GUI # application and behave as if ppc64 and x86_64 support did not occur # until 10.5. # # Note: The above information is taken from the "Application support" # column in the chart not the "Processor support" since I believe # that we care about what instruction sets an application can use # not which processors the OS supports. if arch == 'ppc': return (major, minor) <= (10, 5) if arch == 'ppc64': return (major, minor) == (10, 5) if arch == 'i386': return (major, minor) >= (10, 4) if arch == 'x86_64': return (major, minor) >= (10, 5) if arch in groups: for garch in groups[arch]: if _supports_arch(major, minor, garch): return True return False groups = OrderedDict([ ("fat", ("i386", "ppc")), ("intel", ("x86_64", "i386")), ("fat64", ("x86_64", "ppc64")), ("fat32", ("x86_64", "i386", "ppc")), ]) if _supports_arch(major, minor, machine): arches.append(machine) for garch in groups: if machine in groups[garch] and _supports_arch(major, minor, garch): arches.append(garch) arches.append('universal') return arches
[ "def", "get_darwin_arches", "(", "major", ",", "minor", ",", "machine", ")", ":", "arches", "=", "[", "]", "def", "_supports_arch", "(", "major", ",", "minor", ",", "arch", ")", ":", "# Looking at the application support for macOS versions in the chart", "# provided...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_internal/pep425tags.py#L160-L218
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
tools/manual/detected_faces.py
python
FaceUpdate._tk_edited
(self)
return self._detected_faces.tk_edited
:class:`tkinter.BooleanVar`: The variable indicating whether an edit has occurred meaning a GUI redraw needs to be triggered. Notes ----- The variable is still a ``None`` when this class is initialized, so referenced explicitly.
:class:`tkinter.BooleanVar`: The variable indicating whether an edit has occurred meaning a GUI redraw needs to be triggered.
[ ":", "class", ":", "tkinter", ".", "BooleanVar", ":", "The", "variable", "indicating", "whether", "an", "edit", "has", "occurred", "meaning", "a", "GUI", "redraw", "needs", "to", "be", "triggered", "." ]
def _tk_edited(self): """ :class:`tkinter.BooleanVar`: The variable indicating whether an edit has occurred meaning a GUI redraw needs to be triggered. Notes ----- The variable is still a ``None`` when this class is initialized, so referenced explicitly. """ return self._detected_faces.tk_edited
[ "def", "_tk_edited", "(", "self", ")", ":", "return", "self", ".", "_detected_faces", ".", "tk_edited" ]
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/tools/manual/detected_faces.py#L547-L555
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/modules/igd.py
python
IGDCMDClient.setIDT
(self, args)
[]
def setIDT(self, args): self.igdc.SetIdleDisconnectTime(args.time)
[ "def", "setIDT", "(", "self", ",", "args", ")", ":", "self", ".", "igdc", ".", "SetIdleDisconnectTime", "(", "args", ".", "time", ")" ]
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/modules/igd.py#L122-L124
sakhnik/nvim-gdb
c2a0d076383b8a0991681c33efe80bcba6dd3608
lib/bashdb_proxy.py
python
BashDbProxy.get_prompt
(self)
return self.prompt
[]
def get_prompt(self): return self.prompt
[ "def", "get_prompt", "(", "self", ")", ":", "return", "self", ".", "prompt" ]
https://github.com/sakhnik/nvim-gdb/blob/c2a0d076383b8a0991681c33efe80bcba6dd3608/lib/bashdb_proxy.py#L24-L25
roclark/sportsipy
c19f545d3376d62ded6304b137dc69238ac620a9
sportsipy/ncaab/teams.py
python
Team.opp_field_goals
(self)
return self._opp_field_goals
Returns an ``int`` of the total number of field goals made during the season by opponents.
Returns an ``int`` of the total number of field goals made during the season by opponents.
[ "Returns", "an", "int", "of", "the", "total", "number", "of", "field", "goals", "made", "during", "the", "season", "by", "opponents", "." ]
def opp_field_goals(self): """ Returns an ``int`` of the total number of field goals made during the season by opponents. """ return self._opp_field_goals
[ "def", "opp_field_goals", "(", "self", ")", ":", "return", "self", ".", "_opp_field_goals" ]
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/ncaab/teams.py#L674-L679
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/core/display.py
python
ProgressBar.__next__
(self)
Returns current value and increments display by one.
Returns current value and increments display by one.
[ "Returns", "current", "value", "and", "increments", "display", "by", "one", "." ]
def __next__(self): """Returns current value and increments display by one.""" self.progress += 1 if self.progress < self.total: return self.progress else: raise StopIteration()
[ "def", "__next__", "(", "self", ")", ":", "self", ".", "progress", "+=", "1", "if", "self", ".", "progress", "<", "self", ".", "total", ":", "return", "self", ".", "progress", "else", ":", "raise", "StopIteration", "(", ")" ]
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/core/display.py#L539-L545
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/dogpile/cache/region.py
python
CacheRegion.wrap
(self, proxy)
Takes a ProxyBackend instance or class and wraps the attached backend.
Takes a ProxyBackend instance or class and wraps the attached backend.
[ "Takes", "a", "ProxyBackend", "instance", "or", "class", "and", "wraps", "the", "attached", "backend", "." ]
def wrap(self, proxy): ''' Takes a ProxyBackend instance or class and wraps the attached backend. ''' # if we were passed a type rather than an instance then # initialize it. if type(proxy) == type: proxy = proxy() if not issubclass(type(proxy), ProxyBackend): raise TypeError("Type %s is not a valid ProxyBackend" % type(proxy)) self.backend = proxy.wrap(self.backend)
[ "def", "wrap", "(", "self", ",", "proxy", ")", ":", "# if we were passed a type rather than an instance then", "# initialize it.", "if", "type", "(", "proxy", ")", "==", "type", ":", "proxy", "=", "proxy", "(", ")", "if", "not", "issubclass", "(", "type", "(",...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/dogpile/cache/region.py#L452-L465
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/schema.py
python
_get_table_key
(name, schema)
[]
def _get_table_key(name, schema): if schema is None: return name else: return schema + "." + name
[ "def", "_get_table_key", "(", "name", ",", "schema", ")", ":", "if", "schema", "is", "None", ":", "return", "name", "else", ":", "return", "schema", "+", "\".\"", "+", "name" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/schema.py#L61-L65
qtile/qtile
803dc06fc1f8b121a1d8fe047f26a43812cd427f
libqtile/backend/x11/core.py
python
Core.graceful_shutdown
(self)
Try to close windows gracefully before exiting
Try to close windows gracefully before exiting
[ "Try", "to", "close", "windows", "gracefully", "before", "exiting" ]
def graceful_shutdown(self): """Try to close windows gracefully before exiting""" def get_interesting_pid(win): # We don't need to kill Internal or Static windows, they're qtile # managed and don't have any state. if not isinstance(win, base.Window): return None try: return win.window.get_net_wm_pid() except Exception: logger.exception("Got an exception in getting the window pid") return None pids = map(get_interesting_pid, self.qtile.windows_map.values()) pids = list(filter(lambda x: x is not None, pids)) # Give the windows a chance to shut down nicely. for pid in pids: try: os.kill(pid, signal.SIGTERM) except OSError: # might have died recently pass def still_alive(pid): # most pids will not be children, so we can't use wait() try: os.kill(pid, 0) return True except OSError: return False # give everyone a little time to exit and write their state. but don't # sleep forever (1s). for i in range(10): pids = list(filter(still_alive, pids)) if len(pids) == 0: break time.sleep(0.1)
[ "def", "graceful_shutdown", "(", "self", ")", ":", "def", "get_interesting_pid", "(", "win", ")", ":", "# We don't need to kill Internal or Static windows, they're qtile", "# managed and don't have any state.", "if", "not", "isinstance", "(", "win", ",", "base", ".", "Win...
https://github.com/qtile/qtile/blob/803dc06fc1f8b121a1d8fe047f26a43812cd427f/libqtile/backend/x11/core.py#L792-L831
simaaron/kaggle-Rain
a3a7491d4047e9023f1fa33ab4623f755780870e
NN_architectures.py
python
build_1Dregression_v2
(input_var=None, input_width=None, h_num_units=[64,64], h_grad_clip=1.0, output_width=1)
return output_net_2
A stacked bidirectional RNN network for regression, alternating with dense layers and merging of the two directions, followed by a feature mean pooling in the time direction Args: input_var (theano 3-tensor): minibatch of input sequence vectors input_width (int): length of input sequences h_num_units (int list): no. of units in hidden layer in each stack from bottom to top h_grad_clip (float): gradient clipping maximum value output_width (int): size of output layer (e.g. =1 for 1D regression) Returns: output layer (Lasagne layer object)
A stacked bidirectional RNN network for regression, alternating with dense layers and merging of the two directions, followed by a feature mean pooling in the time direction Args: input_var (theano 3-tensor): minibatch of input sequence vectors input_width (int): length of input sequences h_num_units (int list): no. of units in hidden layer in each stack from bottom to top h_grad_clip (float): gradient clipping maximum value output_width (int): size of output layer (e.g. =1 for 1D regression) Returns: output layer (Lasagne layer object)
[ "A", "stacked", "bidirectional", "RNN", "network", "for", "regression", "alternating", "with", "dense", "layers", "and", "merging", "of", "the", "two", "directions", "followed", "by", "a", "feature", "mean", "pooling", "in", "the", "time", "direction", "Args", ...
def build_1Dregression_v2(input_var=None, input_width=None, h_num_units=[64,64], h_grad_clip=1.0, output_width=1): """ A stacked bidirectional RNN network for regression, alternating with dense layers and merging of the two directions, followed by a feature mean pooling in the time direction Args: input_var (theano 3-tensor): minibatch of input sequence vectors input_width (int): length of input sequences h_num_units (int list): no. of units in hidden layer in each stack from bottom to top h_grad_clip (float): gradient clipping maximum value output_width (int): size of output layer (e.g. =1 for 1D regression) Returns: output layer (Lasagne layer object) """ # Non-linearity hyperparameter nonlin = lasagne.nonlinearities.LeakyRectify(leakiness=0.15) # Input layer l_in = LL.InputLayer(shape=(None, 22, input_width), input_var=input_var) batchsize = l_in.input_var.shape[0] l_in_1 = LL.DimshuffleLayer(l_in, (0,2,1)) # RNN layers for h in h_num_units: # Forward layers l_forward_0 = LL.RecurrentLayer(l_in_1, nonlinearity=nonlin, num_units=h, backwards=False, learn_init=True, grad_clipping=h_grad_clip, unroll_scan=True, precompute_input=True) l_forward_0a = LL.ReshapeLayer(l_forward_0, (-1, h)) l_forward_0b = LL.DenseLayer(l_forward_0a, num_units=h, nonlinearity=nonlin) l_forward_0c = LL.ReshapeLayer(l_forward_0b, (batchsize, input_width, h)) # Backward layers l_backward_0 = LL.RecurrentLayer(l_in_1, nonlinearity=nonlin, num_units=h, backwards=True, learn_init=True, grad_clipping=h_grad_clip, unroll_scan=True, precompute_input=True) l_backward_0a = LL.ReshapeLayer(l_backward_0, (-1, h)) l_backward_0b = LL.DenseLayer(l_backward_0a, num_units=h, nonlinearity=nonlin) l_backward_0c = LL.ReshapeLayer(l_backward_0b, (batchsize, input_width, h)) l_in_1 = LL.ElemwiseSumLayer([l_forward_0c, l_backward_0c]) # Output layers network_0a = LL.ReshapeLayer(l_in_1, (-1, h_num_units[-1])) network_0b = LL.DenseLayer(network_0a, num_units=output_width, nonlinearity=nonlin) network_0c = LL.ReshapeLayer(network_0b, (batchsize, input_width, output_width)) output_net_1 = LL.FlattenLayer(network_0c, outdim=2) output_net_2 = LL.FeaturePoolLayer(output_net_1, pool_size=input_width, pool_function=T.mean) return output_net_2
[ "def", "build_1Dregression_v2", "(", "input_var", "=", "None", ",", "input_width", "=", "None", ",", "h_num_units", "=", "[", "64", ",", "64", "]", ",", "h_grad_clip", "=", "1.0", ",", "output_width", "=", "1", ")", ":", "# Non-linearity hyperparameter", "no...
https://github.com/simaaron/kaggle-Rain/blob/a3a7491d4047e9023f1fa33ab4623f755780870e/NN_architectures.py#L99-L175
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/python-sitelib/win32_named_pipe.py
python
Win32Pipe._create
(self, name=None)
Create a new pipe as a server, with the given name
Create a new pipe as a server, with the given name
[ "Create", "a", "new", "pipe", "as", "a", "server", "with", "the", "given", "name" ]
def _create(self, name=None): """Create a new pipe as a server, with the given name""" self._has_stream = False flags = (PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED) mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE # Windows XP, version (5, 1) doesn't support PIPE_REJECT_REMOTE_CLIENTS # see bug 104569. if sys.getwindowsversion() >= (5, 2): mode |= PIPE_REJECT_REMOTE_CLIENTS pipe_prefix = "\\\\.\\pipe\\" if name is not None: if not name.lower().startswith(pipe_prefix): name = pipe_prefix + name log.debug("Creating new named pipe %s", name) self._pipe = CreateNamedPipe(name, flags, mode, 1, 0x1000, 0x1000, 0, None) if self._pipe == INVALID_HANDLE_VALUE: self._pipe = None raise ctypes.WinError(ctypes.get_last_error()) else: bits = min((256, (255 - len(pipe_prefix)) * 4)) start = random.getrandbits(bits) log.debug("Trying to create pipe with randomness %s", hex(start)) # Try a few variations on the name in case it's somehow taken for i in xrange(1024): name = (pipe_prefix + (self.pipe_prefix or "") + hex(start + i)[2:-1]) assert len(name) <= 256 # Unfortuantely, it is more reliable to create a nowait pipe # and poll for it than it is to create a blocking pipe. self._pipe = CreateNamedPipe(name, flags, mode, 1, 0x1000, 0x1000, 0, None) if self._pipe != INVALID_HANDLE_VALUE: break self._pipe = None errno = ctypes.get_last_error() if errno != ERROR_ACCESS_DENIED: # we get access denied on a name collision raise ctypes.WinError(errno) else: raise ctypes.WinError(ctypes.get_last_error()) self.name = name
[ "def", "_create", "(", "self", ",", "name", "=", "None", ")", ":", "self", ".", "_has_stream", "=", "False", "flags", "=", "(", "PIPE_ACCESS_DUPLEX", "|", "FILE_FLAG_FIRST_PIPE_INSTANCE", "|", "FILE_FLAG_OVERLAPPED", ")", "mode", "=", "PIPE_TYPE_BYTE", "|", "P...
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/python-sitelib/win32_named_pipe.py#L92-L138
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/pep517/wrappers.py
python
LoggerWrapper._write
(self, message)
[]
def _write(self, message): self.logger.log(self.level, message)
[ "def", "_write", "(", "self", ",", "message", ")", ":", "self", ".", "logger", ".", "log", "(", "self", ".", "level", ",", "message", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/pep517/wrappers.py#L370-L371
catalyst-team/catalyst
678dc06eda1848242df010b7f34adb572def2598
catalyst/contrib/datasets/movielens.py
python
MovieLens._fetch_movies
(self)
Fetch data and save in the pytorch format 1. Read the train/test data from raw archive 2. Parse train data 3. Parse test data 4. Save in the .pt with torch.save
Fetch data and save in the pytorch format 1. Read the train/test data from raw archive 2. Parse train data 3. Parse test data 4. Save in the .pt with torch.save
[ "Fetch", "data", "and", "save", "in", "the", "pytorch", "format", "1", ".", "Read", "the", "train", "/", "test", "data", "from", "raw", "archive", "2", ".", "Parse", "train", "data", "3", ".", "Parse", "test", "data", "4", ".", "Save", "in", "the", ...
def _fetch_movies(self): """ Fetch data and save in the pytorch format 1. Read the train/test data from raw archive 2. Parse train data 3. Parse test data 4. Save in the .pt with torch.save """ data = self._read_raw_movielens_data() train_raw = data[0] test_raw = data[1] train_parsed = self._parse(train_raw) test_parsed = self._parse(test_raw) num_users, num_items = self._get_dimensions(train_parsed, test_parsed) train = self._build_interaction_matrix(num_users, num_items, self._parse(train_raw)) test = self._build_interaction_matrix(num_users, num_items, self._parse(test_raw)) assert train.shape == test.shape with open(os.path.join(self.processed_folder, self.training_file), "wb") as f: torch.save(train, f) with open(os.path.join(self.processed_folder, self.test_file), "wb") as f: torch.save(test, f)
[ "def", "_fetch_movies", "(", "self", ")", ":", "data", "=", "self", ".", "_read_raw_movielens_data", "(", ")", "train_raw", "=", "data", "[", "0", "]", "test_raw", "=", "data", "[", "1", "]", "train_parsed", "=", "self", ".", "_parse", "(", "train_raw", ...
https://github.com/catalyst-team/catalyst/blob/678dc06eda1848242df010b7f34adb572def2598/catalyst/contrib/datasets/movielens.py#L256-L281