Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
358,200
def project_describe(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /project-xxxx/describe API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fdescribe
358,201
async def run(self): logging.info() coroutines = set() while True: coro = self._poll_channel() coroutines.add(coro) _, coroutines = await asyncio.wait(coroutines, timeout=0.1)
Entrypoint to route messages between plugins.
358,202
def to_json(self): return {: self.year, : self.month, : self.day, : self.hour, : self.minute}
Get date time as a dictionary.
358,203
def abort(self): if self._state == _State.CLOSED: self._invalid_state("abort() called") return self._force_close(None)
Immediately close the stream, without sending remaining buffers or performing a proper shutdown.
358,204
def service_account_email(self): if self._service_account_id is None: self._service_account_id = app_identity.get_service_account_name() return self._service_account_id
The service account email.
358,205
def write_AST(wdl_file, outdir=None): if outdir is None: outdir = os.getcwd() with open(os.path.join(outdir, ), ) as f: with open(wdl_file, ) as wdl: wdl_string = wdl.read() ast = wdl_parser.parse(wdl_string).ast() f.write(ast.dumps(indent=2))
Writes a file with the AST for a wdl file in the outdir.
358,206
def _fragment_one_level(self, mol_graphs): unique_fragments_on_this_level = [] for mol_graph in mol_graphs: for edge in mol_graph.graph.edges: bond = [(edge[0],edge[1])] try: fragments = mol_graph.split_molecule_subgraphs(bond, all...
Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs, then loop through each graph's edges and attempt to remove that edge in order to obtain two disconnected subgraphs, aka two new fragments. If successful, check to see if the new fragments are alrea...
358,207
def _set_result_from_operation(self): with self._completion_lock: if not self._operation.done or self._result_set: return if self._operation.HasField("response"): resp...
Set the result or exception from the operation if it is complete.
358,208
def write_error_response(self, message): self.set_status(404) response = self.make_error_response(str(message)) now = time.time() spent = now - self.basehandler_starttime response[constants.RESPONSE_KEY_EXECUTION_TIME] = spent self.write_json_response(response)
Writes the message as part of the response and sets 404 status.
358,209
def get_type_name_in_language(cls, type_name, sub_type, language): if language in cls.type_methods_cache: m = cls.type_methods_cache[language] if not m: return type_name return m(type_name) found, method = load_language_plugins(language, ) ...
Get the type for the given language Args: type_name (str): the type to convert language (str): the language to use Returns: a type name in the given language Example: get_type_name_in_language("Varchar", "python") ...
358,210
def ftp_walk(ftpconn: FTP, rootpath=): current_directory = rootpath try: directories, files = directory_listing(ftpconn, current_directory) except ftplib.error_perm: return yield current_directory, directories, files for name in directories: new_path = os.p...
Recursively traverse an ftp directory to discovery directory listing.
358,211
def populate_fw_dev(self, fw_id, mgmt_ip, new): for cnt in self.res: used = self.res.get(cnt).get() if mgmt_ip == self.res[cnt].get(): if new: self.res[cnt][] = used + 1 self.res[cnt][].append(fw_id) return self...
Populate the class after a restart.
358,212
def create_gp(self): nb_bams = len(self.bams) gp_parts = [ textwrap.dedent( ), os.linesep.join([self._gp_style_func(i, nb_bams) for i in range(nb_bams)]), textwrap.dedent( ), os.linesep.j...
Create GnuPlot file.
358,213
def parse(argv, level=0): nargs = [] for i in range(len(argv)): if argv[i] == : level += 1 if level == 1: index = i + 1 elif argv[i] == : level -= 1 sub = argv[index:i] if level == 0: nargs.app...
Parse sub-arguments between `[` and `]` recursively. Examples -------- ``` >>> argv = ['--foo', 'bar', '--buz', '[', 'qux', '--quux', 'corge', ']'] >>> subarg.parse(argv) ['--foo', 'bar', '--buz', ['qux', '--quux', 'corge']] ``` Parameters ---------- argv : list of strings ...
358,214
def get_all_derivatives(self, address): ret = [] direct = self.get_direct_derivatives(address) ret.extend(direct) for t in direct: ret.extend(self.get_all_derivatives(t.address)) return ret
Get all targets derived directly or indirectly from the specified target. Note that the specified target itself is not returned. :API: public
358,215
def isheavy(self): selection_size_bytes = self._calc_selection_size() if selection_size_bytes > self.MAX_DATA_ARRAY_SIZE: return True else: return False
Check if the current selection is too large.
358,216
def create_job(self, emails): resp = self._call(endpoint=, data={: , : .join(emails)}) return Job(resp[])
Create a new bulk verification job for the list of emails. :param list emails: Email addresses to verify. :return: A Job object.
358,217
def open(self, filename=None): if filename is None: address = self.address + else: notebook_path = self.resource_filename(filename) if not notebook_path.isfile(): raise IOError( % notebook_path) else: address = % ...
Open a browser tab with the notebook path specified relative to the notebook directory. If no filename is specified, open the root of the notebook server.
358,218
def compute_kv(self, memory_antecedent): if not self.shared_kv: raise ValueError("compute_kv can only be called with shared_kv") ret = mtf.einsum( [memory_antecedent, self.wkv], reduced_dims=[self.memory_input_dim]) if self.combine_dims: ret = mtf.replace_dimensions(ret, ret.shape.d...
Compute key/value Tensor kv. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims
358,219
def is_admin(): if os.name == : import ctypes import traceback try: return ctypes.windll.shell32.IsUserAnAdmin() except: traceback.print_exc() return False else: return os.getuid() == 0
https://stackoverflow.com/a/19719292 @return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this function to return False.
358,220
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, asynchronous=None, _return_http_data_only=None, collection_formats=None,...
Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, set the asynchronous parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Que...
358,221
def add_changes_markup(dom, ins_nodes, del_nodes): for node in reversed(del_nodes): insert_or_append(node.orig_parent, node, node.orig_next_sibling) wrap(node, ) for node in ins_nodes: wrap(node, ) remove_nesting(dom, ) remove_nesting(dom, ) s...
Add <ins> and <del> tags to the dom to show changes.
358,222
def reference_id(self, reference_id): if reference_id is None: raise ValueError("Invalid value for `reference_id`, must not be `None`") if len(reference_id) > 40: raise ValueError("Invalid value for `reference_id`, length must be less than `40`") self._referenc...
Sets the reference_id of this Order. A client specified identifier to associate an entity in another system with this order. :param reference_id: The reference_id of this Order. :type: str
358,223
def __extract_location_coordinates(self, image_size, color_segment): coordinates = []; for index in color_segment: y = floor(index / image_size[0]); x = index - y * image_size[0]; coordinates.append([x, y]); return coord...
! @brief Extracts coordinates of specified image segment. @param[in] image_size (list): Image size presented as a [width x height]. @param[in] color_segment (list): Image segment whose coordinates should be extracted. @return (list) Coordinates of each pixel.
358,224
def _parse_header(line: str) -> Tuple[str, Dict[str, str]]: r parts = _parseparam(";" + line) key = next(parts) params = [("Dummy", "value")] for p in parts: i = p.find("=") if i >= 0: name = p[:i].strip().lower() value = p[i + 1 :].strip() pa...
r"""Parse a Content-type like header. Return the main content-type and a dictionary of options. >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st" >>> ct, d = _parse_header(d) >>> ct 'form-data' >>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape') True >...
358,225
def jaccard(seq1, seq2): set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) / float(len(set1 | set2))
Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
358,226
def source_sum(self): if self._is_completely_masked: return np.nan * self._data_unit else: return np.sum(self.values)
The sum of the unmasked ``data`` values within the source segment. .. math:: F = \\sum_{i \\in S} (I_i - B_i) where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the ``data``, and :math:`S` are the unmasked pixels in the source segment. Non-finite pixel values (e.g. NaN,...
358,227
def overlap(intv1, intv2): return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0]))
Overlaping of two intervals
358,228
def search(self, initial_ids, initial_cache): state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, loop_vars=[state], shape_invariants=[state_shapes], parallel_iterations=1, back_prop=False) ...
Beam search for sequences with highest scores.
358,229
def append_filter(self, structure_filter): hdict = structure_filter.as_dict() hdict["input_structure"] = self.final_structure.as_dict() self.history.append(hdict)
Adds a filter. Args: structure_filter (StructureFilter): A filter implementating the AbstractStructureFilter API. Tells transmuter waht structures to retain.
358,230
def _get_ref_lengths(self): sam_reader = pysam.Samfile(self.bam, "rb") return dict(zip(sam_reader.references, sam_reader.lengths))
Gets the length of each reference sequence from the header of the bam. Returns dict name => length
358,231
def check(self, user, provider, permission, **kwargs): try: social_user = self._get_social_user(user, provider) if not social_user: return False except SocialUserDoesNotExist: return False backend = self.get_backend(social_user, prov...
user - django User or UserSocialAuth instance provider - name of publisher provider permission - if backend maintains check permissions vk - binary mask in int format facebook - scope string
358,232
def encrypt(self, message): if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode()).hexdigest()
Encrypt the given message
358,233
def convert_to_string(ndarr): with contextlib.closing(BytesIO()) as bytesio: _internal_write(bytesio, ndarr) return bytesio.getvalue()
Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it.
358,234
def symmetric_difference(self, that): diff = self._set.symmetric_difference(that) return self._fromset(diff, key=self._key)
Return a new set with elements in either *self* or *that* but not both.
358,235
def commit(self, wait=False, additionalParams={}): url = "%s/commit" % self.root params = { "f" : "json", } for key, value in additionalParams.items(): params[key] = value if wait == True: res = self._post(url=url, ...
Commit is called once all parts are uploaded during a multipart Add Item or Update Item operation. The parts are combined into a file, and the original file is overwritten during an Update Item operation. This is an asynchronous call and returns immediately. Status can be used to check t...
358,236
def get_parser(): parser = ArgumentParser(description=) parser.add_argument(, metavar=, type=str, nargs=, help=) parser.add_argument(, , type=str, nargs=, help=) parser.add_argument(, , help=, action=) parser.add_argument(,...
Parse command-line arguments.
358,237
def all_substrings(s): join = .join for i in range(1, len(s) + 1): for sub in window(s, i): yield join(sub)
yields all substrings of a string
358,238
def purge_metadata(self, force=False): if not force and self.is_alive(): raise ProcessMetadataManager.MetadataError() super(ProcessManager, self).purge_metadata_by_name(self._name)
Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks for process liveness before purging metadata. :param bool force: If True, skip process liveness check before purging metadata. :raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal.
358,239
def http_auth(self): if in self.request.META.keys(): authmeth, auth = self.request.META[].split( , 1) if authmeth.lower() == : auth = auth.strip().decode() identifier, password = auth.split(, 1) username = get_user...
Returns ``True`` if valid http auth credentials are found in the request header.
358,240
def _tflearn_features(train_config, args): feature_columns = [] target_name = train_config[] key_name = train_config[] for name in train_config[]: if name != target_name and name != key_name: feature_columns.append(tf.contrib.layers.real_valued_column( name, dimension=1)) ...
Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was applied in preprocess_input. Args: train_conf...
358,241
def get_bin_hierarchy_design_session(self): if not self.supports_bin_hierarchy_design(): raise errors.Unimplemented() return sessions.BinHierarchyDesignSession(runtime=self._runtime)
Gets the bin hierarchy design session. return: (osid.resource.BinHierarchyDesignSession) - a ``BinHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_hierarchy_design()`` is ``false`` *compl...
358,242
def add_comment(self, line): if not isinstance(self.last_item, Comment): comment = Comment(self._structure) self._structure.append(comment) self.last_item.add_line(line) return self
Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment
358,243
def _process_irrational_functions(self, functions, predetermined_function_addrs, blockaddr_to_function): functions_to_remove = { } functions_can_be_removed = set(functions.keys()) - set(predetermined_function_addrs) for func_addr, function in functions.items(): if func_a...
For unresolveable indirect jumps, angr marks those jump targets as individual functions. For example, usually the following pattern is seen: sub_0x400010: push ebp mov esp, ebp ... cmp eax, 10 ja end mov eax, jumptable[eax] ...
358,244
def _resolve_source(self, source): if os.path.isdir(source): sources = glob.glob(os.path.join(source, )) if len(sources) == 0: raise ModelLoadError() elif len(sources) > 1: raise ModelLoadError( ) return...
Resolve source to filepath if it is a directory.
358,245
def _safe_minmax(values): isfinite = np.isfinite(values) if np.any(isfinite): values = values[isfinite] minval = np.min(values) maxval = np.max(values) return minval, maxval
Calculate min and max of array with guards for nan and inf.
358,246
def add_text(self, text, x, y, **kws): self.panel.add_text(text, x, y, **kws)
add text to plot
358,247
def float_range(string, minimum, maximum, inf, sup): return _inrange(float(string), minimum, maximum, inf, sup)
Requires values to be a number and range in a certain range. :param string: Value to validate :param minimum: Minimum value to accept :param maximum: Maximum value to accept :param inf: Infimum value to accept :param sup: Supremum value to accept :type string: str :type minimum: float :...
358,248
def ensure_dtraj_list(dtrajs): r if isinstance(dtrajs, list): if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i, dtraj in enumerate(dtrajs): dtrajs[i] = ensure_dtraj(dtraj) return dtrajs else: retu...
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
358,249
def includes_ofs(self, ofs): return (self._region._b + self._ofs) <= ofs < (self._region._b + self._ofs + self._size)
:return: True if the given absolute offset is contained in the cursors current region **Note:** cursor must be valid for this to work
358,250
def main(): dist= mode=1 title="" EQ={:1} if len(sys.argv) > 0: if in sys.argv: print(main.__doc__) sys.exit() if in sys.argv: file=input("Enter file name with dec, inc data: ") dist=input("Enter desired distrubution: [Fish]e...
NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS...
358,251
def unpickle(self, parent): self.parent = parent self._unpickle_collection(self.members) self._unpickle_collection(self.executables) self._unpickle_collection(self.types)
Sets the parent pointer references for the module *and* all of its child classes that also have pointer references.
358,252
def threadProfileCode(func, *args, **kwargs): with ThreadProfiler(threading.current_thread()) as prof: try: prof.thread.status = threadProfileCode.__wrapped__(func, *args, **kwargs) except EscapeException as e: prof.thread.status = e
Toplevel thread profile wrapper.
358,253
def process_formdata(self, valuelist): if valuelist: self.data = .join([ x.strip() for x in filter(lambda x: x, .join(valuelist).splitlines()) ])
Process form data.
358,254
def start(lang, session_id, owner, env, mount, tag, resources, cluster_size): if session_id is None: session_id = token_hex(5) else: session_id = session_id envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) with...
Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" command. \b LANG: The name (and version/platform tags appended after a colon) of...
358,255
def get_bulb_state(self): self.get_status() try: self.state = self.data[] except TypeError: self.state = False return bool(self.state)
Get the relay state.
358,256
def parse(self, url_data): self.url_data = url_data self.loc = False self.url = u"" data = url_data.get_content() isfinal = True try: self.parser.Parse(data, isfinal) except ExpatError as expaterr: self.url_data.add_warning(expater...
Parse XML URL data.
358,257
def unproject(self, image_points): Ki = self.inv_camera_matrix X = np.dot(Ki, to_homogeneous(image_points)) X = X / X[2] XU = self.invert(X) return XU
Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray Image points Returns ---...
358,258
def cdn_set_conf(self, cname, originConf, environment, token): return self.client.service.cdn_set_conf( cname, originConf, environment, token)
The cdn_set_conf method enables the user to update an existing origin configuration in the CDN. The cdn_get_conf returns the token in the response and the cdn_set_conf requires a token as one of the parameters. The set action is valid only if the token returned is equal to the ...
358,259
def filter_ids(self): return self._sorted_ingredients([ d.id for d in self.values() if isinstance(d, Filter) ])
Return the Metrics on this shelf in the order in which they were used.
358,260
def get_completed_or_runnning(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.get_completed_or_runnning_with_http_info(id, **kwargs) else: (data) = self.get_completed_or_runnning_with_http_info(id, **kwargs) return data
Deprecated, use /builds/{id} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) ...
358,261
def get_port_channel_detail_output_lacp_partner_system_id(self, **kwargs): config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_detail, "output") lacp = ET.S...
Auto Generated Code
358,262
def fmt_tag(cur_namespace, tag, val): if tag == : fq_val = val if not in val and cur_namespace is not None: fq_val = cur_namespace.name + + fq_val return fq_val elif tag == : if in val: val, version = val.split(, 1) version = int(versio...
Processes a documentation reference.
358,263
def new_timestamped_uid(bits=32): return "%s-%s" % (re.sub(, , datetime.now().isoformat()).replace(".", "Z-"), new_uid(bits))
A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of randomness. The advantage of this is it sorts nicely by time, while still being unique. Example: 20150912T084555Z-378465-43vtwbx
358,264
def transaction(self, connection=None, **kwargs): with self.connection(connection) as connection: name = connection.transaction_name() connection.transaction_start(name) try: yield connection connection.transaction_stop() ...
a simple context manager useful for when you want to wrap a bunch of db calls in a transaction http://docs.python.org/2/library/contextlib.html http://docs.python.org/release/2.5/whatsnew/pep-343.html example -- with self.transaction() # do a bunch of calls ...
358,265
def add_header(self, key, value, **params): key = self.escape(key) ci_key = key.casefold() def quoted_params(items): for p in items: param_name = self.escape(p[0]) param_val = self.de_quote(self.escape(p[1])) yield param_name...
Add a header to the collection, including potential parameters. Args: key (str): The name of the header value (str): The value to store under that key params: Option parameters to be appended to the value, automatically formatting them in a standard way
358,266
def get(self): LOG.info() response = [] for run in self.backend_store.list_runs(): response.append(run_model.format_response(run)) return response
Get run list
358,267
def listify(generator_func): def list_func(*args, **kwargs): return degenerate(generator_func(*args, **kwargs)) return list_func
Converts generator functions into list returning functions. @listify def test(): yield 1 test() # => [1]
358,268
def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return value.state.name
Convert a value to DB storage. Returns the state name.
358,269
def copy(self): result = CIMInstance( self.classname, properties=self.properties, qualifiers=self.qualifiers) result.path = self.path return result
Return a new :class:`~pywbem.CIMInstance` object that is a copy of this CIM instance. This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vic...
358,270
def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(), obj=None, feval=None, fpreproc=None, as_pandas=True, show_progress=None, show_stdv=True, seed=0): results = [] cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc) for i in range(num_boost_round): fo...
Cross-validation with given paramaters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round : int Number of boosting iterations. nfold : int Number of folds in CV. metrics : list of strings Evaluati...
358,271
def update_auth_settings(self, account_id, auth_settings): url = ACCOUNTS_API.format(account_id) + "/sso_settings" data = self._put_resource(url, auth_settings.json_data()) return CanvasSSOSettings(data=data)
Update the authentication settings for the passed account_id. https://canvas.instructure.com/doc/api/authentication_providers.html#method.account_authorization_configs.update_sso_settings
358,272
def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs): import pandas t = self.resolved_url.get_resource().get_target() kwargs = self._update_pandas_kwargs(dtype, parse_dates, kwargs) return pandas.read_csv(t.fspath, *args, **kwargs)
Fetch the target and pass through to pandas.read_csv Don't provide the first argument of read_csv(); it is supplied internally.
358,273
def _translate_residue(self, selection, default_atomname=): m = self.RESIDUE.match(selection) if not m: errmsg = "Selection {selection!r} is not valid.".format(**vars()) logger.error(errmsg) raise ValueError(errmsg) gmx_resid = self.gmx_resid(int(m.g...
Translate selection for a single res to make_ndx syntax.
358,274
def data(self, message): self._send() resp = self._read() if not resp.startswith(): raise DspamClientError( + resp) for line in message.split(): if line == : line = self._send(line) ...
Send LMTP DATA command and process the server response. The server response is stored as a list of dicts in <DspamClient>.results, keyed on the recipient name(s). Depending on the server return data, different formats are available: * LMTP mode -- Dict containing 'accepted', a bool i...
358,275
def read_host_file(path): res = [] for l in file(path).xreadlines(): hostname = l.strip() if hostname: res.append(hostname) return res
Read the host file. Return a list of hostnames.
358,276
def _can_change_or_view(model, user): model_name = model._meta.model_name app_label = model._meta.app_label can_change = user.has_perm(app_label + + model_name) can_view = user.has_perm(app_label + + model_name) return can_change or can_view
Return True iff `user` has either change or view permission for `model`.
358,277
def convert_mean(binaryproto_fname, output=None): mean_blob = caffe_parser.caffe_pb2.BlobProto() with open(binaryproto_fname, ) as f: mean_blob.ParseFromString(f.read()) img_mean_np = np.array(mean_blob.data) img_mean_np = img_mean_np.reshape( mean_blob.channels, mean_blob.height, ...
Convert caffe mean Parameters ---------- binaryproto_fname : str Filename of the mean output : str, optional Save the mean into mxnet's format Returns ------- NDArray Mean in ndarray
358,278
def fromtimestamp(cls, t, tz=None): _check_tzinfo_arg(tz) converter = _time.localtime if tz is None else _time.gmtime t, frac = divmod(t, 1.0) us = int(frac * 1e6) if us == 1000000: t += 1 us = 0 y, ...
Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well.
358,279
def setup_pod(build_file_path, manage_dir=None, local_requirements=None): paths.setup(build_file_path, manage_dir=manage_dir, local_requirements=local_requirements)
This must be called by the project's build.py for pyntofdjango to function. You can specify it directly with the optional manage_dir kwarg. :param build_file_path: E.g. os.path.abspath(__file__) :param manage_dir: Optional, Searched for if None. :param local_requirements: Optional, pip requirements f...
358,280
def date2timestamp(dte): seconds = mktime(dte.timetuple()) if isinstance(dte, datetime): return seconds + dte.microsecond / 1000000.0 else: return int(seconds)
Convert a *dte* into a valid unix timestamp.
358,281
def get_likes(self) -> Iterator[]: if self.likes == 0: return likes_edges = self._field(, ) if self.likes == len(likes_edges): yield from (Profile(self._context, like[]) for like in likes_edges) return yield from (Pro...
Iterate over all likes of the post. A :class:`Profile` instance of each likee is yielded.
358,282
def get_gene_source_set(gtf): gene_to_source = {} db = get_gtf_db(gtf) for feature in complete_features(db): gene_id = feature[][0] sources = gene_to_source.get(gene_id, set([])).union(set([feature.source])) gene_to_source[gene_id] = sources return gene_to_source
get a dictionary of the set of all sources for a gene
358,283
def get_image(self, image, chunk_size=DEFAULT_DATA_CHUNK_SIZE): res = self._get(self._url("/images/{0}/get", image), stream=True) return self._stream_raw_result(res, chunk_size, False)
Get a tarball of an image. Similar to the ``docker save`` command. Args: image (str): Image name to get chunk_size (int): The number of bytes returned by each iteration of the generator. If ``None``, data will be streamed as it is received. Default: 2 MB ...
358,284
def get_vnetwork_dvpgs_input_vcenter(self, **kwargs): config = ET.Element("config") get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs") config = get_vnetwork_dvpgs input = ET.SubElement(get_vnetwork_dvpgs, "input") vcenter = ET.SubElement(input, "vcenter") vcen...
Auto Generated Code
358,285
def _set_trap(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=trap.trap, is_container=, presence=False, yang_name="trap", rest_name="trap", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u...
Setter method for trap, mapped from YANG variable /snmp_server/enable/trap (container) If this variable is read-only (config: false) in the source YANG file, then _set_trap is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_trap() directly...
358,286
def decipher(self,string): string = string.upper() mapping = dict(zip(self.key,self.table)) ptext = "" for i in string: ptext += mapping[i] return self.demorse(ptext)
Decipher string using FracMorse cipher according to initialised key. Example:: plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext) :param string: The string to decipher. :returns: The enciphered string.
358,287
def get_entity_propnames(entity): ins = entity if isinstance(entity, InstanceState) else inspect(entity) return set( ins.mapper.column_attrs.keys() + ins.mapper.relationships.keys() )
Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set
358,288
def number_of_sections(self): if not self._is_parsed: self._Parse() self._is_parsed = True return len(self._sections)
int: number of sections.
358,289
def get_collection_rules(self, raw=False): logger.debug("Attemping to download collection rules from %s", self.collection_rules_url) net_logger.info("GET %s", self.collection_rules_url) try: req = self.conn.session.get( self.collection_r...
Download the collection rules
358,290
def _prof(self, key): p = self._profs.get(key, None) if not p: self._profs[key] = p = _Prof() return p
Get _Prof object.
358,291
def select(self, selection_specs=None, selection_mode=, **selection): selection = {dim: sel for dim, sel in selection.items() if dim in self.dimensions()+[]} if (selection_specs and not any(self.matches(sp) for sp in selection_specs) or not selection): ...
Allows selecting data by the slices, sets and scalar values along a particular dimension. The indices should be supplied as keywords mapping between the selected dimension and value. Additionally selection_specs (taking the form of a list of type.group.label strings, types or functions) ...
358,292
def backup_file(*, file, host): if _driver: log.msg_debug("[{driver}] Backing up file " .format(driver=_driver.get_name(), file=file)) _driver.backup_file(file=file, host=host)
Perform backup action on set driver :param file: Name of the file to be used by the driver :param host: Corresponding host name associated with file
358,293
def _sanity_check_args(args): if "scheduler" in args and "queue" in args: if args.scheduler and not args.queue: if args.scheduler != "sge": return "IPython parallel scheduler (-s) specified. This also requires a queue (-q)." elif args.queue and not args.scheduler: ...
Ensure dependent arguments are correctly specified
358,294
def read(self, symbol, as_of=None): if as_of is not None: res = self.find_one({: symbol, : {: as_of}}, sort=[(, pymongo.DESCENDING)]) else: res = self.find_one({: symbol}, sort=[(, pymongo.DESCENDING)]) return res[] if res is not N...
Return current metadata saved for `symbol` Parameters ---------- symbol : `str` symbol name for the item as_of : `datetime.datetime` return entry valid at given time Returns ------- metadata
358,295
def get_params(names): params = {} for name in names: value = request.form.get(name) or request.files.get(name) if value is not None: params[name] = value return params
Return a dictionary with params from request. TODO: I think we don't use it anymore and it should be removed before someone gets hurt.
358,296
def ports(self) -> dict: return { param: self[param].raw for param in self if param.startswith(IOPORT) }
Create a smaller dictionary containing all ports.
358,297
def _edge_both_nodes(nodes: List[Node]): node_ids = [node.id for node in nodes] return and_( Edge.source_id.in_(node_ids), Edge.target_id.in_(node_ids), )
Get edges where both the source and target are in the list of nodes.
358,298
def _generate_noise_temporal_drift(trs, tr_duration, basis="discrete_cos", period=150, ): if basis == : timepoints = np.linspace(0, trs - 1, trs) ...
Generate the drift noise Create a trend (either sine or discrete_cos), of a given period and random phase, to represent the drift of the signal over time Parameters ---------- trs : int How many volumes (aka TRs) are there tr_duration : float How long in seconds is each volum...
358,299
def arabic_digit_to_thai_digit(text: str) -> str: if not text or not isinstance(text, str): return "" newtext = [] for ch in text: if ch in _arabic_thai: newtext.append(_arabic_thai[ch]) else: newtext.append(ch) return "".join(newtext)
:param str text: Text with Arabic digits such as '1', '2', '3' :return: Text with Arabic digits being converted to Thai digits such as '๑', '๒', '๓'