Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,400
def search_upstream(self, device: devicetools.Device, name: str = ) -> : try: selection = Selection(name) if isinstance(device, devicetools.Node): node = self.nodes[device.name] return self.__get_nextnode(node, selection) ...
Return the network upstream of the given starting point, including the starting point itself. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() You can pass both |Node| and |Element| objects and, optionally, the name of the new...
365,401
def generate(self, text): if not text: raise Exception("No text to speak") if len(text) >= self.MAX_CHARS: raise Exception("Number of characters must be less than 2000") params = self.__params.copy() params["text"] = text self._data = requests.g...
Try to get the generated file. Args: text: The text that you want to generate.
365,402
def currentItemChanged(self, _currentIndex=None, _previousIndex=None): self.editor.clear() self.editor.setTextColor(QCOLOR_REGULAR) regItem = self.getCurrentRegItem() if regItem is None: return if self._importOnSelect and regItem.successfullyImported is No...
Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored.
365,403
def format_filename(self, data, row): return self.filename.format(**self.filename_formatters(data, row))
Returns a formatted filename using the template stored in self.filename - `data`: vaping message - `row`: vaping message data row
365,404
def trace_memory_usage(self, frame, event, arg): if (event in (, , ) and frame.f_code in self.code_map): if event != : mem = _get_memory(-1, include_children=self.include_children) old_mem = self.code_map[fram...
Callback for sys.settrace
365,405
def _assemble_lsid(self, module_number): if self.base_lsid is None: raise Exception("Base LSID in LSID authority not initialized") return self.base_lsid + ":" + str(module_number)
Return an assembled LSID based off the provided module number and the authority's base LSID. Note: Never includes the module's version number. :param module_number: :return: string
365,406
def set_menu(self, menu): self.menu = menu self.in_queue.put(MPImageMenu(menu))
set a MPTopMenu on the frame
365,407
def decrypt(key, ciphertext): index = 0 decrypted = "" for char in ciphertext: if char in string.punctuation + string.whitespace + string.digits: decrypted += char continue alphabet = string.ascii_uppercase if key[index].isupper() else string.ascii_lo...
Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext
365,408
def print_table(seqs, id2name, name): itable = open( % (name.rsplit(, 1)[0]), ) print(.join([, , , , , , , , , , , , ]), file=itable) for seq, info in list(seqs.items()): gene, model, insertions = info name = id2name[seq] for i, ins in enumerate(insertions, 1): gene_...
print table of results # seqs[id] = [gene, model, [[i-gene_pos, i-model_pos, i-length, iseq, [orfs], [introns], orfs?, introns?], ...]]
365,409
def datastore(self, domain, data_type, mapping=None): from .tcex_datastore import TcExDataStore return TcExDataStore(self, domain, data_type, mapping)
Get instance of the DataStore module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writi...
365,410
def create_dataset(args): if not in args.full_path and args.vault and args.path: full_path, path_dict = Object.validate_full_path( .format(args.vault, args.path, args.full_path)) else: full_path, path_dict = Object.validate_full_path( args.f...
Attempt to create a new dataset given the following params: * template_id * template_file * capacity * create_vault * [argument] dataset name or full path NOTE: genome_build has been deprecated and is no longer used.
365,411
def delete_actions(self, form_id, action_ids): response = self._client.session.delete( .format( url=self.endpoint_url, form_id=form_id ), params={: action_ids} ) return self.process_response(response)
Remove actions from a form :param form_id: int :param action_ids: list|tuple :return: dict|str
365,412
def getitem_column_array(self, key): numeric_indices = list(self.columns.get_indexer_for(key)) def getitem(df, internal_indices=[]): return df.iloc[:, internal_indices] result = self.data.apply_func_to_select_indices( 0, getitem, nume...
Get column data for target labels. Args: key: Target labels by which to retrieve data. Returns: A new QueryCompiler.
365,413
def _find_countour_yaml(start, checked, names=None): extensions = [] if names: for name in names: if not os.path.splitext(name)[1]: extensions.append(name + ".yaml") extensions.append(name + ".yml") yaml_names = (names or []) + CONTOUR_YAML_NAMES + ...
Traverse the directory tree identified by start until a directory already in checked is encountered or the path of countour.yaml is found. Checked is present both to make the loop termination easy to reason about and so the same directories do not get rechecked Args: start: the path to...
365,414
def _filter_attrs(self, feature, request): if in request.params: attrs = request.params[].split() props = feature.properties new_props = {} for name in attrs: if name in props: new_props[name] = props[name] ...
Remove some attributes from the feature and set the geometry to None in the feature based ``attrs`` and the ``no_geom`` parameters.
365,415
def flipcoords(xcoord, ycoord, axis): axis = axis.lower() if axis == : if xcoord > 0: return str(xcoord - xcoord - xcoord) + + str(ycoord) elif xcoord < 0: return str(xcoord + abs(xcoord) * 2) + + str(ycoord) elif xcoord == 0: return str(xcoord...
Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip across. Could be 'x' or 'y'
365,416
def lxml(self) -> _LXML: if self._lxml is None: self._lxml = etree.fromstring(self.raw_xml) return self._lxml
`lxml <http://lxml.de>`_ representation of the :class:`Element <Element>` or :class:`XML <XML>`.
365,417
def read_fwf(filepath_or_buffer: FilePathOrBuffer, colspecs=, widths=None, infer_nrows=100, **kwds): r if colspecs is None and widths is None: raise ValueError("Must specify either colspecs or widths") elif colspecs not in (None, ) and width...
r""" Read a table of fixed-width formatted lines into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the `online docs for IO Tools <http://pandas.pydata.org/pandas-docs/stable/io.html>`_. Parameters ---------- filepat...
365,418
def write_logfile(): command = os.path.basename(os.path.realpath(os.path.abspath(sys.argv[0]))) now = datetime.datetime.now().strftime() filename = .format(command, now) with open(filename, ) as logfile: if six.PY3: logfile.write(_LOGFILE_STREAM.getvalue()) else: ...
Write a DEBUG log file COMMAND-YYYYMMDD-HHMMSS.ffffff.log.
365,419
def _is_match(self, response, answer): def compare_conditions(droppable_id, spatial_units, response_conditions): coordinate_match = True for coordinate in response_conditions[][][droppable_id]: answer_match = False for spatial_unit i...
Does the response match the answer
365,420
def cache_cluster_present(name, wait=900, security_groups=None, region=None, key=None, keyid=None, profile=None, **args): names not provided. ReplicationGroupId The ID of the replication group to which this cache cluster should belong. If this parameter is ...
Ensure a given cache cluster exists. name Name of the cache cluster (cache cluster id). wait Integer describing how long, in seconds, to wait for confirmation from AWS that the resource is in the desired state. Zero meaning to return success or failure immediately of course. ...
365,421
def freeze(value): if isinstance(value, list): return FrozenList(*value) if isinstance(value, dict): return FrozenDict(**value) return value
Cast value to its frozen counterpart.
365,422
def combine_calls(*args): if len(args) == 3: is_cwl = False batch_id, samples, data = args caller_names, vrn_files = _organize_variants(samples, batch_id) else: is_cwl = True samples = [utils.to_single_data(x) for x in args] samples = [cwlutils.unpack_tarball...
Combine multiple callsets into a final set of merged calls.
365,423
def _sslobj(sock): pass if isinstance(sock._sslobj, _ssl._SSLSocket): return sock._sslobj else: return sock._sslobj._sslobj
Returns the underlying PySLLSocket object with which the C extension functions interface.
365,424
def request_sensor_value(self, req, msg): exact, name_filter = construct_name_filter(msg.arguments[0] if msg.arguments else None) sensors = [(name, sensor) for name, sensor in sorted(self._sensors.iteritems()) if name_filter(...
Request the value of a sensor or sensors. A list of sensor values as a sequence of #sensor-value informs. Parameters ---------- name : str, optional Name of the sensor to poll (the default is to send values for all sensors). If name starts and ends with '/' it i...
365,425
def BIC(self,data=None): s assigned data Must have data to get BIC' if data is None: return -2*sum(self.log_likelihood(s.data).sum() for s in self.states_list) + \ self.num_parameters() * np.log( sum(s.data.shape[0] for s in sel...
BIC on the passed data. If passed data is None (default), calculates BIC on the model's assigned data
365,426
def deps_used(self, pkg, used): if find_package(pkg + self.meta.sp, self.meta.pkg_path): if pkg not in self.deps_dict.values(): self.deps_dict[pkg] = used else: self.deps_dict[pkg] += used
Create dependencies dictionary
365,427
def Throughput(self): try: throughput = spectrum.TabularSpectralElement() product = self._multiplyThroughputs(0) throughput._wavetable = product.GetWaveSet() throughput._throughputtable = product(throughput._wavetable) throughput.waveunits =...
Combined throughput from multiplying all the components together. Returns ------- throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None` Combined throughput.
365,428
def clean(self): super(CTENode, self).clean() if self.parent and self.pk in getattr(self.parent, self._cte_node_path): raise ValidationError(_("A node cannot be made a descendant of itself."))
Prevents cycles in the tree.
365,429
def synthesize(self, duration): sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds)) return AudioSamples(samples, self.samplerate)
Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound
365,430
def int_global_to_local(self, index, axis=0): if index >= self.__mask[axis].stop-self.__halos[1][axis]: return None if index < self.__mask[axis].start+self.__halos[0][axis]: return None return index-self.__mask[axis].start
Calculate local index from global index for integer input :param index: global index as integer :param axis: current axis to process :return:
365,431
def format_number(col, d): sc = SparkContext._active_spark_context return Column(sc._jvm.functions.format_number(_to_java_column(col), d))
Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places with HALF_EVEN round mode, and returns the result as a string. :param col: the column name of the numeric value to be formatted :param d: the N decimal places >>> spark.createDataFrame([(5,)], ['a']).select(format_number...
365,432
def cd_previous(self): if self._prev_dir is None or isinstance(self._prev_dir, ROOT.TROOT): return False if isinstance(self._prev_dir, ROOT.TFile): if self._prev_dir.IsOpen() and self._prev_dir.IsWritable(): self._prev_dir.cd() return True...
cd to the gDirectory before this file was open.
365,433
def predict_proba(self, a, b, device=None): device = SETTINGS.get_default(device=device) if self.model is None: print() raise ValueError if len(np.array(a).shape) == 1: a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) ...
Infer causal directions using the trained NCC pairwise model. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``) Returns: float: Causation score (Va...
365,434
def declaration_path(decl): if not decl: return [] if not decl.cache.declaration_path: result = [decl.name] parent = decl.parent while parent: if parent.cache.declaration_path: result.reverse() decl.cache.declaration_path = parent...
Returns a list of parent declarations names. Args: decl (declaration_t): declaration for which declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and la...
365,435
def find_recipients_conversations(self, context=None, exclude=None, from_conversation_id=None, permissions=None, search=None, type=None, user_id=None): path = {} data = {} params = {} if search is not None: params["search"] = search ...
Find recipients. Find valid recipients (users, courses and groups) that the current user can send messages to. The /api/v1/search/recipients path is the preferred endpoint, /api/v1/conversations/find_recipients is deprecated. Pagination is supported.
365,436
def _get_full_model_smt_script(self, constraints=(), variables=()): smt_script = smt_script += smt_script += self._smtlib_exprs(variables) smt_script += self._smtlib_exprs(constraints) smt_script += smt_script += return smt_script
Returns a SMT script that declare all the symbols and constraint and checks their satisfiability (check-sat) :param extra-constraints: list of extra constraints that we want to evaluate only in the scope of this call :return string: smt-lib representation of th...
365,437
def frange(start, end, step): val = start while val < end: yield val val += step
Like range(), but with floats.
365,438
def _get_line_styles(marker_str): def _extract_marker_value(marker_str, code_dict): val = None for code in code_dict: if code in marker_str: val = code_dict[code] break return val return [_extract_marker_value(marker_str, code_di...
Return line style, color and marker type from specified marker string. For example, if ``marker_str`` is 'g-o' then the method returns ``('solid', 'green', 'circle')``.
365,439
def get_coordinates_xyz(filename): f = open(filename, ) V = list() atoms = list() n_atoms = 0 try: n_atoms = int(f.readline()) except ValueError: exit("error: Could not obtain the number of atoms in the .xyz file.") f.readline() for lines_read, lin...
Get coordinates from filename and return a vectorset with all the coordinates, in XYZ format. Parameters ---------- filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms
365,440
def setExpandedIcon( self, column, icon ): self._expandedIcon[column] = QtGui.QIcon(icon)
Sets the icon to be used when the item is expanded. :param column | <int> icon | <QtGui.QIcon> || None
365,441
def get_checking_block(self): checking_block = if self.eth_node is constants.EthClient.PARITY: checking_block = return checking_block
Workaround for parity https://github.com/paritytech/parity-ethereum/issues/9707 In parity doing any call() with the 'pending' block no longer falls back to the latest if no pending block is found but throws a mistaken error. Until that bug is fixed we need to enforce special behaviour for parity...
365,442
def pause(vm_): * with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, , vm_) if vm_uuid is False: return False try: xapi.VM.pause(vm_uuid) return True except Exception: return False
Pause the named vm CLI Example: .. code-block:: bash salt '*' virt.pause <vm name>
365,443
def ensure_dir_exists(directory): if directory and not os.path.exists(directory): os.makedirs(directory)
Se asegura de que un directorio exista.
365,444
def setitem_via_pathlist(ol,value,pathlist): abc this = ol for i in range(0,pathlist.__len__()-1): key = pathlist[i] this = this.__getitem__(key) this.__setitem__(pathlist[-1],value) return(ol)
from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] setitem_via_pathlist(y,"500",[1,1]) y
365,445
def connect(reactor, control_endpoint=None, password_function=None): @inlineCallbacks def try_endpoint(control_ep): assert IStreamClientEndpoint.providedBy(control_ep) proto = yield control_ep.connect( TorProtocolFactory( password_function=password_function ...
Creates a :class:`txtorcon.Tor` instance by connecting to an already-running tor's control port. For example, a common default tor uses is UNIXClientEndpoint(reactor, '/var/run/tor/control') or TCP4ClientEndpoint(reactor, 'localhost', 9051) If only password authentication is available in the tor we con...
365,446
def add_rule(self, ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip): rule = IPPermissions(self) rule.ip_protocol = ip_protocol rule.from_port = from_port rule.to_port = to_port self.rules.append(rule) rule.add_grant(s...
Add a rule to the SecurityGroup object. Note that this method only changes the local version of the object. No information is sent to EC2.
365,447
def check_column_existence(col_name, df, presence=True): if presence: if col_name not in df.columns: msg = "Ensure that `{}` is in `df.columns`." raise ValueError(msg.format(col_name)) else: if col_name in df.columns: msg = "Ensure that `{}` is not in `df...
Checks whether or not `col_name` is in `df` and raises a helpful error msg if the desired condition is not met. Parameters ---------- col_name : str. Should represent a column whose presence in `df` is to be checked. df : pandas DataFrame. The dataframe that will be checked for the ...
365,448
def set_reload_params( self, min_lifetime=None, max_lifetime=None, max_requests=None, max_requests_delta=None, max_addr_space=None, max_rss=None, max_uss=None, max_pss=None, max_addr_space_forced=None, max_rss_forced=None, watch_interval_forced=None, mercy=Non...
Sets workers reload parameters. :param int min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive for N seconds (default 60). This is an anti-fork-bomb measure. Since 1.9 :param int max_lifetime: Reload workers after this many seconds. Disabled by default....
365,449
def set_callbacks(self, **dic_functions): for action in self.interface.CALLBACKS: try: f = dic_functions[action] except KeyError: pass else: setattr(self.interface.callbacks, action, f) manquantes = [ ...
Register callbacks needed by the interface object
365,450
def clear_file(self, label): rm = self.my_osid_object_form._get_provider_manager() catalog_id_str = if in self.my_osid_object_form._my_map: catalog_id_str = self.my_osid_object_form._my_map[][0] elif in self.my_osid_object_form._my_map: catalog_id_st...
stub
365,451
def summed_probabilities(self, choosers, alternatives): def normalize(s): return s / s.sum() choosers, alternatives = self.apply_predict_filters( choosers, alternatives) probs = self.probabilities(choosers, alternatives, filter_tables=False) if...
Calculate total probability associated with each alternative. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. alternatives : pandas.DataFrame Table describing the things from which agents are choosing...
365,452
def king(self, color: Color) -> Optional[Square]: king_mask = self.occupied_co[color] & self.kings & ~self.promoted return msb(king_mask) if king_mask else None
Finds the king square of the given side. Returns ``None`` if there is no king of that color. In variants with king promotions, only non-promoted kings are considered.
365,453
def check_activation(self, contacts): now = time.time() was_is_in_effect = self.is_in_effect self.is_in_effect = (self.start_time <= now <= self.end_time) if not was_is_in_effect and self.is_in_effect: self.enter(contacts) if was_is_in_eff...
Enter or exit downtime if necessary :return: None
365,454
def socket(type, filename, line_nbr): return c_void_p(lib.zsys_socket(type, filename, line_nbr))
Get a new ZMQ socket, automagically creating a ZMQ context if this is the first time. Caller is responsible for destroying the ZMQ socket before process exits, to avoid a ZMQ deadlock. Note: you should not use this method in CZMQ apps, use zsock_new() instead. *** This is for CZMQ internal use only and may change arbit...
365,455
def encode(cls, value): val_encoding = def encode_str(v): try: v_enc = encode(v, val_encoding) except UnicodeDecodeError: if PY3: raise else: v_enc = v ...
Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. :rtype: bytes
365,456
def register(self, name, description, obj, plugin): if name in self._shared_objects.keys(): raise SharedObjectExistException("Shared Object %s already registered by %s" % (name, self._shared_objects[name].plugin.name)) new_shared_object ...
Registers a new shared object. :param name: Unique name for shared object :type name: str :param description: Description of shared object :type description: str :param obj: The object, which shall be shared :type obj: any type :param plugin: Plugin, which regist...
365,457
def get_context_data(self, **kwargs): self.request.session.set_test_cookie() if not self.request.session.test_cookie_worked(): messages.add_message( self.request, messages.ERROR, "Please enable cookies.") self.request.session.delete_test_cookie() retu...
Tests cookies.
365,458
def parse(cls, data): parsers = { : ([], Step.parse), : ([], Endpoint.parse), } for datum in data: assert isinstance(datum, dict) for type, (items, parse) in parsers.items(): if type in datum: items.appe...
Parse a Config structure out of a Python dict (that's likely deserialized from YAML). :param data: Config-y dict :type data: dict :return: Config object :rtype: valohai_yaml.objs.Config
365,459
def inv_diagonal(S): S = np.asarray(S) if S.ndim != 2 or S.shape[0] != S.shape[1]: raise ValueError() si = np.zeros(S.shape) for i in range(len(S)): si[i, i] = 1. / S[i, i] return si
Computes the inverse of a diagonal NxN np.array S. In general this will be much faster than calling np.linalg.inv(). However, does NOT check if the off diagonal elements are non-zero. So long as S is truly diagonal, the output is identical to np.linalg.inv(). Parameters ---------- S : np.array...
365,460
def inspect_container(self, container): return self._result( self._get(self._url("/containers/{0}/json", container)), True )
Identical to the `docker inspect` command, but only for containers. Args: container (str): The container to inspect Returns: (dict): Similar to the output of `docker inspect`, but as a single dict Raises: :py:class:`docker.errors.APIError` ...
365,461
def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): if fmtmap is None: fmtmap = {} fwdthn = fprec + fwdthdlt fldfmt = [fmtmap[lbl] if lbl in fmtmap else (( % (fwdth0)) if idx == 0 else (( % (fwdth...
Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (default None) A dict providing a mapping from field header strings to print format strings,...
365,462
def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]): _limit = 100 cnt = 0 if first < 0: first = 0 while True: txs = self.blockchain.rpc.get_account_history( self["id"], "1.11.{}".format(...
Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first transaction to return (*optional*) :param int last: sequence number of the...
365,463
def is_builtin(text): from spyder.py3compat import builtins return text in [str(name) for name in dir(builtins) if not name.startswith()]
Test if passed string is the name of a Python builtin object
365,464
def get_config(): * cmd = try: raw_config = _pshell(cmd, ignore_retcode=True) except CommandExecutionError as exc: if in exc.info[]: raise CommandExecutionError() raise config = dict() if raw_config: if in raw_config[0]: confi...
Get the current DSC Configuration Returns: dict: A dictionary representing the DSC Configuration on the machine Raises: CommandExecutionError: On failure CLI Example: .. code-block:: bash salt '*' dsc.get_config
365,465
def _get_generic_two_antidep_episodes_result( rowdata: Tuple[Any, ...] = None) -> DataFrame: data = [rowdata] if rowdata else [] return DataFrame(array( data, dtype=[ (RCN_PATIENT_ID, DTYPE_STRING), (RCN_DRUG_A_NAME, DTYPE_STRING), ...
Create a results row for this application.
365,466
def vcsNodeState_originator_switch_info_switchIdentifier(self, **kwargs): config = ET.Element("config") vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs") originator_switch_info = ET.SubElement(vcsNodeState, "originator-switch-info") s...
Auto Generated Code
365,467
def _kalman_prediction_step_SVD(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False, p_dm = None, p_dP = None): Prev_cov, S_old, V_old = p_P A = p_dyn_model_callable.Ak(k,p_m,Prev_cov) Q = p_dyn_model_...
Desctrete prediction function Input: k:int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time se...
365,468
def connect_signals(self, target): if self.connected: raise RuntimeError("GtkBuilder can only connect signals once") self.builder.connect_signals(target) self.connected = True
This is deprecated. Pass your controller to connect signals the old way.
365,469
def init_printing(*, reset=False, init_sympy=True, **kwargs): logger = logging.getLogger(__name__) if reset: SympyPrinter._global_settings = {} if init_sympy: if kwargs.get(, ) == : sympy_init_printing(use_unicode=True) if kwargs.get(, ) == : ...
Initialize the printing system. This determines the behavior of the :func:`ascii`, :func:`unicode`, and :func:`latex` functions, as well as the ``__str__`` and ``__repr__`` of any :class:`.Expression`. The routine may be called in one of two forms. First, :: init_printing( st...
365,470
def _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, scale:float=1.35) -> Iterator[List[Tensor]]: "Computes the outputs for several augmented inputs for TTA" dl = learn.dl(ds_type) ds = dl.dataset old = ds.tfms augm_tfm = [o for o in learn.data.train_ds.tfms if o.tfm not in ...
Computes the outputs for several augmented inputs for TTA
365,471
def rotateX(self, angle): rad = angle * math.pi / 180 cosa = math.cos(rad) sina = math.sin(rad) y = self.y * cosa - self.z * sina z = self.y * sina + self.z * cosa return Point3D(self.x, y, z)
Rotates the point around the X axis by the given angle in degrees.
365,472
def get_assessment_part_form(self, *args, **kwargs): if isinstance(args[-1], list) or in kwargs: return self.get_assessment_part_form_for_create(*args, **kwargs) else: return self.get_assessment_part_form_for_update(*args, **kwargs)
Pass through to provider AssessmentPartAdminSession.get_assessment_part_form_for_update
365,473
def _times_to_hours_after_local_midnight(times): times = times.tz_localize(None) hrs = 1 / NS_PER_HR * ( times.astype(np.int64) - times.normalize().astype(np.int64)) return np.array(hrs)
convert local pandas datetime indices to array of hours as floats
365,474
def assert_inbounds(num, low, high, msg=, eq=False, verbose=not util_arg.QUIET): r from utool import util_str if util_arg.NO_ASSERTS: return passed = util_alg.inbounds(num, low, high, eq=eq) if isinstance(passed, np.ndarray): passflag = np.all(passed) else: passflag = pas...
r""" Args: num (scalar): low (scalar): high (scalar): msg (str):
365,475
def from_coordinates(cls, coordinates, labels): from molmod.ext import molecules_distance_matrix distance_matrix = molecules_distance_matrix(coordinates) return cls(distance_matrix, labels)
Initialize a similarity descriptor Arguments: coordinates -- a Nx3 numpy array labels -- a list with integer labels used to identify atoms of the same type
365,476
def v(msg, *args, **kwargs): return logging.log(VERBOSE, msg, *args, **kwargs)
log a message at verbose level;
365,477
def add_response_signature(self, response_data, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1): return self.__build_signature(response_data, , sign_algorithm)
Builds the Signature of the SAML Response. :param response_data: The Response parameters :type response_data: dict :param sign_algorithm: Signature algorithm method :type sign_algorithm: string
365,478
def collect_mean(self, fitness_functions): if not self._need_mean_ff: return self._mean_ff_result.append(np.mean(fitness_functions))
! @brief Stores average value of fitness function among chromosomes on specific iteration. @param[in] fitness_functions (float): Average value of fitness functions among chromosomes.
365,479
def IncrementCounter(self, metric_name, delta=1, fields=None): if delta < 0: raise ValueError("Invalid increment for counter: %d." % delta) self._counter_metrics[metric_name].Increment(delta, fields)
See base class.
365,480
def wait_for_event(event): f = Future() def ready(): get_event_loop().remove_win32_handle(event) f.set_result(None) get_event_loop().add_win32_handle(event, ready) return f
Wraps a win32 event into a `Future` and wait for it.
365,481
def replicate_per_farm_dbs(cloud_url=None, local_url=None, farm_name=None): cloud_url = cloud_url or config["cloud_server"]["url"] local_url = local_url or config["local_server"]["url"] farm_name = farm_name or config["cloud_server"]["farm_name"] username = config["cloud_server"]["username"] pa...
Sete up replication of the per-farm databases from the local server to the cloud server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing the cloud server :param str local_url: Used to override the loca...
365,482
def pull(configuration, *resources): print("Pulling conf/locale/config.yaml:locales from Transifex...") for lang in configuration.translated_locales: cmd = .format(lang=lang) if resources: for resource in resources: execute(cmd + .format(resource=resource)) ...
Pull translations from all languages listed in conf/locale/config.yaml where there is at least 10% reviewed translations. If arguments are provided, they are specific resources to pull. Otherwise, all resources are pulled.
365,483
def execute_greenlet_async(func, *args, **kwargs): global _GREENLET_EXECUTOR if _GREENLET_EXECUTOR is None: _GREENLET_EXECUTOR = GreenletExecutor( num_greenlets=settings.node.greenlet_pool_size) return _GREENLET_EXECUTOR.submit(func, *args, **kwargs)
Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`.
365,484
def _set_bad_packet(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=bad_packet.bad_packet, is_container=, presence=True, yang_name="bad-packet", rest_name="bad-packet", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_...
Setter method for bad_packet, mapped from YANG variable /rbridge_id/router/ospf/log/bad_packet (container) If this variable is read-only (config: false) in the source YANG file, then _set_bad_packet is considered as a private method. Backends looking to populate this variable should do so via calling th...
365,485
def temp_dir(sub_dir=): user = getpass.getuser().replace(, ) current_date = date.today() date_string = current_date.isoformat() if in os.environ: new_directory = os.environ[] else: handle, filename = mkstemp() os.close(handle) new_directory = o...
Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a temporary directory under the inasafe wo...
365,486
def _track_change(self, name, value, formatter=None): self._emulation_log.track_change(self._emulation_address, name, value, formatter)
Track that a change happened. This function is only needed for manually recording changes that are not captured by changes to properties of this object that are tracked automatically. Classes that inherit from `emulation_mixin` should use this function to record interesting changes in ...
365,487
def view_vector(self, vector, viewup=None): focal_pt = self.center if viewup is None: viewup = rcParams[][] cpos = [vector + np.array(focal_pt), focal_pt, viewup] self.camera_position = cpos return self.reset_camera()
Point the camera in the direction of the given vector
365,488
def get_sorted_proposal_list(self): proposals = {} for proposal in self.proposals: proposals.setdefault(proposal.scope, []).append(proposal) result = [] for scope in self.scopepref: scope_proposals = proposals.get(scope, []) scope_proposals = ...
Return a list of `CodeAssistProposal`
365,489
def serialize_smarttag(ctx, document, el, root): "Serializes smarttag." if ctx.options[]: _span = etree.SubElement(root, , {: , : el.element}) else: _span = root for elem in el.elements: _ser = ctx.get_serializer(elem) if _ser: _td = _ser(ctx, document, ele...
Serializes smarttag.
365,490
def _build_error_report( self, message, report_location=None, http_context=None, user=None ): payload = { "serviceContext": {"service": self.service}, "message": "{0}".format(message), } if self.version: payload["serviceContext"]["version...
Builds the Error Reporting object to report. This builds the object according to https://cloud.google.com/error-reporting/docs/formatting-error-messages :type message: str :param message: The stack trace that was reported or logged by the service. :type rep...
365,491
def permute(sequence, permutation): if len(sequence) != len(permutation): raise ValueError((sequence, permutation)) if not check_permutation(permutation): raise BadPermutationError(str(permutation)) if type(sequence) in (list, tuple, str): constructor = type(sequence) else:...
Apply a permutation sigma({j}) to an arbitrary sequence. :param sequence: Any finite length sequence ``[l_1,l_2,...l_n]``. If it is a list, tuple or str, the return type will be the same. :param permutation: permutation image tuple :type permutation: tuple :return: The permuted sequence ``[l_sigma(1), ...
365,492
def infer_modifications(stmts): linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): for af_stmt in _get_statements_by_type(stmts, ActiveForm): if not af_stmt.agent.entity_matches(act_stmt.obj): continue ...
Return inferred Modification from RegulateActivity + ActiveForm. This function looks for combinations of Activation/Inhibition Statements and ActiveForm Statements that imply a Modification Statement. For example, if we know that A activates B, and phosphorylated B is active, then we ca...
365,493
def put(self, thing_id=, property_name=None): thing = self.get_thing(thing_id) if thing is None: self.set_status(404) return try: args = json.loads(self.request.body.decode()) except ValueError: self.set_status(400) re...
Handle a PUT request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path
365,494
def date(self, year: Number, month: Number, day: Number) -> Date: return Date(year, month, day)
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order.
365,495
def resize(self, image, size): (width, height, force) = size if image.size[0] > width or image.size[1] > height: if force: return ImageOps.fit(self.image, (width, height), Image.ANTIALIAS) else: thumb = self.image.copy() t...
Resizes the image :param image: The image object :param size: size is PIL tuple (width, heigth, force) ex: (200,100,True)
365,496
def get_summary(self): if not self.is_valid(): return None else: return { "source": self.source, "assembly": self.assembly, "build": self.build, "build_detected": self.build_detected, "snp_co...
Get summary of ``SNPs``. Returns ------- dict summary info, else None if ``SNPs`` is not valid
365,497
def basic_reject(self, delivery_tag, requeue): args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(requeue) self._send_method((60, 90), args)
Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the ...
365,498
def OverwriteAndClose(self, compressed_data, size): self.Set(self.Schema.CONTENT(compressed_data)) self.Set(self.Schema.SIZE(size)) super(AFF4MemoryStreamBase, self).Close()
Directly overwrite the current contents. Replaces the data currently in the stream with compressed_data, and closes the object. Makes it possible to avoid recompressing the data. Args: compressed_data: The data to write, must be zlib compressed. size: The uncompressed size of the data.
365,499
def iterative_overlap_assembly( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): if len(variant_sequences) <= 1: return variant_sequences n_before_collapse = len(variant_sequences) variant_sequences = collapse_substrin...
Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequence which contains them. Returns a list of variant sequences, sorted by decreasing read support.