Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,300
def as_dict(self, replace_value_names=True): r = RootSectionTerm(doc=self) for s in self: for t in s: r.terms.append(t) return r.as_dict(replace_value_names)
Iterate, link terms and convert to a dict
355,301
def _getNodeData(self, name, metadata, channel=None): nodeChannel = None if name in metadata: nodeChannelList = metadata[name] if len(nodeChannelList) > 1: nodeChannel = channel if channel is not None else nodeChannelList[0] elif len(nodeChann...
Returns a data point from data
355,302
def fetch_commit(self, event): gh = self.github user = self.options.user repo = self.options.project rc, data = gh.repos[user][repo].git.commits[ event["commit_id"]].get() if rc == 200: return data self.raise_GitHubError(rc, data, gh.get...
Fetch commit data for specified event. :param dict event: dictionary with event information :rtype: dict :return: dictionary with commit data
355,303
def _get_fido_dollar(self, account_number, number): data = json.dumps({"fidoDollarBalanceFormList": [{"phoneNumber": number, "accountNumber": account_number}]}) headers_json = self._headers.copy() headers_json["Co...
Get current Fido dollar balance.
355,304
def _dump_stats_group(self, title, items, normal_formatter=None, verbose_formatter=None): if self.verbose: self.outf.write("[%s]\n" % (title,)) for name, value in items: if verbose_formatter is not None: value = verbose_formatter(value...
Dump a statistics group. In verbose mode, do so as a config file so that other processors can load the information if they want to. :param normal_formatter: the callable to apply to the value before displaying it in normal mode :param verbose_formatter: the callable to...
355,305
def build_indentation_list(parser: str = ): r indentation_list = list() if (parser == or parser == or parser == or parser == or parser == ): for i in range(0, md_parser[parser][][]): indentation_list.append(False) return indentation_list
r"""Create a data structure that holds the state of indentations. :parameter parser: decides the length of the list. Defaults to ``github``. :type parser: str :returns: indentation_list, a list that contains the state of indentations given a header type. :rtype: list :raises: a bu...
355,306
def get_artist(self, id_): endpoint = "artists/{id}".format(id=id_) return self._make_request(endpoint)
Data for a specific artist.
355,307
def create_packages(self): for index, _ in enumerate(self._subpath_components): relpath = _PACKAGE_COMPONENTS + self._subpath_components[:index + 1] + [] touch(os.path.join(self.ROOT, *relpath))
Create missing packages joining the vendor root to the base of the vendored distribution. For example, given a root at ``/home/jake/dev/pantsbuild/pex`` and a vendored distribution at ``pex/vendor/_vendored/requests`` this method would create the following package files:: pex/vendor/_vendored/__init__.p...
355,308
def compile_action_preconditions(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> List[TensorFluent]: scope = self.action_precondition_scope(state, action) preconds = [] with self.graph.as_default(): with tf.name_scope(): ...
Compiles the action preconditions given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`.
355,309
def project(lon0, lat0, lon1, lat1): costh = np.cos(np.pi / 2. - lat0) cosphi = np.cos(lon0) sinth = np.sin(np.pi / 2. - lat0) sinphi = np.sin(lon0) xyz = lonlat_to_xyz(lon1, lat1) x1 = xyz[0] y1 = xyz[1] z1 = xyz[2] x1p = x1 * costh * cosphi + y1 * costh * sinphi - z1 * sin...
This function performs a stereographic projection on the unit vector (lon1,lat1) with the pole defined at the reference unit vector (lon0,lat0).
355,310
def get_single_group_category(self, group_category_id): path = {} data = {} params = {} path["group_category_id"] = group_category_id self.logger.debug("GET /api/v1/group_categories/{group_category_id} with query params: {params} and form dat...
Get a single group category. Returns the data for a single group category, or a 401 if the caller doesn't have the rights to see it.
355,311
def reply(self, incoming, user, message, prefix=None): if not isinstance(user, User): user = User(user) if isinstance(incoming, User): if prefix: self.msg(user, "%s: %s" % (user.nick, message)) else: self.msg(user, message) ...
Replies to a user in a given channel or PM. If the specified incoming is a user, simply sends a PM to user. If the specified incoming is a channel, prefixes the message with the user's nick and sends it to the channel. This is specifically useful in creating responses to commands that ...
355,312
def ensure_path(path, mode=0o777): if path: try: umask = os.umask(000) os.makedirs(path, mode) os.umask(umask) except OSError as e: if e.errno != errno.EEXIST: raise
Ensure that path exists in a multiprocessing safe way. If the path does not exist, recursively create it and its parent directories using the provided mode. If the path already exists, do nothing. The umask is cleared to enable the mode to be set, and then reset to the original value after the mode i...
355,313
def snmp_server_group_group_name(self, **kwargs): config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") group = ET.SubElement(snmp_server, "group") group_version_key = ET.SubElement(group, "group-version") ...
Auto Generated Code
355,314
def get_devices(self, force_reload=False, save_devices=True): if ( (not os.path.exists(self._devices_filename)) or (force_reload is True) ): log.debug("getting devices from LaMetric cloud...") _, url = CLOUD_URLS["get_devices"] ...
get all devices that are linked to the user, if the local device file is not existing the devices will be obtained from the LaMetric cloud, otherwise the local device file will be read. :param bool force_reload: When True, devices are read again from cloud :param bool save_devices: When...
355,315
def QueryHowDoI(Query, num_answers, full_text): Query howdoi_command = HOW_DO_I_COMMAND full_text_option = if full_text else t = subprocess.Popen(howdoi_command + + Query + + str(num_answers)+full_text_option, stdout=subprocess.PIPE) (output, err) = t.communicate() print(.format(Query.rstrip(...
Kicks off a subprocess to send the 'Query' to HowDoI Prints the result, which in this program will route to a gooeyGUI window :param Query: text english question to ask the HowDoI web engine :return: nothing
355,316
def idxmin(self, **kwargs): if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().idxmin(**kwargs) axis = kwargs.get("axis", 0) index = self.index if axis == 0 else self.columns def idxmin_builder(df, **kwargs): ...
Returns the first occurrence of the minimum over requested axis. Returns: A new QueryCompiler object containing the minimum of each column or axis.
355,317
def find_element(self, search): ExperimentalqueryincludeUserAgentShadowDOMsearchIdresultCountExperimentalsearchIdfromIndextoIndexnodeIdsExperimentalsearchId res = self.DOM_performSearch(search, includeUserAgentShadowDOM=False) assert in res assert in res[] searchid = res[][] res_cnt = res[][] self.lo...
DOM_performSearch(self, query, includeUserAgentShadowDOM) Python Function: DOM_performSearch Domain: DOM Method name: performSearch WARNING: This function is marked 'Experimental'! Parameters: 'query' (type: string) -> Plain text or query selector or XPath s...
355,318
def main_crop(): if args.verbose: print("\nProcessing the PDF with pdfCropMargins (version", __version__+")...") print("System type:", ex.system_os) if len(args.pdf_input_doc) > 1: print("\nError in pdfCropMargins: Only one input PDF document is allowed." ...
This function does the real work. It is called by main() in pdfCropMargins.py, which just handles catching exceptions and cleaning up.
355,319
def partial_tempering(topfile="processed.top", outfile="scaled.top", banned_lines=, scale_lipids=1.0, scale_protein=1.0): banned_lines = map(int, banned_lines.split()) top = TOP(topfile) groups = [("_", float(scale_protein)), ("=", float(scale_lipids))] ...
Set up topology for partial tempering (REST2) replica exchange. .. versionchanged:: 0.7.0 Use keyword arguments instead of an `args` Namespace object.
355,320
def flatten_list(l: List[list]) -> list: return [v for inner_l in l for v in inner_l]
takes a list of lists, l and returns a flat list
355,321
def merge(profile, head, base, commit_message=None): if not commit_message: commit_message = "Merged " + head + " into " + base + "." payload = { "base": base, "head": head, "commit_message": commit_message, } response = api.post_merge_request(profile, payload) ...
Merge the head of a branch into the base branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. head The head to ...
355,322
def _check_times(self, min_times, max_times, step): kassert.is_int(min_times) kassert.is_int(max_times) kassert.is_int(step) if not((min_times >= 0) and (max_times > 0) and (max_times >= min_times) and (step > 0)): raise KittyException( % (min_times, max_times))
Make sure that the arguments are valid :raises: KittyException if not valid
355,323
def _read_addr_resolve(self, length, htype): if htype == 1: _byte = self._read_fileng(6) _addr = .join(textwrap.wrap(_byte.hex(), 2)) else: _addr = self._read_fileng(length) return _addr
Resolve MAC address according to protocol. Positional arguments: * length -- int, hardware address length * htype -- int, hardware type Returns: * str -- MAC address
355,324
def get_pyobj(self, multihash, **kwargs): warnings.warn("Using `*_pyobj` on untrusted data is a security risk", DeprecationWarning) return self.cat(multihash, decoder=, **kwargs)
Loads a pickled Python object from IPFS. .. deprecated:: 0.4.2 The ``*_pyobj`` APIs allow for arbitrary code execution if abused. Either switch to :meth:`~ipfsapi.Client.get_json` or use ``pickle.loads(client.cat(multihash))`` instead. .. caution:: The pic...
355,325
def get_choice(cls, value): attribute_for_value = cls.attributes[value] return cls._fields[attribute_for_value]
Return the underlying :class:`ChoiceItem` for a given value.
355,326
def wrap_reports(cls, reports, content_type): reports = [ _ReportTemplateWrapper(content_type, report) for report in reports ] return reports
Wraps the reports in a _ReportTemplateWrapper for the given content_type -- this allows data to be returned as HTML links, for instance.
355,327
def dependencies(self, kwargs=None, expand_only=False): sections = self._get_dependency_sections_to_use(kwargs) deps = [] for sect in sections: if expand_only: deps.extend(lang.expand_dependencies_section(sect, kwargs)) else: ...
Returns all dependencies of this assistant with regards to specified kwargs. If expand_only == False, this method returns list of mappings of dependency types to actual dependencies (keeps order, types can repeat), e.g. Example: [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam...
355,328
def load_commodities(self): if isinstance(self.amount, Amount): self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency)) else: self.amount = Amount("{0:.8f} {1}".format(self.amount, self.currency))
Load the commodities for Amounts in this object.
355,329
def create_rank_dicts(self, alt_scores): self.alts_to_ranks = dict() cur_score = max(alt_scores.values()) cur_rank = 0 self.ranks_to_alts = {cur_rank:[]} for i in sorted(alt_scores.keys(), key=lambda x: -alt_scores[x]): if alt_scores[i] == cur_score: ...
Description: Takes in the scores of the alternatives in the form alt:score and generates the dictionaries mapping alternatives to rankings and rankings to alternatives. Parameters: alt_scores: dictionary of the scores of every alternative
355,330
def add_eps(self, eps): _nodeids, _eps, _vars = self._nodeids, self._eps, self._vars for ep in eps: try: if not isinstance(ep, ElementaryPredication): ep = ElementaryPredication(*ep) except TypeError: raise Xmr...
Incorporate the list of EPs given by *eps*.
355,331
def create_shn (archive, compression, cmd, verbosity, interactive, filenames): if len(filenames) > 1: raise util.PatoolError("multiple filenames for shorten not supported") cmdlist = [util.shell_quote(cmd)] cmdlist.extend([, util.shell_quote(archive), , util.shell_quote(filenames[0])]) ...
Compress a WAV file to a SHN archive.
355,332
def translate_logical_line(start, end, contents, indent_stack, endmarker=False): while contents[0] == : start += 1 contents.pop(0) while contents[-1] == : end -= 1 contents.pop() indent = len(indent_stack[-1]) if indent_stack else 0 if endmarker: indent = le...
Translate raw contents to logical lines
355,333
def parse(): from fortpy.code import CodeParser c = CodeParser() if args["verbose"]: c.verbose = True f90files = {} c.scan_path(args["source"], f90files) for fname, fpath in f90files.items(): if fname not in c._modulefiles: c._modulefiles[fname] = [] ...
Parses all the modules in the library specified by the script args.
355,334
def maxEntropy(n,k): s = float(k)/n if s > 0.0 and s < 1.0: entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2) else: entropy = 0 return n*entropy
The maximum enropy we could get with n units and k winners
355,335
def csv_line(self, line): self.csv_sep = "," return self.csv_sep.join([ + str(x) + for x in line])
turn a list of values into a CSV line
355,336
def double_click(self): self.scroll_to() ActionChains(self.parent.driver).double_click(self._element).perform()
Performs a double click in the element. Currently works only on Chrome driver.
355,337
def eventFilter(self, object, event): if object == self.parent() and event.type() == QtCore.QEvent.Resize: self.resize(event.size()) elif event.type() == QtCore.QEvent.Close: self.setResult(0) return False
Resizes this overlay as the widget resizes. :param object | <QtCore.QObject> event | <QtCore.QEvent> :return <bool>
355,338
def copy_from(self, other): self.verbose, self.quiet, self.path, self.name, self.tracing = other.verbose, other.quiet, other.path, other.name, other.tracing
Copy other onto self.
355,339
def _create_rates(self, dist=, size=None, eps=1e-4): uniformloguniform if size is None: size = self.output_size if dist == : z = np.random.uniform(eps, 1 - eps, size=size).astype(util.FLOAT) return theano.shared(z, name=self._fmt()) if dist == : ...
Create a rate parameter (usually for a recurrent network layer). Parameters ---------- dist : {'uniform', 'log'}, optional Distribution of rate values. Defaults to ``'uniform'``. size : int, optional Number of rates to create. Defaults to ``self.output_size``. ...
355,340
def add_to_package_numpy(self, root, ndarray, node_path, target, source_path, transform, custom_meta): filehash = self.save_numpy(ndarray) metahash = self.save_metadata(custom_meta) self._add_to_package_contents(root, node_path, [filehash], target, source_path, transform, metahash)
Save a Numpy array to the store.
355,341
def output_vlan(gandi, vlan, datacenters, output_keys, justify=10): output_generic(gandi, vlan, output_keys, justify) if in output_keys: for dc in datacenters: if dc[] == vlan.get(, vlan.get(, {}).get()): dc_name = dc.get(, dc.get(, ...
Helper to output a vlan information.
355,342
def get_ttf(self): font_dict = {} families = [] rootdirlist = string.split(self.search_path, os.pathsep) for dirName, subdirList, filelist in itertools.chain.from_iterable(os.walk(path) for path in rootdirlist): for item in filelist: ...
Given a search path, find file with requested extension
355,343
def get_max_op_version(): s max op-version value Requires Glusterfs version > 3.9 CLI Example: .. code-block:: bash salt glusterfs.get_max_op_version Glusterfs version must be 3.10+. Your version is {0}..volume get all cluster.max-op-versionopErrstrvolGetoptsValueOptValue': ...
.. versionadded:: 2019.2.0 Returns the glusterfs volume's max op-version value Requires Glusterfs version > 3.9 CLI Example: .. code-block:: bash salt '*' glusterfs.get_max_op_version
355,344
def initnew(self, fname): iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) idfhandle = StringIO() self.idfname = idfhandle self.read() if fname: self.idfname = fname
Use the current IDD and create a new empty IDF. If the IDD has not yet been initialised then this is done first. Parameters ---------- fname : str, optional Path to an IDF. This does not need to be set at this point.
355,345
def get_queryset(self, queryset=None): serializer = self.get_serializer() return getattr(self, , serializer.Meta.model.objects.all())
Returns a queryset for this request. Arguments: queryset: Optional root-level queryset.
355,346
def flush(self): try: termios.tcdrain(self._fd) except termios.error as e: raise SerialError(e.errno, "Flushing serial port: " + e.strerror)
Flush the write buffer of the serial port, blocking until all bytes are written. Raises: SerialError: if an I/O or OS error occurs.
355,347
def set_checkbox(self, data, uncheck_other_boxes=True): for (name, value) in data.items(): checkboxes = self.find_by_type("input", "checkbox", {: name}) if not checkboxes: raise InvalidFormMethod("No input checkbox named " + name) ...
Set the *checked*-attribute of input elements of type "checkbox" specified by ``data`` (i.e. check boxes). :param data: Dict of ``{name: value, ...}``. In the family of checkboxes whose *name*-attribute is ``name``, check the box whose *value*-attribute is ``value``. All boxes i...
355,348
def plot(self, tick_interval=[30, 30], minor_tick_interval=None, ax=None, ax2=None, colorbar=False, cb_orientation=, cb_label=None, grid=False, axes_labelsize=None, tick_labelsize=None, show=True, fname=None, **kwargs): if tick_interval is None: xticks...
Plot the raw data using a simple cylindrical projection. Usage ----- x.plot([tick_interval, minor_tick_interval, ax, ax2, colorbar, cb_orientation, cb_label, grid, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, def...
355,349
def get_grade_system_query_session_for_gradebook(self, gradebook_id): if not self.supports_grade_system_query(): raise errors.Unimplemented() return sessions.GradeSystemQuerySession(gradebook_id, runtime=self._runtime)
Gets the ``OsidSession`` associated with the grade system query service for the given gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook return: (osid.grading.GradeSystemQuerySession) - ``a GradeSystemQuerySession`` raise: NotFound - ``gradebook_id`` not ...
355,350
def get(tag: {str, }, normalize=True) -> : if isinstance(tag, Language): if not normalize: return tag tag_lower = tag.lower() if normalize and tag_lower in LANGUAGE_REPLACEMENTS: ...
Create a Language object from a language tag string. If normalize=True, non-standard or overlong tags will be replaced as they're interpreted. This is recommended. Here are several examples of language codes, which are also test cases. Most language codes are straightforward, but these...
355,351
def send_discuss_msg_async(self, *, discuss_id, message, auto_escape=False): return super().__getattr__() \ (discuss_id=discuss_id, message=message, auto_escape=auto_escape)
发送讨论组消息 (异步版本) ------------ :param int discuss_id: 讨论组 ID(正常情况下看不到,需要从讨论组消息上报的数据中获得) :param str | list[ dict[ str, unknown ] ] message: 要发送的内容 :param bool auto_escape: 消息内容是否作为纯文本发送(即不解析 CQ 码),`message` 数据类型为 `list` 时无效 :return: None :rtype: None
355,352
def string_match(self, datastring, findstring, flags=None): if type(datastring) is IntType: return None if flags is None: flags = [] if "REG_EXP" in flags: match = re.search(findstring, datastring) if match is None: po...
Returns position of findstring in datastring or None if not found. Flags is a list of strings. Supported strings are: * "MATCH_CASE": The case has to match for valid find * "WHOLE_WORD": The word has to be surrounded by whitespace characters if in the middle of the str...
355,353
def load_defaults(self): extract_files = [ self.config.settings.user.extract, self.config.settings.system.extract, ] for extract_file in extract_files: if extract_file: try: self.load_from_file(extract_fil...
Loads default extraction rules from the user and system extract.conf files. Returns None.
355,354
def get_vmware_inventory_path(): if sys.platform.startswith("win"): return os.path.expandvars(r"%APPDATA%\Vmware\Inventory.vmls") elif sys.platform.startswith("darwin"): return os.path.expanduser("~/Library/Application Support/VMware Fusion/vmInventory") else: ...
Returns VMware inventory file path. :returns: path to the inventory file
355,355
def _normalize(self, name, columns, points): for i, _ in enumerate(points): if points[i] is None: del(points[i]) del(columns[i]) continue try: points[i] = float(points[i])...
Normalize data for the InfluxDB's data model.
355,356
def id_offset(cls): max_ids = [] for backend in Store.renderers.keys(): store_ids = Store.custom_options(backend=backend).keys() max_id = max(store_ids)+1 if len(store_ids) > 0 else 0 max_ids.append(max_id) return max(max_ids) if len(max_ids)...
Compute an appropriate offset for future id values given the set of ids currently defined across backends.
355,357
def sub(self, x, axis): return self.__array_op(operator.sub, x, axis)
Function to sub 3D View with vector or 2D array (type = numpy.ndarray or 2D Field or 2D View) or 2D View with vector (type = numpy.ndarray) :param x: array(1D, 2D) or field (2D) or View(2D) :param axis: specifies axis, eg. axis = (1,2) plane lies in yz-plane, axis=0 vector along x axis :return: ...
355,358
def eigenvectors_left_samples(self): r res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :, :] = self._sampled_hmms[i].eigenvectors_left return res
r""" Samples of the left eigenvectors of the hidden transition matrix
355,359
def close(self): if self._file: if not(self._file.closed): self._file.close() self.closed = True
Close the SExtractor file.
355,360
def change_parent(sender, instance, **kwargs): if instance.id is None: return if len({, } & set(instance.changed_fields)) != 0: diff = instance.diff parent = diff[][0] if in diff else diff[][0] parent_id = parent.item_id if isinstance(parent, Task) else Task.objects.get(pk=...
When the given task instance has changed. Look at task and context and change the corresponding item relation.
355,361
def display_graphic(self, flag_curves, ui): ui.graphic_widget.canvas.picture.clear() x = scipy.linspace(self.x_data[0], self.x_data[-1], len(self.x_data)) curve_wanted = 0 for curve in self.y_data: if flag_curves: if curve_wanted == self.num_plo...
This function plots results of a file into the canvas. Inputs : flag_curves : A boolean to know with we have to plot all curves or not. ui : The main_Window.
355,362
def to_dict(self): return { : self.current, : self.first, : self.last, : self.more, : self.prev, }
Convert the Paginator into a dict
355,363
def GetFileEntryByPathSpec(self, path_spec): volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec) if volume_index is None: location = getattr(path_spec, , None) if location is None or location != self.LOCATION_ROOT: return None return apfs_containe...
Retrieves a file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: APFSContainerFileEntry: a file entry or None if not exists.
355,364
def union(self, *others: ) -> : new_subst = Substitution(self) for other in others: for variable_name, replacement in other.items(): new_subst.try_add_variable(variable_name, replacement) return new_subst
Try to merge the substitutions. If a variable occurs in multiple substitutions, try to merge the replacements. See :meth:`union_with_variable` to see how replacements are merged. Does not modify any of the original substitutions. Example: >>> subst1 = Substitution({'x': Multi...
355,365
def iso8601_date(d): if d == values.unset: return d elif isinstance(d, datetime.datetime): return str(d.date()) elif isinstance(d, datetime.date): return str(d) elif isinstance(d, str): return d
Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
355,366
def gen_assist_requests(self): config = embedded_assistant_pb2.AssistConfig( audio_in_config=embedded_assistant_pb2.AudioInConfig( encoding=, sample_rate_hertz=self.conversation_stream.sample_rate, ), audio_out_config=embedded_assista...
Yields: AssistRequest messages to send to the API.
355,367
def ipython_paste(self,e): u if self.enable_win32_clipboard: txt=clipboard.get_clipboard_text_and_convert( self.enable_ipython_paste_list_of_lists) if self.enable_ipython_paste_for_paths: if len...
u"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is True then try to convert tabseparated data to repr of list of lists or repr of array. If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space
355,368
def load_nipy_img(nii_file): import nipy if not os.path.exists(nii_file): raise FileNotFound(nii_file) try: return nipy.load_image(nii_file) except Exception as exc: raise Exception(.format(repr_imgs(nii_file))) from exc
Read a Nifti file and return as nipy.Image Parameters ---------- param nii_file: str Nifti file path Returns ------- nipy.Image
355,369
def showOverlay(self, ulOverlayHandle): fn = self.function_table.showOverlay result = fn(ulOverlayHandle) return result
Shows the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this.
355,370
def get_chempot_correction(element, temp, pres): if element not in ["O", "N", "Cl", "F", "H"]: return 0 std_temp = 298.15 std_pres = 1E5 ideal_gas_const = 8.3144598 Cp_dict = {"O": 29.376, ...
Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, T_std = 1 bar). The gas phase is limited to be one of O2, N2, Cl2, F2, H2. Calculation formula ...
355,371
def pack(self, update_timestamp=False, insert_before_payload=""): return self._header.pack(update_timestamp) \ + insert_before_payload \ + self._payload
Pack this object into a transmittable format :param update_timestamp: Should the timestamp be updated to current (default: False) :type update_timestamp: bool :param insert_before_payload: Insert this after this data, but before payload (default: "") :type insert...
355,372
def _archive_elements(self): try: stackfile_key, propertyfile_key = self._craft_s3_keys() template_file = self._config.get(, {}).get(, None) bucket = self._config.get(, {}).get(, None) if not os.path.isfile(template_file): logging.info("{...
Cloud Formation likes to take the template from S3 so here we put the template into S3. We also store the parameters file that was used in this run. Note: you can pass anything as the version string but you should at least consider a version control tag or git commit hash as the version....
355,373
def clean(amount): if not amount: return amount if re.search(r, amount): return amount.replace(, ).replace(, ).replace(, ) if re.search(r, amount): return amount.replace(, ).replace(, ) if re.search(r, amo...
Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str
355,374
def _check_and_install_rbenv(ret, user=None): ret = _check_rbenv(ret, user) if ret[] is False: if __salt__[](user): ret[] = True ret[] = else: ret[] = False ret[] = else: ret[] = True ret[] = return ret
Verify that rbenv is installed, install if unavailable
355,375
def run_step(self, rewriter): assert rewriter, ("FileRewriter instance required to run " "FileInRewriterStep.") rewriter.files_in_to_out(in_path=self.path_in, out_path=self.path_out)
Do the file in to out rewrite. Doesn't do anything more crazy than call files_in_to_out on the rewriter. Args: rewriter: pypyr.filesystem.FileRewriter instance.
355,376
def update_state(self, state): checklistitem_json = self.fetch_json( uri_path = self.base_uri + , http_method = , query_params = {: if state else } ) return self.create_checklist_item(self.idCard, self.idChecklist, checklistitem_json)
Set the state of the current checklist item. Returns a new ChecklistItem object.
355,377
async def shuffle(self, state: Optional[bool] = None, *, device: Optional[SomeDevice] = None): await self.__user.http.shuffle_playback(state)
shuffle on or off for user’s playback. Parameters ---------- state : Optional[bool] if `True` then Shuffle user’s playback. else if `False` do not shuffle user’s playback. device : Optional[:obj:`SomeDevice`] The Device object or id of the device this...
355,378
def register_fetcher(self, name, fetcher): assert name not in self.fetchers self.fetchers[name] = fetcher
Register a fetcher. :param name: Fetcher name. :param fetcher: The new fetcher.
355,379
def write_hdf5_series(series, output, path=None, attrs=None, **kwargs): if attrs is None: attrs = format_index_array_attrs(series) return write_hdf5_array(series, output, path=path, attrs=attrs, **kwargs)
Write a Series to HDF5. See :func:`write_hdf5_array` for details of arguments and keywords.
355,380
def createPregeneratedGraphs(): listofNValues = [250, 500, 1000, 1500, 2000, 2500] kw = 32 errors = np.array([ [3.65083333e-03, 3.06166667e-04, 1.89166667e-05, 4.16666667e-06, 1.50000000e-06, 9.16666667e-07], [2.44633333e-02, 3.64491667e-03, 3.16083333e-04, 6.93333333e-05, 2.16666667e-05, ...
Creates graphs based on previous runs of the scripts. Useful for editing graph format for writeups.
355,381
def _find_phrases( self, sentence, syntax_layer, cutPhrases, cutMaxThreshold ): BI NPattribPos = [ , , , , , , , , , , ] NPheadPos = [ , , ] NPlabels = [ for i in range(len(sentence)) ] for i in range(len(sentence)):...
Detects NP phrases by relying on local dependency relations: 1) Identifies potential heads of NP phrases; 2) Identifies consecutive words that can form an NP phrase: 2.1) potential attribute + potential head; 2.2) quantity word or phrase + nominal; ...
355,382
def clear_caches(self): self.get_repository.cache_clear() self._get_repository.cache_clear() self.pool.clear_caches()
Clear all cached data.
355,383
def load_urlencoded_body(handler): @wraps(handler) def wrapper(event, context): if isinstance(event.get(), str): try: event[] = parse_qs(event[]) except: return {: 400, : } return handler(event, context) return wrapper
Automatically deserialize application/x-www-form-urlencoded bodies Automatically returns a 400 BAD REQUEST if there is an error while parsing. Usage:: >>> from lambda_decorators import load_urlencoded_body >>> @load_urlencoded_body ... def handler(event, context): ... return event...
355,384
def _check_status(self): logger.info() status = self.log_call( [, , ], callwith=subprocess.check_output, cwd=self.cwd, ) if status: raise DirtyException(status)
Check repo status and except if dirty.
355,385
def grant_bonus(self, worker_id, assignment_id, bonus_price, reason): params = bonus_price.get_as_params(, 1) params[] = worker_id params[] = assignment_id params[] = reason return self._process_request(, params)
Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or rejected. This payment happens separately from the reward you pay to the Worker when you approve the W...
355,386
def write_manifest(self): self.filelist._repair() files = [self._manifest_normalize(f) for f in self.filelist.files] msg = "writing manifest file " % self.manifest self.execute(write_file, (self.manifest, files), msg)
Write the file list in 'self.filelist' to the manifest file named by 'self.manifest'.
355,387
async def _send(self, request: Request, content: Dict[Text, Any], stack: Stack): msg = { : { : request.conversation.fbid, }, : content, } if stack and stack.has_layer(Messag...
Actually proceed to sending the message to the Facebook API.
355,388
def reconstruct_url(self, path_info=None, query_string=None, relative=False): environ = self.environ if relative: url = else: url = environ[] + if environ.get(): url += environ[] else: url += environ[] ...
Reconstructs the request URL using the algorithm provided by PEP3333
355,389
def reduce_sum(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {:}) return , new_attrs, inputs
Reduce the array along a given axis by sum value
355,390
def metadata_path_unset(self): if not self.metadata_file: raise IOError() log.debug(.format(self.id, self.metadata_path)) tmp_sr = SeqIO.read(self.metadata_path, ) tmp_feats = tmp_sr.features self.metadata_dir = None self.metadata_file = No...
Copy features to memory and remove the association of the metadata file.
355,391
def get(self, session, words, time=, aFilter=, nick=None): request = TOPRequest() request[] = words request[] = time request[] = aFilter if nick!=None: request[] = nick self.create(self.execute(request, session)) return self.result
taobao.simba.insight.wordsbase.get =================================== 词基础数据查询
355,392
def percentile(self, percentile): percentile = float(percentile) if percentile != percentile or percentile < 0 or percentile > 100: raise ValueError() result = c_float() if not Gauged.map_percentile(self.ptr, percentile, byref(result)): raise MemoryError ...
Get a percentile of all floats in the map. Since the sorting is done in-place, the map is no longer safe to use after calling this or median()
355,393
def register_device(self, dev_name): if dev_name not in self.devices: self.devices.append(dev_name) group_name = self.system.__dict__[dev_name]._group if group_name not in self.group.keys(): self.group[group_name] = {}
register a device to the device list
355,394
def _check_tbit(self, **keys): colnums = keys.get(, None) if colnums is None: colnums = self._extract_colnums() has_tbit = False for i, colnum in enumerate(colnums): npy_type, isvar, istbit = self._get_tbl_numpy_dtype(colnum) if (istbit): ...
Check if one of the columns is a TBIT column parameters ---------- colnums: integer array, optional
355,395
def kp_pan_zoom_set(self, viewer, event, data_x, data_y, msg=True): if self.canpan: reg = 1 with viewer.suppress_redraw: viewer.panset_xy(data_x, data_y) scale_x, scale_y = self._save.get((viewer, , reg), ...
Sets the pan position under the cursor.
355,396
def parse(number, region=None, keep_raw_input=False, numobj=None, _check_region=True): if numobj is None: numobj = PhoneNumber() if number is None: raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The phone number supplied was None....
Parse a string and return a corresponding PhoneNumber object. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the numb...
355,397
def alter_1(self, given_container_name, container_name, meta, val): meta.container = None if not isinstance(container_name, six.string_types): meta.container = container_name container_name = container_name.container_name return container_name
Get the container_name of the container if a container is specified
355,398
def auth_check(self, auth_list, funs, args, tgt, tgt_type=, groups=None, publish_validate=False, minions=None, whitelist=None): if s...
Returns a bool which defines if the requested function is authorized. Used to evaluate the standard structure under external master authentication interfaces, like eauth, peer, peer_run, etc.
355,399
def _api_key_patch_replace(conn, apiKey, path, value): response = conn.update_api_key(apiKey=apiKey, patchOperations=[{: , : path, : value}]) return response
the replace patch operation on an ApiKey resource