Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
2,900
def add_user(name, profile=): client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, ) ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False ...
Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle
2,901
def actionAngleTorus_xvFreqs_c(pot,jr,jphi,jz, angler,anglephi,anglez, tol=0.003): from galpy.orbit.integrateFullOrbit import _parse_pot npot, pot_type, pot_args= _parse_pot(pot,potfortorus=True) R= numpy.empty(len(angler)) vR...
NAME: actionAngleTorus_xvFreqs_c PURPOSE: compute configuration (x,v) and frequencies of a set of angles on a single torus INPUT: pot - Potential object or list thereof jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) ang...
2,902
def to_dict(cls, obj): t prefixed with __, isnt callable. ' return { k: getattr(obj, k) for k in dir(obj) if cls.serialisable(k, obj) }
Serialises the object, by default serialises anything that isn't prefixed with __, isn't in the blacklist, and isn't callable.
2,903
def create_folder_structure(self): self.info_file, directories = create_folder_structure(self.project, self.name) self.project_dir, self.batch_dir, self.raw_dir = directories logger.debug("create folders:" + str(directories))
Creates a folder structure based on the project and batch name. Project - Batch-name - Raw-data-dir The info_df JSON-file will be stored in the Project folder. The summary-files will be saved in the Batch-name folder. The raw data (including exported cycles and ica-data) will be saved ...
2,904
def timed_operation(msg, log_start=False): assert len(msg) if log_start: logger.info(.format(msg)) start = timer() yield msg = msg[0].upper() + msg[1:] logger.info(.format( msg, timer() - start))
Surround a context with a timer. Args: msg(str): the log to print. log_start(bool): whether to print also at the beginning. Example: .. code-block:: python with timed_operation('Good Stuff'): time.sleep(1) Will print: .. code-block:: pytho...
2,905
def mcast_ip_mask(ip_addr_and_mask, return_tuple=True): regex_mcast_ip_and_mask = __re.compile("^(((2[2-3][4-9])|(23[0-3]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))/((3[0-2])|([1-2][0-9])...
Function to check if a address is multicast and that the CIDR mask is good Args: ip_addr_and_mask: Multicast IP address and mask in the following format 239.1.1.1/24 return_tuple: Set to True it returns a IP and mask in a tuple, set to False returns True or False Returns: see return_tuple for r...
2,906
def join_room(self, room_id_or_alias): if not room_id_or_alias: raise MatrixError("No alias or room ID to join.") path = "/join/%s" % quote(room_id_or_alias) return self._send("POST", path)
Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join.
2,907
def split_header_words(header_values): r assert not isinstance(header_values, str) result = [] for text in header_values: orig_text = text pairs = [] while text: m = HEADER_TOKEN_RE.search(text) if m: text = unmatched(m) nam...
r"""Parse header values into a list of lists containing key,value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the header_values passed as argument contains multiple val...
2,908
def MRA(biomf, sampleIDs=None, transform=None): ra = relative_abundance(biomf, sampleIDs) if transform is not None: ra = {sample: {otuID: transform(abd) for otuID, abd in ra[sample].items()} for sample in ra.keys()} otuIDs = biomf.ids(axis="observation") return mean_otu_pct_ab...
Calculate the mean relative abundance percentage. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :param transform: Mathematical function which is used to transform smax to another ...
2,909
def run_shell_command(commands, **kwargs): p = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) output, error = p.communicate() return p.returncode, output, error
Run a shell command.
2,910
def xml_filter(self, content): r content = utils.strip_whitespace(content, True) if self.__options[] else content.strip() if not self.__options[]: encoding = self.guess_xml_encoding(content) or self.__encoding self.set_options(encoding=encoding) if self.__option...
r"""Filter and preprocess xml content :param content: xml content :rtype: str
2,911
def load_simple_endpoint(category, name): for ep in pkg_resources.iter_entry_points(category): if ep.name == name: return ep.load() raise KeyError(name)
fetches the entry point for a plugin and calls it with the given aux_info
2,912
def removeTab(self, index): view = self.widget(index) if isinstance(view, XView): try: view.windowTitleChanged.disconnect(self.refreshTitles) view.sizeConstraintChanged.disconnect(self.adjustSizeConstraint) except: pass ...
Removes the view at the inputed index and disconnects it from the \ panel. :param index | <int>
2,913
def readACTIONRECORD(self): action = None actionCode = self.readUI8() if actionCode != 0: actionLength = self.readUI16() if actionCode >= 0x80 else 0 action = SWFActionFactory.create(actionCode, actionLength) action.parse(self) re...
Read a SWFActionRecord
2,914
def cutR_seq(seq, cutR, max_palindrome): complement_dict = {: , : , : , : } if cutR < max_palindrome: seq = seq + .join([complement_dict[nt] for nt in seq[cutR - max_palindrome:]][::-1]) else: seq = seq[:len(seq) - cutR + max_palindrome] return seq
Cut genomic sequence from the right. Parameters ---------- seq : str Nucleotide sequence to be cut from the right cutR : int cutR - max_palindrome = how many nucleotides to cut from the right. Negative cutR implies complementary palindromic insertions. max_palindrome : int ...
2,915
def to_tgt(self): enc_part = EncryptedData({: 1, : b}) tgt_rep = {} tgt_rep[] = krb5_pvno tgt_rep[] = MESSAGE_TYPE.KRB_AS_REP.value tgt_rep[] = self.server.realm.to_string() tgt_rep[] = self.client.to_asn1()[0] tgt_rep[] = Ticket.load(self.ticket.to_asn1()).native tgt_rep[] = enc_part.native t ...
Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format
2,916
def from_string(cls, link): ma = cls._pattern.search(link) if ma is None: raise ValueError(link) id = ma.group() return cls(id)
Return a new SheetUrl instance from parsed URL string. >>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam') <SheetUrl id='spam' gid=0>
2,917
def run_with(self, inputs, options): self._inputs = inputs self._options = options
Store the run parameters (inputs and options)
2,918
def from_json(cls, data): required_keys = (, , , , , , ) for key in required_keys: assert key in data, .format(key) return cls(data[], data[], Location.from_json(data[]), DryBulbCondition.from_json(data[]), Humi...
Create a Design Day from a dictionary. Args: data = { "name": string, "day_type": string, "location": ladybug Location schema, "dry_bulb_condition": ladybug DryBulbCondition schema, "humidity_condition": ladybug HumidityCondition schema, ...
2,919
def do_b0(self, line): self.application.apply_update(opendnp3.Binary(False), index=6)
Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0
2,920
def get_base(vpc, **conn): base_result = describe_vpcs(VpcIds=[vpc["id"]], **conn)[0] vpc_name = None for t in base_result.get("Tags", []): if t["Key"] == "Name": vpc_name = t["Value"] dhcp_opts = None if base_result.get("DhcpOptionsId"): dh...
The base will return: - ARN - Region - Name - Id - Tags - IsDefault - InstanceTenancy - CidrBlock - CidrBlockAssociationSet - Ipv6CidrBlockAssociationSet - DhcpOptionsId - Attributes - _version :param bucket_name: :param conn: :return:
2,921
def attributes(self): if self._attributes is None: self._filters, self._attributes = self._fetch_configuration() return self._attributes
List of attributes available for the dataset (cached).
2,922
def _fw_rule_create(self, drvr_name, data, cache): tenant_id = data.get().get() fw_rule = data.get() rule = self._fw_rule_decode_store(data) fw_pol_id = fw_rule.get() rule_id = fw_rule.get() if tenant_id not in self.fwid_attr: self.fwid_attr[tenant_id...
Firewall Rule create routine. This function updates its local cache with rule parameters. It checks if local cache has information about the Policy associated with the rule. If not, it means a restart has happened. It retrieves the policy associated with the FW by calling Openst...
2,923
def execute_function(function_request): dispatch_table = getattr(settings, , None) if dispatch_table is None: raise BeanstalkDispatchError() for key in (FUNCTION, ARGS, KWARGS): if key not in function_request.keys(): raise BeanstalkDispatchError( .format(key...
Given a request created by `beanstalk_dispatch.common.create_request_body`, executes the request. This function is to be run on a beanstalk worker.
2,924
def _create_alignment_button(self): iconnames = ["AlignTop", "AlignCenter", "AlignBottom"] bmplist = [icons[iconname] for iconname in iconnames] self.alignment_tb = _widgets.BitmapToggleButton(self, bmplist) self.alignment_tb.SetToolTipString(_(u"Alignment")) self.Bind...
Creates vertical alignment button
2,925
def heartbeat(self): try: with create_session() as session: job = session.query(BaseJob).filter_by(id=self.id).one() make_transient(job) session.commit() if job.state == State.SHUTDOWN: self.kill() is_...
Heartbeats update the job's entry in the database with a timestamp for the latest_heartbeat and allows for the job to be killed externally. This allows at the system level to monitor what is actually active. For instance, an old heartbeat for SchedulerJob would mean something is...
2,926
def write(self, data): proxy.state(self).digest.update(data) return proxy.original(self).write(data)
Intercepted method for writing data. :param data: Data to write :returns: Whatever the original method returns :raises: Whatever the original method raises This method updates the internal digest object with with the new data and then proceed...
2,927
def read(self): writes = [c for c in connections if c.pending()] try: readable, writable, exceptable = select.select( connections, writes, connections, self._timeout) except exceptions.ConnectionClosedException: logger.exception(...
Read from any of the connections that need it
2,928
def remove_tag(self, tag): tags = self.get_tags() tags.remove(tag) post_data = TAGS_TEMPLATE.format(connectware_id=self.get_connectware_id(), tags=escape(",".join(tags))) self._conn.put(, post_data) self._device_json =...
Remove tag from existing device tags :param tag: the tag to be removed from the list :raises ValueError: If tag does not exist in list
2,929
def write_info(dirs, parallel, config): if parallel["type"] in ["ipython"] and not parallel.get("run_local"): out_file = _get_cache_file(dirs, parallel) if not utils.file_exists(out_file): sys_config = copy.deepcopy(config) minfos = _get_machine_info(parallel, sys_config...
Write cluster or local filesystem resources, spinning up cluster if not present.
2,930
def set_up(self): self.path.profile = self.path.gen.joinpath("profile") if not self.path.profile.exists(): self.path.profile.mkdir() self.python = hitchpylibrarytoolkit.project_build( "strictyaml", self.path, self.given["python version"]...
Set up your applications and the test environment.
2,931
def check_aggregations_privacy(self, aggregations_params): fields = self.get_aggregations_fields(aggregations_params) fields_dict = dictset.fromkeys(fields) fields_dict[] = self.view.Model.__name__ try: validate_data_privacy(self.view.request, fields_dict) e...
Check per-field privacy rules in aggregations. Privacy is checked by making sure user has access to the fields used in aggregations.
2,932
def Maybe(validator): @wraps(Maybe) def built(value): if value != None: return validator(value) return built
Wraps the given validator callable, only using it for the given value if it is not ``None``.
2,933
def pif_list(call=None): if call != : raise SaltCloudSystemExit( ) ret = {} session = _get_session() pifs = session.xenapi.PIF.get_all() for pif in pifs: record = session.xenapi.PIF.get_record(pif) ret[record[]] = record return ret
Get a list of Resource Pools .. code-block:: bash salt-cloud -f pool_list myxen
2,934
def all(self, *, collection, attribute, word, func=None, operation=None): return self.iterable(, collection=collection, attribute=attribute, word=word, func=func, operation=operation)
Performs a filter with the OData 'all' keyword on the collection For example: q.any(collection='email_addresses', attribute='address', operation='eq', word='george@best.com') will transform to a filter such as: emailAddresses/all(a:a/address eq 'george@best.com') :par...
2,935
def get_new_connection(self, connection_params): name = connection_params.pop() es = connection_params.pop() connection_params[] = OrderedDict if self.client_connection is not None: self.client_connection.close() self.cl...
Receives a dictionary connection_params to setup a connection to the database. Dictionary correct setup is made through the get_connection_params method. TODO: This needs to be made more generic to accept other MongoClient parameters.
2,936
def is_tp(self, atol=None, rtol=None): choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(choi, atol, rtol)
Test if a channel is completely-positive (CP)
2,937
def density(self, *args): M = self.mass(*args) * MSUN V = 4./3 * np.pi * (self.radius(*args) * RSUN)**3 return M/V
Mean density in g/cc
2,938
def load_manual_sequence_file(self, ident, seq_file, copy_file=False, outdir=None, set_as_representative=False): if copy_file: if not outdir: outdir = self.sequence_dir if not outdir: raise ValueError() shutil.copy(seq_file, ou...
Load a manual sequence, given as a FASTA file and optionally set it as the representative sequence. Also store it in the sequences attribute. Args: ident (str): Sequence ID seq_file (str): Path to sequence FASTA file copy_file (bool): If the FASTA file should be copi...
2,939
def kong_61_2007(): r dlf = DigitalFilter(, ) dlf.base = np.array([ 2.3517745856009100e-02, 2.6649097336355482e-02, 3.0197383422318501e-02, 3.4218118311666032e-02, 3.8774207831722009e-02, 4.3936933623407420e-02, 4.9787068367863938e-02, 5.6416139503777350e-02...
r"""Kong 61 pt Hankel filter, as published in [Kong07]_. Taken from file ``FilterModules.f90`` provided with 1DCSEM_. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_.
2,940
def feed_ssldata(self, data): if self._state == self.S_UNWRAPPED: return ([], [data] if data else []) ssldata = []; appdata = [] self._need_ssldata = False if data: self._incoming.write(data) try: if self._state == self.S_...
Feed SSL record level data into the pipe. The data must be a bytes instance. It is OK to send an empty bytes instance. This can be used to get ssldata for a handshake initiated by this endpoint. Return a (ssldata, appdata) tuple. The ssldata element is a list of buffers contain...
2,941
def build_from_generator(cls, generator, target_size, max_subtoken_length=None, reserved_tokens=None): token_counts = collections.defaultdict(int) for item in generator: for tok in tokenizer.en...
Builds a SubwordTextEncoder from the generated text. Args: generator: yields text. target_size: int, approximate vocabulary size to create. max_subtoken_length: Maximum length of a subtoken. If this is not set, then the runtime and memory use of creating the vocab is quadratic in ...
2,942
async def _get_difference(self, channel_id, pts_date): self.client._log[__name__].debug() if channel_id: try: where = await self.client.get_input_entity(channel_id) except ValueError: return result = await se...
Get the difference for this `channel_id` if any, then load entities. Calls :tl:`updates.getDifference`, which fills the entities cache (always done by `__call__`) and lets us know about the full entities.
2,943
def benchmark(self, func, gpu_args, instance, times, verbose): logging.debug( + instance.name) logging.debug(, *instance.threads) logging.debug(, *instance.grid) time = None try: time = self.dev.benchmark(func, gpu_args, instance.threads, instance.grid, time...
benchmark the kernel instance
2,944
def rollback(self, dt): if not self.onOffset(dt): businesshours = self._get_business_hours_by_sec if self.n >= 0: dt = self._prev_opening_time( dt) + timedelta(seconds=businesshours) else: dt = self._next_opening_ti...
Roll provided date backward to next offset only if not on offset.
2,945
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key): algorithm = RsaAlgorithmIdentifier() algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID pkcs8_key = PKCS8PrivateKey() pkcs8_key["version"] = 0 pkcs8_key["privateKeyAlgorithm"] = algorithm pkcs8_key["privateKey"] = pkcs1_key return encod...
Convert a PKCS1-encoded RSA private key to PKCS8.
2,946
def _load_data_alignment(self, chain1, chain2): parser = PDB.PDBParser(QUIET=True) ppb = PDB.PPBuilder() structure1 = parser.get_structure(chain1, self.pdb1) structure2 = parser.get_structure(chain2, self.pdb2) seq1 = str(ppb.build_peptides(structure1)[0].get_sequence(...
Extract the sequences from the PDB file, perform the alignment, and load the coordinates of the CA of the common residues.
2,947
def export_coreml(self, filename): import coremltools from coremltools.proto.FeatureTypes_pb2 import ArrayFeatureType from .._mxnet import _mxnet_utils prob_name = self.target + def get_custom_model_spec(): from coremltools.models.neural_network import Neu...
Save the model in Core ML format. See Also -------- save Examples -------- >>> model.export_coreml('./myModel.mlmodel')
2,948
def splitSymbol(self, index): row = [0,0,1,1,2,2,1,3,2,3,3][index>>6] col = [0,1,0,1,0,1,2,0,2,1,2][index>>6] insertLengthCode = row<<3 | index>>3&7 if row: insertLengthCode -= 8 copyLengthCode = col<<3 | index&7 return ( Symbol(self...
Give relevant values for computations: (insertSymbol, copySymbol, dist0flag)
2,949
def affiliation_history(self): affs = self._json.get(, {}).get() try: return [d[] for d in affs] except TypeError: return None
Unordered list of IDs of all affiliations the author was affiliated with acccording to Scopus.
2,950
def import_crud(app): try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module(, app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
Import crud module and register all model cruds which it contains
2,951
def to_url(self): base_url = urlparse(self.url) if PY3: query = parse_qs(base_url.query) for k, v in self.items(): query.setdefault(k, []).append(to_utf8_optional_iterator(v)) scheme = base_url.scheme netloc = base_url.netloc ...
Serialize as a URL for a GET request.
2,952
def get_activities_for_project(self, module=None, **kwargs): _module_id = kwargs.get(, module) _activities_url = ACTIVITIES_URL.format(module_id=_module_id) return self._request_api(url=_activities_url).json()
Get the related activities of a project. :param str module: Stages of a given module :return: JSON
2,953
def _options_request(self, url, **kwargs): request_kwargs = { : , : url } for key, value in kwargs.items(): request_kwargs[key] = value return self._request(**request_kwargs)
a method to catch and report http options request connectivity errors
2,954
def pathconf(path, os_name=os.name, isdir_fnc=os.path.isdir, pathconf_fnc=getattr(os, , None), pathconf_names=getattr(os, , ())): if pathconf_fnc and pathconf_names: return {key: pathconf_fnc(path, key) for key in pathconf_names} if os_name == : ...
Get all pathconf variables for given path. :param path: absolute fs path :type path: str :returns: dictionary containing pathconf keys and their values (both str) :rtype: dict
2,955
def add_instruction(self, specification): instruction = self.as_instruction(specification) self._type_to_instruction[instruction.type] = instruction
Add an instruction specification :param specification: a specification with a key :data:`knittingpattern.Instruction.TYPE` .. seealso:: :meth:`as_instruction`
2,956
def _gen_success_message(publish_output): application_id = publish_output.get() details = json.dumps(publish_output.get(), indent=2) if CREATE_APPLICATION in publish_output.get(): return "Created new application with the following metadata:\n{}".format(details) return .format(application_...
Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed success message
2,957
def dfbool2intervals(df,colbool): df.index=range(len(df)) intervals=bools2intervals(df[colbool]) for intervali,interval in enumerate(intervals): df.loc[interval[0]:interval[1],f]=intervali df.loc[interval[0]:interval[1],f]=interval[0] df.loc[interval[0]:interval[1],f]=interval[1...
ds contains bool values
2,958
def get_instance(self, payload): return AuthTypeCallsInstance( self._version, payload, account_sid=self._solution[], domain_sid=self._solution[], )
Build an instance of AuthTypeCallsInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInsta...
2,959
def evaluate(self, global_state: GlobalState, post=False) -> List[GlobalState]: log.debug("Evaluating {}".format(self.op_code)) op = self.op_code.lower() if self.op_code.startswith("PUSH"): op = "push" elif self.op_code.startswith("DUP"): op = "d...
Performs the mutation for this instruction. :param global_state: :param post: :return:
2,960
def safe_version(version): try: return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(, ) return re.sub(, , version)
Convert an arbitrary string to a standard version string
2,961
def dump_to_stream(self, cnf, stream, **opts): tree = container_to_etree(cnf, **opts) etree_write(tree, stream)
:param cnf: Configuration data to dump :param stream: Config file or file like object write to :param opts: optional keyword parameters
2,962
def save_split_next(self): filenames = [] width = int(math.ceil(math.log(len(self), 10))) + 1 i = 1 blurb = Blurbs() while self: metadata, body = self.pop() metadata[] = str(i).rjust(width, ) if in metadata:...
Save out blurbs created from "blurb split". They don't have dates, so we have to get creative.
2,963
def destroy(self): if self == App._main_app: App._main_app = None self.tk.destroy()
Destroy and close the App. :return: None. :note: Once destroyed an App can no longer be used.
2,964
def get_electron_number(self, charge=0): atomic_number = constants.elements[].to_dict() return sum([atomic_number[atom] for atom in self[]]) - charge
Return the number of electrons. Args: charge (int): Charge of the molecule. Returns: int:
2,965
def measure_impedance(self, sampling_window_ms, n_sampling_windows, delay_between_windows_ms, interleave_samples, rms, state): state_ = uint8_tVector() for i in range(0, len(state)): state_.append(int(state[i])) buffer = n...
Measure voltage across load of each of the following control board feedback circuits: - Reference _(i.e., attenuated high-voltage amplifier output)_. - Load _(i.e., voltage across DMF device)_. The measured voltage _(i.e., ``V2``)_ can be used to compute the impedance of the ...
2,966
def _make_index_list(num_samples, num_params, num_groups=None): if num_groups is None: num_groups = num_params index_list = [] for j in range(num_samples): index_list.append(np.arange(num_groups + 1) + j * (num_groups + 1)) return index_list
Identify indices of input sample associated with each trajectory For each trajectory, identifies the indexes of the input sample which is a function of the number of factors/groups and the number of samples Arguments --------- num_samples : int The number of traject...
2,967
def write_data(self, buf): result = self.devh.controlMsg( usb.ENDPOINT_OUT + usb.TYPE_CLASS + usb.RECIP_INTERFACE, usb.REQ_SET_CONFIGURATION, buf, value=0x200, timeout=50) if result != len(buf): raise IOError() return True
Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool
2,968
def SegmentSum(a, ids, *args): func = lambda idxs: reduce(np.add, a[idxs]) return seg_map(func, a, ids),
Segmented sum op.
2,969
def _readoct(self, length, start): if length % 3: raise InterpretError("Cannot convert to octal unambiguously - " "not multiple of 3 bits.") if not length: return end = oct(self._readuint(length, start))[LEADING...
Read bits and interpret as an octal string.
2,970
def add_prefix(self): p = Prefix() if in request.json: try: if request.json[] is None or len(unicode(request.json[])) == 0: p.vrf = None else: p.vrf = VRF.get(int(request.json[])) except ...
Add prefix according to the specification. The following keys can be used: vrf ID of VRF to place the prefix in prefix the prefix to add if already known family address family (4 or 6) description A short description ...
2,971
def _select_list_view(self, model, **kwargs): from uliweb import request fields = kwargs.pop(, None) meta = kwargs.pop(, ) if in request.GET: if in kwargs: fields = kwargs.pop(, fields) if in kwargs: meta = kwa...
:param model: :param fields_convert_map: it's different from ListView :param kwargs: :return:
2,972
def _validate_row_label(label, column_type_map): if not isinstance(label, str): raise TypeError("The row label column name must be a string.") if not label in column_type_map.keys(): raise ToolkitError("Row label column not found in the dataset.") if not column_type_map[label] in (str...
Validate a row label column. Parameters ---------- label : str Name of the row label column. column_type_map : dict[str, type] Dictionary mapping the name of each column in an SFrame to the type of the values in the column.
2,973
def line(ax, p1, p2, permutation=None, **kwargs): pp1 = project_point(p1, permutation=permutation) pp2 = project_point(p2, permutation=permutation) ax.add_line(Line2D((pp1[0], pp2[0]), (pp1[1], pp2[1]), **kwargs))
Draws a line on `ax` from p1 to p2. Parameters ---------- ax: Matplotlib AxesSubplot, None The subplot to draw on. p1: 2-tuple The (x,y) starting coordinates p2: 2-tuple The (x,y) ending coordinates kwargs: Any kwargs to pass through to Matplotlib.
2,974
def sliced(seq, n): return takewhile(bool, (seq[i: i + n] for i in count(0, n)))
Yield slices of length *n* from the sequence *seq*. >>> list(sliced((1, 2, 3, 4, 5, 6), 3)) [(1, 2, 3), (4, 5, 6)] If the length of the sequence is not divisible by the requested slice length, the last slice will be shorter. >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3)) [(1, 2...
2,975
def set_raw_tag_data(filename, data, act=True, verbose=False): "Replace the ID3 tag in FILENAME with DATA." check_tag_data(data) with open(filename, "rb+") as file: try: (cls, offset, length) = stagger.tags.detect_tag(file) except stagger.NoTagError: (offset, length) ...
Replace the ID3 tag in FILENAME with DATA.
2,976
def _to_dict(self): _dict = {} if hasattr(self, ) and self.from_ is not None: _dict[] = self.from_ if hasattr(self, ) and self.to is not None: _dict[] = self.to if hasattr(self, ) and self.speaker is not None: _dict[] = self.speaker if...
Return a json dictionary representing this model.
2,977
def get_constantvalue(self): buff = self.get_attribute("ConstantValue") if buff is None: return None with unpack(buff) as up: (cval_ref, ) = up.unpack_struct(_H) return cval_ref
the constant pool index for this field, or None if this is not a contant field reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2
2,978
def find_slack_bus(sub_network): gens = sub_network.generators() if len(gens) == 0: logger.warning("No generators in sub-network {}, better hope power is already balanced".format(sub_network.name)) sub_network.slack_generator = None sub_network.slack_bus = sub_network.buses_i()[0]...
Find the slack bus in a connected sub-network.
2,979
def writeClient(self, fd, sdClass=None, **kw): sdClass = sdClass or ServiceDescription assert issubclass(sdClass, ServiceDescription), \ print >>fd, *50 print >>fd, %self.getClientModuleName() print >>fd, print >>fd, %self.__class__ pri...
write out client module to file descriptor. Parameters and Keywords arguments: fd -- file descriptor sdClass -- service description class name imports -- list of imports readerclass -- class name of ParsedSoap reader writerclass -- class name of SoapWr...
2,980
def cli_help(context, command_name, general_parser, command_parsers): if command_name == : command_name = with context.io_manager.with_stdout() as stdout: if not command_name: general_parser.print_help(stdout) elif command_name in command_parsers: command_pa...
Outputs help information. See :py:mod:`swiftly.cli.help` for context usage information. See :py:class:`CLIHelp` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param command_name: The command_name to output help information for, or set to ...
2,981
def manage(cls, entity, unit_of_work): if hasattr(entity, ): if not unit_of_work is entity.__everest__.unit_of_work: raise ValueError( ) else: entity.__everest__ = cls(entity, unit_of_work)
Manages the given entity under the given Unit Of Work. If `entity` is already managed by the given Unit Of Work, nothing is done. :raises ValueError: If the given entity is already under management by a different Unit Of Work.
2,982
def make_value_from_env(self, param, value_type, function): value = os.getenv(param) if value is None: self.notify_user("Environment variable `%s` undefined" % param) return self.value_convert(value, value_type)
get environment variable
2,983
def acquire(self): start_time = time.time() while True: try: self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) break except (OSError,) as e: if e.errno != errno.EEXIST: ...
Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception.
2,984
def snapshot_list(self): NO_SNAPSHOTS_TAKEN = output = self._run_vagrant_command([, ]) if NO_SNAPSHOTS_TAKEN in output: return [] else: return output.splitlines()
This command will list all the snapshots taken.
2,985
def worker_bonus(self, chosen_hit, auto, amount, reason=, assignment_ids=None): if self.config.has_option(, ): reason = self.config.get(, ) while not reason: user_input = raw_input("Type the reason for the bonus. Workers " ...
Bonus worker
2,986
def get_field_cache(self, cache_type=): if cache_type == : try: search_results = urlopen(self.get_url).read().decode() except HTTPError: return [] index_pattern = json.loads(search_results) f...
Return a list of fields' mappings
2,987
def delete_message(self, id, remove): path = {} data = {} params = {} path["id"] = id data["remove"] = remove self.logger.debug("POST /api/v1/conversations/{id}/remove_messages with query params: {params} and for...
Delete a message. Delete messages from this conversation. Note that this only affects this user's view of the conversation. If all messages are deleted, the conversation will be as well (equivalent to DELETE)
2,988
def rlgt(self, time=None, times=1, disallow_sibling_lgts=False): lgt = LGT(self.copy()) for _ in range(times): lgt.rlgt(time, disallow_sibling_lgts) return lgt.tree
Uses class LGT to perform random lateral gene transfer on ultrametric tree
2,989
def populate(self, priority, address, rtr, data): assert isinstance(data, bytes) self.needs_no_rtr(rtr) self.needs_data(data, 6) self.set_attributes(priority, address, rtr) self.cur = (((data[0] << 8)| data[1]) / 32 ) * 0.0625 self.min = (((data[2] << 8) | data[3...
data bytes (high + low) 1 + 2 = current temp 3 + 4 = min temp 5 + 6 = max temp :return: None
2,990
def construct_inlines(self): inline_formsets = [] for inline_class in self.get_inlines(): inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self) inline_formset = inline_instance.construct_formset() inline_formsets.append(inli...
Returns the inline formset instances
2,991
def _pcca_connected_isa(evec, n_clusters): (n, m) = evec.shape if n_clusters > m: raise ValueError("Cannot cluster the (" + str(n) + " x " + str(m) + " eigenvector matrix to " + str(n_clusters) + " clusters.") diffs = np.abs(np.max(evec, axis=0) - np.min(eve...
PCCA+ spectral clustering method using the inner simplex algorithm. Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states. This function assumes that the state space is fully connected, i.e. the transition matrix whose eigenvectors are used is supposed to have only...
2,992
def all_subclasses(cls): subclasses = cls.__subclasses__() descendants = (descendant for subclass in subclasses for descendant in all_subclasses(subclass)) return set(subclasses) | set(descendants)
Recursively returns all the subclasses of the provided class.
2,993
def generate_daily(day_end_hour, use_dst, calib_data, hourly_data, daily_data, process_from): start = daily_data.before(datetime.max) if start is None: start = datetime.min start = calib_data.after(start + SECOND) if process_from: if start: start = min...
Generate daily summaries from calibrated and hourly data.
2,994
def double_ell_distance (mjr0, mnr0, pa0, mjr1, mnr1, pa1, dx, dy): theta = -np.arctan2 (dy, dx) sx0, sy0, cxy0 = ellbiv (mjr0, mnr0, pa0 + theta) sx1, sy1, cxy1 = ellbiv (mjr1, mnr1, pa1 + theta) sx, sy, cxy = bivconvolve (sx0, sy0, cxy0, sx1, sy1, cxy1) d = np.sqrt (dx*...
Given two ellipses separated by *dx* and *dy*, compute their separation in terms of σ. Based on Pineau et al (2011A&A...527A.126P). The "0" ellipse is taken to be centered at (0, 0), while the "1" ellipse is centered at (dx, dy).
2,995
def escape(s, quote=True): assert not isinstance(s, bytes), if quote: return s.translate(_escape_map_full) return s.translate(_escape_map)
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated.
2,996
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): try: tarobj = tarfile.open(filename) except tarfile.TarError: raise UnrecognizedFormat( "%s is not a compressed or uncompressed tar file" % (filename,) ) try: tarobj.chown = lambda *...
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument.
2,997
def add_new_data_port(self): try: new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states(, int, [self.model]) if new_data_port_ids: self.select_entry(new_data_port_ids[self.model.state]) except ValueError: pass
Add a new port with default values and select it
2,998
def predict(self, pairs): check_is_fitted(self, [, ]) return 2 * (- self.decision_function(pairs) <= self.threshold_) - 1
Predicts the learned metric between input pairs. (For now it just calls decision function). Returns the learned metric value between samples in every pair. It should ideally be low for similar samples and high for dissimilar samples. Parameters ---------- pairs : array-like, shape=(n_pairs, 2,...
2,999
def render_latex(latex: str) -> PIL.Image: tmpfilename = with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename) with open(tmppath + , ) as latex_file: latex_file.write(latex) subprocess.run(["pdflatex", ...
Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX document as a string. Returns: A PIL Image Raises: O...