Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
380,700
def receive_offer(self, pkt): logger.debug("C2. Received OFFER?, in SELECTING state.") if isoffer(pkt): logger.debug("C2: T, OFFER received") self.offers.append(pkt) if len(self.offers) >= MAX_OFFERS_COLLECTED: logger.debug("C2.5: T, raise REQ...
Receive offer on SELECTING state.
380,701
def get_changes(self, factory_name, global_factory=False, resources=None, task_handle=taskhandle.NullTaskHandle()): if resources is None: resources = self.project.get_python_files() changes = ChangeSet( % factory_name) job_set = task_handle.create_jobset(...
Get the changes this refactoring makes `factory_name` indicates the name of the factory function to be added. If `global_factory` is `True` the factory will be global otherwise a static method is added to the class. `resources` can be a list of `rope.base.resource.File`\s that ...
380,702
def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths): if ruleset and ruleset_file: raise click.BadOptionUsage( "Options and cannot be used together.") try: if not debug: logging.basicConfig(stream=six.StringIO()) log_level...
Print the checks.
380,703
def _build_conflict_target(self): conflict_target = [] if not isinstance(self.query.conflict_target, list): raise SuspiciousOperation(( ) % str(self.query.conflict_target)) def _assert_valid_field(field_name):...
Builds the `conflict_target` for the ON CONFLICT clause.
380,704
def utc2local(date): date_offset = (datetime.now() - datetime.utcnow()) date_offset = (date_offset.microseconds + (date_offset.seconds + date_offset.days * 24 * 3600) * 1e6) / 1e6 date_offset = int(round(date_offset / 60 / 60)) return date + timedelta(hours=date_offset)
DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time.
380,705
def render_surface_function(surfimg, funcimg=None, alphasurf=0.2, alphafunc=1.0, isosurf=0.5, isofunc=0.5, smoothsurf=None, smoothfunc=None, cmapsurf=, cmapfunc=, filename=None, notebook=False, auto_open=False): cmap_dict = { ...
Render an image as a base surface and an optional collection of other image. ANTsR function: `renderSurfaceFunction` NOTE: The ANTsPy version of this function is actually completely different than the ANTsR version, although they should produce similar results. Arguments --------- surf...
380,706
def read_file(file_name, encoding=): with open(file_name, ) as f: data = f.read() if encoding is not None: data = data.decode(encoding) return data
读文本文件 :param encoding: :param file_name: :return:
380,707
def _filter_result(result, filter_functions=None): if filter_functions is not None: for filter_func in filter_functions: result = filter(filter_func, result) return result
Filter result with given filter functions. :param result: an iterable object :param filter_functions: some filter functions :return: a filter object (filtered result)
380,708
def exception(self, timeout=None): if self._state == self.RUNNING: self._context.wait_all_futures([self], timeout) return self._exception
Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn't done. If None, then there is no limit on the wait time. Returns: The exception raised by the ca...
380,709
def preconstrain_flag_page(self, magic_content): for m, v in zip(magic_content, self.state.cgc.flag_bytes): self.preconstrain(m, v)
Preconstrain the data in the flag page. :param magic_content: The content of the magic page as a bytestring.
380,710
def skycoord_to_healpix(self, skycoord, return_offsets=False): if self.frame is None: raise NoFrameError("skycoord_to_healpix") skycoord = skycoord.transform_to(self.frame) representation = skycoord.represent_as(UnitSphericalRepresentation) lon, lat = representation....
Convert celestial coordinates to HEALPix indices (optionally with offsets). Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`. ...
380,711
def get_parameter(self, path, default=None, return_group=False): value = read_parameter_by_path(self.job[][], path, return_group) if value is None: return default return value
Reads hyperparameter from job configuration. If nothing found use given default. :param path: str :param default: * :param return_group: If true and path is a choice_group, we return the dict instead of the group name. :return: *
380,712
def add(name, beacon_data, **kwargs): *processessalt-masterstoppedapache2stopped ret = {: .format(name), : False} if name in list_(return_yaml=False, **kwargs): ret[] = .format(name) return ret if any( in key for key in beacon_data): res = next(value for va...
Add a beacon on the minion Args: name (str): Name of the beacon to configure beacon_data (dict): Dictionary or list containing configuration for beacon. Returns: dict: Boolean and status message on success or failure of add. CLI Example: .. code-bloc...
380,713
def parse_schema(schema_file): e = xml.etree.ElementTree.parse(schema_file) root = e.getroot() cols = [] for elem in root.findall(".//{http://genomic.elet.polimi.it/entities}field"): cols.append(elem.text) return cols
parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe :param schema_file: the path to the schema file :return: the columns of the schema file
380,714
def read(self, lenient=False): self.preamble(lenient=lenient) raw = self.idatdecomp(lenient) if self.interlace: raw = bytearray(itertools.chain(*raw)) arraycode = [self.bitdepth > 8] pixels = map(lambda *row: array(arraycode...
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptio...
380,715
def sub_menu(self): submenu = gtk.Menu() self.start = gtk.ImageMenuItem("Start") self.stop = gtk.ImageMenuItem("Stop") self.restart = gtk.ImageMenuItem("Restart") self.status = gtk.ImageMenuItem("Status") self.start.show() self.stop.show() self.r...
Create daemon submenu
380,716
def putParamset(self, remote, address, paramset, value): if self._server is not None: return self._server.putParamset(remote, address, paramset, value)
Set paramsets manually
380,717
def on_before_trading(self, date_time): if self.cta_call[] > 0: self.cta_call[] += 1 if self.cta_put[] > 0: self.cta_put[] += 1 self.cta_call[] = False self.cta_put[] = False
开盘的时候检查,如果有持仓,就把持有天数 + 1
380,718
def print_task_output(batch_client, job_id, task_ids, encoding=None): for task_id in task_ids: file_text = read_task_file_as_string( batch_client, job_id, task_id, _STANDARD_OUT_FILE_NAME, encoding) print("{} content for task {}: ".for...
Prints the stdout and stderr for each task specified. Originally in azure-batch-samples.Python.Batch.common.helpers :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :param str job_id: The id of the job to monitor. :param task_ids: The collect...
380,719
def render_tag(self, context, kwargs, nodelist): self.load_configuration(**kwargs) request = context[] self.full_path = request.get_full_path() context.push() content = nodelist.render(context) context.pop() ...
render content with "active" urls logic
380,720
def find_in_registry(category = None, namespace = None, name = None): selected_registry = registry if category is not None: selected_registry = [re for re in selected_registry if re.category==category] if namespace is not None: selected_registry = [re for re in selected_registry if re.n...
Find a given category/namespace/name combination in the registry category - string, see utils.inputs.registrycategories namespace - module namespace, see settings.NAMESPACE name - lowercase name of module
380,721
def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None): tdos = self.y if len(self.ydim) == 1 else np.sum(self.y, axis=1) if not abs_tol: tol = tol * tdos.sum() / tdos.shape[0] energies = self.x below_fermi = [i for i in range(len(energies)) ...
Expects a DOS object and finds the gap Args: tol: tolerance in occupations for determining the gap abs_tol: Set to True for an absolute tolerance and False for a relative one. spin: Possible values are None - finds the gap in the summed densit...
380,722
def commit(self): assert self.batch is not None, "No active batch, call start() first" logger.debug("Comitting batch from %d sources...", len(self.batch)) by_priority = [] for name in self.batch.keys(): priority = self.priorities.get(name, self.default_pri...
Commit a batch.
380,723
def list(self, all_pages=False, **kwargs): self._separate(kwargs) return super(Resource, self).list(all_pages=all_pages, **kwargs)
Return a list of notification templates. Note here configuration-related fields like 'notification_configuration' and 'channels' will not be used even provided. If one or more filters are provided through keyword arguments, filter the results accordingly. If no filters...
380,724
def inheritance_patch(attrs): for key, obj in attrs.items(): if isinstance(obj, attribute): if getattr(obj, , None) == AttrWriteType.READ_WRITE: if not getattr(obj, , None): method_name = obj.write_method_name or "write_" + key obj.fse...
Patch tango objects before they are processed by the metaclass.
380,725
def inherit_kwargs(inherit_func): import utool as ut keys, is_arbitrary = ut.get_kwargs(inherit_func) if is_arbitrary: keys += [] kwargs_append = .join(keys) def _wrp(func): if func.__doc__ is None: func.__doc__ = kwargs_block = + ut.inde...
TODO move to util_decor inherit_func = inspect_pdfs func = encoder.visualize.im_func
380,726
def get_vcs_details_output_vcs_details_node_vcs_mode(self, **kwargs): config = ET.Element("config") get_vcs_details = ET.Element("get_vcs_details") config = get_vcs_details output = ET.SubElement(get_vcs_details, "output") vcs_details = ET.SubElement(output, "vcs-details...
Auto Generated Code
380,727
def bug(self, container: Container) -> Bug: name = container.bug return self.__installation.bugs[name]
Returns a description of the bug inside a given container.
380,728
def debug(sequence): points = [] for i, p in enumerate(sequence): copy = Point(p) copy[] = i points.append(copy) return sequence.__class__(points)
adds information to the sequence for better debugging, currently only an index property on each point in the sequence.
380,729
def get_device_info(self, bigip): coll = bigip.tm.cm.devices.get_collection() device = [device for device in coll if device.selfDevice == ] assert len(device) == 1 return device[0]
Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object
380,730
def actions(connection): session = _make_session(connection=connection) for action in Action.ls(session=session): click.echo(f)
List all actions.
380,731
def asini(b, orbit, solve_for=None): orbit_ps = _get_system_ps(b, orbit) metawargs = orbit_ps.meta metawargs.pop() sma_def = FloatParameter(qualifier=, value=8.0, default_unit=u.solRad, description=) incl_def = FloatParameter(qualifier=, value=90.0, default_unit=u.deg, de...
Create a constraint for asini in an orbit. If any of the required parameters ('asini', 'sma', 'incl') do not exist in the orbit, they will be created. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should be built ...
380,732
def ControlFromHandle(handle: int) -> Control: return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))
Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass.
380,733
def get(self, request, **resources): instance = resources.get(self._meta.name) if not instance is None: return instance return self.paginate( request, self.get_collection(request, **resources))
Default GET method. Return instance (collection) by model. :return object: instance or collection from self model
380,734
def imslic(img, n_segments=100, aspect=None): from skimage.segmentation import (slic, mark_boundaries) from skimage.morphology import (dilation) if img.ndim == 2 or img.ndim == 3 and img.shape[-1] == 1: imz = np.stack([img, img, img], 2) else: imz = img slics = slic(imz, n_seg...
slic args : n_segments=100, compactness=10., max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3, slic_zero=False mark_boundaries args: label_img, color=(1, 1, 0), outline_color=None, mode='outer', background...
380,735
def set_to_cache(self): queryset = self.get_queryset() cache.set(self._get_cache_key(), { : [ queryset.none(), queryset.query, ], : self.__class__, : tuple(self.search_fields), ...
Add widget's attributes to Django's cache. Split the QuerySet, to not pickle the result set.
380,736
def parse_file(path, format=None, encoding=, force_types=True): try: with open(path, ) as f: return parse(f, format, encoding, force_types) except EnvironmentError as e: raise AnyMarkupError(e, traceback.format_exc())
A convenience wrapper of parse, which accepts path of file to parse. Args: path: path to file to parse format: explicitly override the guessed `inp` markup format encoding: file encoding, defaults to utf-8 force_types: if `True`, integers, floats, booleans and none/null ...
380,737
def experiment_completed(self): heroku_app = HerokuApp(self.app_id) status_url = "{}/summary".format(heroku_app.url) data = {} try: resp = requests.get(status_url) data = resp.json() except (ValueError, requests.exceptions.RequestException): ...
Checks the current state of the experiment to see whether it has completed. This makes use of the experiment server `/summary` route, which in turn uses :meth:`~Experiment.is_complete`.
380,738
def is_disabled_action(view): if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, , None) return action in view.disabled_actions if action is not None else False
Checks whether Link action is disabled.
380,739
def recv(self): try: items = self.poller.poll(self.timeout) except KeyboardInterrupt: return if items: msg = self.client.recv_multipart() self.close() if self.verbose: logging.info("I: received r...
Returns the reply message or None if there was no reply.
380,740
def _parse_results(self, raw_results, includes_qualifiers): results = [] for res in raw_results: item = CaseInsensitiveDict() for prop_name in self.property_names: item[prop_name] = None for wmi_property in res.Prope...
Parse WMI query results in a more comprehensive form. Returns: List of WMI objects ``` [ { 'freemegabytes': 19742.0, 'name': 'C:', 'avgdiskbytesperwrite': 1536.0 }, { 'freemegabytes': 19742.0, ...
380,741
def select_rows(self, rows): self.values = self.values.iloc[rows] self.index = self.index.iloc[rows, :] for prop in self._property_columns: vals = getattr(self, prop)[rows] setattr(self, prop, vals)
Truncate internal arrays to keep only the specified rows. Args: rows (array): An integer or boolean array identifying the indices of rows to keep.
380,742
def atomic_to_cim_xml(obj): if obj is None: return obj elif isinstance(obj, six.text_type): return obj elif isinstance(obj, six.binary_type): return _to_unicode(obj) elif isinstance(obj, bool): return u if obj else u elif isinstance(obj, (CIMInt, six.integer_ty...
Convert an "atomic" scalar value to a CIM-XML string and return that string. The returned CIM-XML string is ready for use as the text of a CIM-XML 'VALUE' element. Parameters: obj (:term:`CIM data type`, :term:`number`, :class:`py:datetime`): The "atomic" input value. May be `None`. ...
380,743
def get_season_player_stats(self, season_key, player_key): season_player_stats_url = self.api_path + "season/" + season_key + "/player/" + player_key + "/stats/" response = self.get_response(season_player_stats_url) return response
Calling Season Player Stats API. Arg: season_key: key of the season player_key: key of the player Return: json data
380,744
def _drop_schema(self, force_drop=False): connection = connections[get_tenant_database_alias()] has_schema = hasattr(connection, ) if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exception("Cans own schema or " ...
Drops the schema
380,745
def predict_moments(self, X): check_is_fitted(self, [, , , , ]) X = check_array(X) Phi = self.basis.transform(X, *atleast_list(self.hypers_)) Ey = Phi.dot(self.weights_) Vf = (Phi.dot(self.covariance_) * Phi).sum(axis=1) return Ey...
Full predictive distribution from Bayesian linear regression. Parameters ---------- X : ndarray (N*,d) array query input dataset (N* samples, d dimensions). Returns ------- Ey : ndarray The expected value of y* for the query inputs, X* of shape (...
380,746
def add_ecc_cgw(psr, gwtheta, gwphi, mc, dist, F, inc, psi, gamma0, e0, l0, q, nmax=100, nset=None, pd=None, periEv=True, psrTerm=True, tref=0, check=True, useFile=True): cosgwtheta, cosgwphi = N.cos(gwtheta), N.cos(gwphi) singwtheta, singwphi = N.sin(gwtheta), N.s...
Simulate GW from eccentric SMBHB. Waveform models from Taylor et al. (2015) and Barack and Cutler (2004). WARNING: This residual waveform is only accurate if the GW frequency is not significantly evolving over the observation time of the pulsar. :param psr: pulsar object :param gwtheta: Polar...
380,747
def jsonify_payload(self): if isinstance(self.payload, string_types): return self.payload return json.dumps(self.payload, cls=StandardJSONEncoder)
Dump the payload to JSON
380,748
def _get_client(self): return (_oss.StsAuth if in self._storage_parameters else _oss.Auth if self._storage_parameters else _oss.AnonymousAuth)(**self._storage_parameters)
OSS2 Auth client Returns: oss2.Auth or oss2.StsAuth: client
380,749
def pool_info(name=None, **kwargs): * result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): states = [, , , , ] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else desc = ElementTree.fromstring(pool.XMLDesc()) pa...
Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is...
380,750
def return_buffer_contents(self, frame, force_unescaped=False): if not force_unescaped: if frame.eval_ctx.volatile: self.writeline() self.indent() self.writeline( % frame.buffer) self.outdent() self.writeline() ...
Return the buffer contents of the frame.
380,751
def _encode_secret_part_v2_v3(version, condition, root_key, ns): data = bytearray() data.append(version) encode_uvarint(len(root_key), data) data.extend(root_key) if version >= VERSION_3: encode_uvarint(len(ns), data) data.extend(ns) data.extend(condition.encode()) retur...
Creates a version 2 or version 3 secret part of the third party caveat. The returned data is not encrypted. The format has the following packed binary fields: version 2 or 3 [1 byte] root key length [n: uvarint] root key [n bytes] namespace length [n: uvarint] (v3 only) namespace [n bytes] ...
380,752
def ciphertext(self, be_secure=True): if be_secure and not self.__is_obfuscated: self.obfuscate() return self.__ciphertext
Return the ciphertext of the EncryptedNumber. Choosing a random number is slow. Therefore, methods like :meth:`__add__` and :meth:`__mul__` take a shortcut and do not follow Paillier encryption fully - every encrypted sum or product should be multiplied by r ** :attr:`~PaillierP...
380,753
def make_site_obj(argdict): d = os.getcwd() if in argdict: d = argdict[] try: s = s2site.Site(d) except: print "Could not instantiate site object." sys.exit() return s
Instantiate and return the site. This will be used for all commands
380,754
def fromstring(cls, dis_string): temp = tempfile.NamedTemporaryFile(delete=False) temp.write(dis_string) temp.close() dis_tree = cls(dis_filepath=temp.name) os.unlink(temp.name) return dis_tree
Create a DisRSTTree instance from a string containing a *.dis parse.
380,755
def RACCU_calc(TOP, P, POP): try: result = ((TOP + P) / (2 * POP))**2 return result except Exception: return "None"
Calculate RACCU (Random accuracy unbiased). :param TOP: test outcome positive :type TOP : int :param P: condition positive :type P : int :param POP: population :type POP : int :return: RACCU as float
380,756
def remove_fetcher(self, fetcher): self._lock.acquire() try: for t, f in list(self._active_fetchers): if f is fetcher: self._active_fetchers.remove((t, f)) f._deactivated() return finally: ...
Remove a running fetcher from the list of active fetchers. :Parameters: - `fetcher`: fetcher instance. :Types: - `fetcher`: `CacheFetcher`
380,757
def close(self, suppress_logging=False): for publisher in self.publishers: try: publisher.close() except Exception as e: self.logger.error(.format(self.name, e), exc_info=not suppress_logging) self.publish...
purges all connections. method closes ampq connection (disconnects)
380,758
def handle_key_rotate(self, now): to_rotate = False dfn = os.path.join(self.opts[], ) try: stats = os.stat(dfn) salt.utils.master.ping_all_connected_minions(self.opts)
Rotate the AES key rotation
380,759
def clone(cls, repo_location, repo_dir=None, branch_or_tag=None, temp=False): if temp: reponame = repo_location.rsplit(, 1)[-1] suffix = % .join( [str(x) for x in (reponame, branch_or_tag) if x]) repo_dir = create_tempdir(suffix=suffix,...
Clone repo at repo_location into repo_dir and checkout branch_or_tag. Defaults into current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be cloned into it. The tempdir is scheduled for deletion (...
380,760
def trimquants(self, col: str, inf: float, sup: float): try: self.df = self._trimquants(col, inf, sup) except Exception as e: self.err(e, self.trimquants, "Can not trim quantiles")
Remove superior and inferior quantiles from the dataframe :param col: column name :type col: str :param inf: inferior quantile :type inf: float :param sup: superior quantile :type sup: float :example: ``ds.trimquants("Col 1", 0.01, 0.99)``
380,761
def mine_get(tgt, fun, tgt_type=, opts=None): mine, pass in the target, function to look up and the target type minions,minions/{0}mine') if not isinstance(mdata, dict): continue if not _ret_dict and functions and functions[0] in mdata: ret[minion] = mdata.get(func...
Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type
380,762
def GetElapsedMs(self): counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetElapsedMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value counts milliseconds, regardless of ...
380,763
def moments_XX(X, remove_mean=False, modify_data=False, weights=None, sparse_mode=, sparse_tol=0.0, column_selection=None, diag_only=False): r if weights is not None: assert X.shape[0] == weights.shape[0], if diag_only and sparse_mode is not : if sparse_mode is : ...
r""" Computes the first two unnormalized moments of X Computes :math:`s = \sum_t x_t` and :math:`C = X^\top X` while exploiting zero or constant columns in the data matrix. Parameters ---------- X : ndarray (T, M) Data matrix remove_mean : bool True: remove column mean from the...
380,764
def _set_shape(self, shape): try: shape = (int(shape),) except TypeError: pass shp = list(shape) shp[0] = timetools.Period()/self.simulationstep shp[0] = int(numpy.ceil(round(shp[0], 10))) getattr(self.fastaccess, self.name).ratios = numpy...
Private on purpose.
380,765
def get_me(self): response = self.request_json(self.config[]) user = objects.Redditor(self, response[], response) user.__class__ = objects.LoggedInRedditor return user
Return a LoggedInRedditor object. Note: This function is only intended to be used with an 'identity' providing OAuth2 grant.
380,766
def colorize_text(self, text): result = text result = self.colorize_heading(result) result = self.colorize_block_indent(result) result = self.colorize_backticks(result) re...
Colorize the text.
380,767
def _values(self): if self.interpolate: return [ val[0] for serie in self.series for val in serie.interpolated ] else: return super(Line, self)._values
Getter for series values (flattened)
380,768
def process_event(self, event, ipmicmd, seldata): event[] = None evdata = event[] if evdata[0] & 0b11000000 == 0b10000000: event[] = evdata[1] if evdata[0] & 0b110000 == 0b100000: event[] = evdata[2]
Modify an event according with OEM understanding. Given an event, allow an OEM module to augment it. For example, event data fields can have OEM bytes. Other times an OEM may wish to apply some transform to some field to suit their conventions.
380,769
def publish_topology_closed(self, topology_id): event = TopologyClosedEvent(topology_id) for subscriber in self.__topology_listeners: try: subscriber.closed(event) except Exception: _handle_exception()
Publish a TopologyClosedEvent to all topology listeners. :Parameters: - `topology_id`: A unique identifier for the topology this server is a part of.
380,770
def select_pane(self, target_pane): if target_pane in [, , , , ]: proc = self.cmd(, % self.id, target_pane) else: proc = self.cmd(, % target_pane) if proc.stderr: raise exc.LibTmuxException(proc.stderr) return self.attached_pane
Return selected :class:`Pane` through ``$ tmux select-pane``. Parameters ---------- target_pane : str 'target_pane', '-U' ,'-D', '-L', '-R', or '-l'. Return ------ :class:`Pane`
380,771
def company(random=random, *args, **kwargs): return random.choice([ "faculty of applied {noun}", "{noun}{second_noun} studios", "{noun}{noun}{noun} studios", "{noun}shop", "{noun} studies department", "the law offices of {lastname}, {noun}, and {other_lastname}",...
Produce a company name >>> mock_random.seed(0) >>> company(random=mock_random) 'faculty of applied chimp' >>> mock_random.seed(1) >>> company(random=mock_random) 'blistersecret studios' >>> mock_random.seed(2) >>> company(random=mock_random) 'pooppooppoop studios' >>> mock_rando...
380,772
def _create_sot_file(self): try: self._delete_file(filename="sot_file") except Exception: pass commands = [ "terminal dont-ask", "checkpoint file sot_file", "no terminal dont-ask", ] self._sen...
Create Source of Truth file to compare.
380,773
def discover_modules(self): sphinxsphinx.util\.util$sphinx.util modules = [self.package_name] for dirpath, dirnames, filenames in os.walk(self.root_path): root_uri = self._path2uri(os.path.join(self.root_path, d...
Return module sequence discovered from ``self.package_name`` Parameters ---------- None Returns ------- mods : sequence Sequence of module names within ``self.package_name`` Examples -------- >>> dw = ApiDocWriter('sphinx') ...
380,774
def add_page_if_missing(request): try: page = Page.objects.for_request(request, best_match=True) return { : page, : page, } except Page.DoesNotExist: return {}
Returns ``feincms_page`` for request.
380,775
def update(self, reseed): if self._clear: for i in range(0, 3): self._screen.print_at(" ", self._x, self._screen.start_line + self._y + i) self._maybe_reseed(reseed) else: ...
Update that trail! :param reseed: Whether we are in the normal reseed cycle or not.
380,776
def evaluate_world_model( real_env, hparams, world_model_dir, debug_video_path, split=tf.estimator.ModeKeys.EVAL, ): frame_stack_size = hparams.frame_stack_size rollout_subsequences = [] def initial_frame_chooser(batch_size): assert batch_size == len(rollout_subsequences) return np.stack([ ...
Evaluate the world model (reward accuracy).
380,777
def get_too_few_non_zero_degree_day_warning( model_type, balance_point, degree_day_type, degree_days, minimum_non_zero ): warnings = [] n_non_zero = int((degree_days > 0).sum()) if n_non_zero < minimum_non_zero: warnings.append( EEMeterWarning( qualified_name=( ...
Return an empty list or a single warning wrapped in a list regarding non-zero degree days for a set of degree days. Parameters ---------- model_type : :any:`str` Model type (e.g., ``'cdd_hdd'``). balance_point : :any:`float` The balance point in question. degree_day_type : :any:...
380,778
def setWidth(self, vehID, width): self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_WIDTH, vehID, width)
setWidth(string, double) -> None Sets the width in m for this vehicle.
380,779
def get_preview_name(self): if self.safe_type == EsaSafeType.OLD_TYPE: name = _edit_name(self.tile_id, AwsConstants.PVI, delete_end=True) else: name = .join([self.tile_id.split()[1], self.get_datatake_time(), AwsConstants.PVI]) return .format(name)
Returns .SAFE name of full resolution L1C preview :return: name of preview file :rtype: str
380,780
def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policie...
Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]"
380,781
def create(self, vals, check=True): if not and in vals: tmp_room_lines = vals.get(, []) vals[] = vals.get(, ) vals.update({: []}) folio_id = super(HotelFolio, self).create(vals) for line in (tmp_room_lines): line[2].update({:...
Overrides orm create method. @param self: The object pointer @param vals: dictionary of fields value. @return: new record set for hotel folio.
380,782
def create_index(self): es = self._init_connection() if not es.indices.exists(index=self.index): es.indices.create(index=self.index, body=self.settings)
Override to provide code for creating the target index. By default it will be created without any special settings or mappings.
380,783
def get_account_info(self): headers = self._manager.get_account_headers() return (headers.get("x-account-container-count"), headers.get("x-account-bytes-used"))
Returns a tuple for the number of containers and total bytes in the account.
380,784
def get_package_path(name): name = name.lower() pkg = importlib.import_module(name) return Path(pkg.__file__).parent
Get the path to an installed package. name (unicode): Package name. RETURNS (Path): Path to installed package.
380,785
def write_incron_file_verbose(user, path): s incrontab and return error message on error CLI Example: .. code-block:: bash salt incron.write_incron_file_verbose root /tmp/new_incron cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False)
Writes the contents of a file to a user's incrontab and return error message on error CLI Example: .. code-block:: bash salt '*' incron.write_incron_file_verbose root /tmp/new_incron
380,786
def I(r, limbdark): if limbdark.ldmodel == QUADRATIC: u1 = limbdark.u1 u2 = limbdark.u2 return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == KIPPING: a = np.sqrt(limbdark.q1) b = 2*limbdark.q2 u1 = a*b u2 = a*(1 - b) return (1...
The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r`
380,787
def _output_function_label(self): if self.asm_code: return True if not self.blocks: return True the_block = next((b for b in self.blocks if b.addr == self.addr), None) if the_block is None: return True if not the_block.instructions: ...
Determines if we want to output the function label in assembly. We output the function label only when the original instruction does not output the function label. :return: True if we should output the function label, False otherwise. :rtype: bool
380,788
def create(self, acl=None): parent, name = getParentAndBase(self.path) json = { : name } if acl is not None: json[] = acl.to_api_param() response = self.client.postJsonHelper(DataDirectory._getUrl(parent), json, False) if (response.status_code != 200): ...
Creates a directory, optionally include Acl argument to set permissions
380,789
def extract_files_from_dict(d): files = {} for key, value in six.iteritems(d): if isinstance(value, dict): files[key] = extract_files_from_dict(value) elif is_file_like(value): files[key] = value return files
Return any file objects from the provided dict. >>> extract_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... }}) # doctest:+ELLIPSIS {'track': {'asset_data': <...}}
380,790
def from_raw_script(cls, raw_script): script = format_raw_script(raw_script) if not script: raise EmptyCommand expanded = shell.from_shell(script) output = get_output(script, expanded) return cls(expanded, output)
Creates instance of `Command` from a list of script parts. :type raw_script: [basestring] :rtype: Command :raises: EmptyCommand
380,791
def are_equal(self, sp1, sp2): for s1 in sp1.keys(): spin1 = getattr(s1, "spin", 0) oxi1 = getattr(s1, "oxi_state", 0) for s2 in sp2.keys(): spin2 = getattr(s2, "spin", 0) oxi2 = getattr(s2, "oxi_state", 0) if (s1.symbo...
True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa. Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. s...
380,792
def output(self, _filename): txt = for c in self.contracts: txt += "\nContract %s\n"%c.name table = PrettyTable([, ]) for v in c.state_variables: table.add_row([v.name, _get(v, c)]) txt += str(table) txt += "\n" ...
_filename is not used Args: _filename(string)
380,793
def radviz(X, y=None, ax=None, features=None, classes=None, color=None, colormap=None, alpha=1.0, **kwargs): visualizer = RadialVisualizer( ax, features, classes, color, colormap, alpha, **kwargs ) visualizer.fit(X, y, **kwargs) visualizer.transform(X) return...
Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance. This helper function is a quick wrapper to utilize the RadialVisualizer (Transformer) for one-off analysis. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
380,794
def _load_assembly_mapping_data(filename): try: assembly_mapping_data = {} with tarfile.open(filename, "r") as tar: for member in tar.getmembers(): if ".json" in member.name: with tar.extractfile(membe...
Load assembly mapping data. Parameters ---------- filename : str path to compressed archive with assembly mapping data Returns ------- assembly_mapping_data : dict dict of assembly maps if loading was successful, else None Notes ...
380,795
def _validate_data(data): data_keys = set(data.keys()) extra_keys = data_keys - set(ALLOWED_KEYS) missing_keys = set(REQUIRED_KEYS) - data_keys if extra_keys: raise ValueError( .format(.join(extra_keys)) ) if missing_keys: raise ValueError( .for...
Validates the given data and raises an error if any non-allowed keys are provided or any required keys are missing. :param data: Data to send to API :type data: dict
380,796
def _analyze_variable_attributes(self, attributes): if in attributes: self._indexed = attributes[] super(EventVariableSolc, self)._analyze_variable_attributes(attributes)
Analyze event variable attributes :param attributes: The event variable attributes to parse. :return: None
380,797
def _EvaluateElementsDataSize(self, context): elements_data_size = None if self._data_type_definition.elements_data_size: elements_data_size = self._data_type_definition.elements_data_size elif self._data_type_definition.elements_data_size_expression: expression = self._data_type_definitio...
Evaluates elements data size. Args: context (DataTypeMapContext): data type map context. Returns: int: elements data size. Raises: MappingError: if the elements data size cannot be determined.
380,798
def p0f_impersonate(pkt, osgenre=None, osdetails=None, signature=None, extrahops=0, mtu=1500, uptime=None): pkt = pkt.copy() while pkt.haslayer(IP) and pkt.haslayer(TCP): pkt = pkt.getlayer(IP) if isinstance(pkt.payload, TCP): break pkt = pkt.pay...
Modifies pkt so that p0f will think it has been sent by a specific OS. If osdetails is None, then we randomly pick up a personality matching osgenre. If osgenre and signature are also None, we use a local signature (using p0f_getlocalsigs). If signature is specified (as a tuple), we use the signature. For now, only T...
380,799
def GetLocations(): r = clc.v1.API.Call(,,{}) if r[] != True: if clc.args: clc.v1.output.Status(,3, % (,r[],r[])) raise Exception( % (,r[],r[])) elif int(r[]) == 0: clc.LOCATIONS = [x[] for x in r[]] return(r[])
Return all cloud locations available to the calling alias.