Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
337,400
def median(series): if np.issubdtype(series.dtype, np.number): return series.median() else: return np.nan
Returns the median value of a series. Args: series (pandas.Series): column to summarize.
337,401
def place_quote(self, package_keyname, location, item_keynames, complex_type=None, preset_keyname=None, extras=None, quantity=1, quote_name=None, send_email=False): order = self.generate_order(package_keyname, location, item_keynames, complex_type=complex_type, ...
Place a quote with the given package and prices. This function takes in parameters needed for an order and places the quote. :param str package_keyname: The keyname for the package being ordered :param str location: The datacenter location string for ordering (Ex: DALLAS13) :param list...
337,402
def to_cloudformation(self, **kwargs): function = kwargs.get() if not function: raise TypeError("Missing required keyword argument: function") if not in kwargs or kwargs[] is None: raise TypeError("Missing required keyword argument: bucket") if not i...
Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers. :param dict kwargs: S3 bucket resource :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands :rtype: list
337,403
def from_iterable(cls, target_types, address_mapper, adaptor_iter): inst = cls(target_types, address_mapper) all_valid_addresses = set() for target_adaptor in adaptor_iter: inst._inject_target(target_adaptor) all_valid_addresses.add(target_adaptor.address) inst._validate(all_valid_addre...
Create a new DependentGraph from an iterable of TargetAdaptor subclasses.
337,404
def rotate_point(xorigin, yorigin, x, y, angle): rotx = (x - xorigin) * np.cos(angle) - (y - yorigin) * np.sin(angle) roty = (x - yorigin) * np.sin(angle) + (y - yorigin) * np.cos(angle) return rotx, roty
Rotate the given point by angle
337,405
def process_vm_json( self, json_dict, **kwargs ): s JSON, given as a dict; Returns a list: lines of analyses in the VISL CG3 input format; ' mrf_lines = convert_vm_json_to_mrf( json_dict ) return self.process_mrf_lines( mrf_lines, **kwargs )
Executes the preprocessing pipeline on vabamorf's JSON, given as a dict; Returns a list: lines of analyses in the VISL CG3 input format;
337,406
async def send( self, message: Union[Data, Iterable[Data], AsyncIterable[Data]] ) -> None: await self.ensure_open() if isinstance(message, (str, bytes, bytearray, memoryview)): opcode, data = prepare_data(message) await self.write_frame(Tr...
This coroutine sends a message. It sends a string (:class:`str`) as a text frame and a bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a binary frame. It also accepts an iterable or an asynchronous iterator of strings or bytes-like objects. Eac...
337,407
def openStream(self, source): if hasattr(source, ): stream = source else: stream = StringIO(source) return stream
Produces a file object from source. source can be either a file object, local filename or a string.
337,408
def get_msg_info(yaml_info, topics, parse_header=True): topic_info = yaml_info[] msgs = {} classes = {} for topic in topics: base_key = get_key_name(topic) msg_paths = [] msg_types = {} for info in topic_info: if info[] == topic: msg_clas...
Get info from all of the messages about what they contain and will be added to the dataframe
337,409
def is_unicode(string): str_type = str(type(string)) if str_type.find() > 0 or str_type.find() > 0: return True return False
Validates that the object itself is some kinda string
337,410
def get_time_ranges(ranges): now = int(time.time()) time_slots = dict() for key, value in ranges.items(): time_slots[key] = (now - value[0], now - value[1], value[2]) return (now, time_slots)
:param ranges: :return:
337,411
def romanise(number): if number is None: return roman_list = [, , , , , , , , , , , , ] try: roman = roman_list[int(number)] except ValueError: return None return roman
Return the roman numeral for a number. Note that this only works for number in interval range [0, 12] since at the moment we only use it on realtime earthquake to conver MMI value. :param number: The number that will be romanised :type number: float :return Roman numeral equivalent of the value ...
337,412
def encode(self, word, max_length=4, zero_pad=True): def _start_repl(word, src, tar, post=None): if post: for i in post: if word.startswith(src + i): return tar + word[len(src) :] elif word.startswith(src)...
Return the Phonix code for a word. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4) zero_pad : bool Pad the end of the return value with 0s to achieve a max_length ...
337,413
def has_pixels(self): return any( ci.id >= 0 and cd.data and len(cd.data) > 0 for ci, cd in zip(self._record.channel_info, self._channels) )
Returns True if the layer has associated pixels. When this is True, `topil` method returns :py:class:`PIL.Image`. :return: `bool`
337,414
def is_subdirectory(path_a, path_b): path_a = os.path.realpath(path_a) path_b = os.path.realpath(path_b) relative = os.path.relpath(path_a, path_b) return (not relative.startswith(os.pardir + os.sep))
Returns True if `path_a` is a subdirectory of `path_b`.
337,415
def pread(self, position, length): r _complain_ifclosed(self.closed) if position > self.size: raise IOError("position cannot be past EOF") if length < 0: length = self.size - position data = self.f.raw.pread(position, length) if self.__encoding: ...
r""" Read ``length`` bytes of data from the file, starting from ``position``\ . :type position: int :param position: position from which to read :type length: int :param length: the number of bytes to read :rtype: string :return: the chunk of data read fr...
337,416
def bool_2_indices(a): if any(a): lims = [] lims.append(np.where(a[:-1] != a[1:])[0]) if a[0]: lims.append([0]) if a[-1]: lims.append([len(a) - 1]) lims = np.concatenate(lims) lims.sort() return np.reshape(lims, (lims.size // 2, ...
Convert boolean array into a 2D array of (start, stop) pairs.
337,417
def project_add_tags(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /project-xxxx/addTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2FaddTags
337,418
def createMenu(self, parent): menu = QtGui.QMenu(parent) menu.setTitle() act = menu.addAction() act.setIcon(QtGui.QIcon(projexui.resources.find())) act.triggered.connect(self.toggleLocked) menu.addSeparator() act = menu.addAction() act.s...
Creates a new menu for the inputed parent item. :param parent | <QMenu>
337,419
def render_authenticateLinks(self, ctx, data): if self.username is not None: return return ctx.tag[signups]
For unauthenticated users, add login and signup links to the given tag. For authenticated users, remove the given tag from the output. When necessary, the I{signup-link} pattern will be loaded from the tag. Each copy of it will have I{prompt} and I{url} slots filled. The list of copies...
337,420
def get_objective(self): if not bool(self._my_map[]): raise errors.IllegalState() mgr = self._get_provider_manager() if not mgr.supports_objective_lookup(): raise errors.OperationFailed() lookup_session = mgr.get_objective_lookup_session(proxy=ge...
Gets the related objective. return: (osid.learning.Objective) - the related objective raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
337,421
def _parse_special_fields(self, data): self.created = parse_date(data.pop()) if data.get(): self.settled = parse_date(data.pop()) if (data.get() and not isinstance(data[], six.text_type)): self.merchant = MonzoMerchant(data=data.pop()...
Helper method that parses special fields to Python objects :param data: response from Monzo API request :type data: dict
337,422
def validate_sbml_model(filename, check_model=True, internal_consistency=True, check_units_consistency=False, check_modeling_practice=False, **kwargs): keys = ( "SBML_FATAL", "SBML_ERR...
Validate SBML model and returns the model along with a list of errors. Parameters ---------- filename : str The filename (or SBML string) of the SBML model to be validated. internal_consistency: boolean {True, False} Check internal consistency. check_units_consistency: boolean {True...
337,423
def remove(unique_id): for p in PolygonFilter.instances: if p.unique_id == unique_id: PolygonFilter.instances.remove(p)
Remove a polygon filter from `PolygonFilter.instances`
337,424
def open(self, baudrate=None, no_reader_thread=False): try: self._read_thread = Device.ReadThread(self) self._device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self._use_ssl: self._init_ssl() self._device.connect((self._hos...
Opens the device. :param baudrate: baudrate to use :type baudrate: int :param no_reader_thread: whether or not to automatically open the reader thread. :type no_reader_thread: bool :raises: :py:class:`~alarmdecoder.util.NoDeviceError`, :py:class...
337,425
def triads_inv(reference_labels, estimated_labels): validate(reference_labels, estimated_labels) ref_roots, ref_semitones, ref_bass = encode_many(reference_labels, False) est_roots, est_semitones, est_bass = encode_many(estimated_labels, False) eq_roots = ref_roots == est_roots eq_basses = ref...
Score chords along triad (root, quality to #5, & bass) relationships. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_eval.io.load_labeled_intervals('est.lab') >>> est_intervals, est_labels = m...
337,426
def _get_format(self, token): if token in self._formats: return self._formats[token] if self._style is None: result = self._get_format_from_document(token, self._document) else: result = self._get_format_from_style(token, self._style) self._...
Returns a QTextCharFormat for token or None.
337,427
def get_access_token(self): if self.token_info and not self.is_token_expired(self.token_info): return self.token_info[] token_info = self._request_access_token() token_info = self._add_custom_values_to_token_info(token_info) self.token_info = token_info retu...
If a valid access token is in memory, returns it Else feches a new token and returns it
337,428
def __process_line(line, strip_eol, strip): if strip: line = line.strip() elif strip_eol and line.endswith(): line = line[:-1] return line
process a single line value.
337,429
def hms(self, warn=True): if warn and self.preference != : raise WrongUnitError() sign, units, minutes, seconds = _sexagesimalize_to_float(self._hours) return sign * units, sign * minutes, sign * seconds
Convert to a tuple (hours, minutes, seconds). All three quantities will have the same sign as the angle itself.
337,430
def query_entry(): allowed_str_args = [, , , , , , , , , , , , , , , , , , , , , , , , ] allowed_int_args = [, , , , ] args = get_args( request_args=request.args, allowed_int_args=allowed_...
Returns list of HGNC entries by query paramaters --- tags: - Query functions parameters: - name: name in: query type: string required: false description: 'HGNC approved name for the gene' default: 'lysine demethylase 1A' - name: symbol i...
337,431
def punct(self, text): cls = self.PUNCTUATION[text] self.push_token(cls(text, self.lineno, self.offset))
Push punctuation onto the token queue.
337,432
def get_credentials_arn(self): role = self.iam.Role(self.role_name) self.credentials_arn = role.arn return role, self.credentials_arn
Given our role name, get and set the credentials_arn.
337,433
def image_transform(X, function, reshape_before=False, reshape_after=False, width=None, height=None, **kwargs): if not callable(function): function = import_object(function) elif not callable(function): raise ValueError("function must be a str or a callable") flat...
Apply a function image by image. Args: reshape_before: whether 1d array needs to be reshaped to a 2d image reshape_after: whether the returned values need to be reshaped back to a 1d array width: image width used to rebuild the 2d images. Required if the image is not square. height:...
337,434
def inv_shift_rows(state): state = state.reshape(4, 4, 8) return fcat( state[0][0], state[3][1], state[2][2], state[1][3], state[1][0], state[0][1], state[3][2], state[2][3], state[2][0], state[1][1], state[0][2], state[3][3], state[3][0], state[2][1], state[1][2], state[0][...
Transformation in the Inverse Cipher that is the inverse of ShiftRows().
337,435
def account_unpin(self, id): id = self.__unpack_id(id) url = .format(str(id)) return self.__api_request(, url)
Unpin / un-endorse a user. Returns a `relationship dict`_ containing the updated relationship to the user.
337,436
def cudnnActivationBackward(handle, mode, alpha, srcDesc, srcData, srcDiffDesc, srcDiffData, destDesc, destData, beta, destDiffDesc, destDiffData): dataType = cudnnGetTensor4dDescriptor(destDesc)[0] if dataType == cudnnDataType[]: alphaRef = ctypes.byref(ctypes.c_double...
Gradient of activation function. This routine computes the gradient of a neuron activation function. In-place operation is allowed for this routine; i.e., srcData and destData pointers may be equal and srcDiffData and destDiffData pointers may be equal. However, this requires the corresponding tensor ...
337,437
def list_targets_by_instance(self, instance_id, target_list=None): if target_list is not None: return [target for target in target_list if target[] == instance_id] else: ports = self._target_ports_by_instance(ins...
Returns a list of FloatingIpTarget objects of FIP association. :param instance_id: ID of target VM instance :param target_list: (optional) a list returned by list_targets(). If specified, looking up is done against the specified list to save extra API calls to a back-end. Otherw...
337,438
def from_config(cls, gitlab_id=None, config_files=None): config = gitlab.config.GitlabConfigParser(gitlab_id=gitlab_id, config_files=config_files) return cls(config.url, private_token=config.private_token, oauth_token=config.o...
Create a Gitlab connection from configuration files. Args: gitlab_id (str): ID of the configuration section. config_files list[str]: List of paths to configuration files. Returns: (gitlab.Gitlab): A Gitlab connection. Raises: gitlab.config.Gitla...
337,439
def create(self, width=0, depth=0, path=None, flags=0, seed=0): return self.create_method(self, width, depth, path, flags, seed)
Create new sketch Params: <int> width <str> path <int> flags <int> seed
337,440
def do_plugin(self, arg): pos = arg.find() if pos < 0: name = arg arg = else: name = arg[:pos] arg = arg[pos:].strip() if not name: raise CmdError("missing plugin name") for c in name: if c not in...
[~prefix] .<name> [arguments] - run a plugin command [~prefix] plugin <name> [arguments] - run a plugin command
337,441
def archaius(self): bucket = self.format[].format(**self.data) path = self.format[].format(**self.data) archaius_name = self.format[].format(**self.data) archaius = {: archaius_name, : bucket, : path} return archaius
Generate archaius bucket path.
337,442
def runSavedQueryByUrl(self, saved_query_url, returned_properties=None): try: if "=" not in saved_query_url: raise exception.BadValue() saved_query_id = saved_query_url.split("=")[-1] if not saved_query_id: raise exception.BadValue() ...
Query workitems using the saved query url :param saved_query_url: the saved query url :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :class:`list` that contains the queried ...
337,443
def mag_cal_report_encode(self, compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, diag_y, diag_z, offdiag_x, offdiag_y, offdiag_z): return MAVLink_mag_cal_report_message(compass_id, cal_mask, cal_status, autosaved, fitness, ofs_x, ofs_y, ofs_z, diag_x, d...
Reports results of completed compass calibration. Sent until MAG_CAL_ACK received. compass_id : Compass being calibrated (uint8_t) cal_mask : Bitmask of compasses being calibrated (uint8_t) cal_status : Statu...
337,444
def createNew(cls, store, pathSegments): if isinstance(pathSegments, basestring): raise ValueError( % (pathSegments,)) if store.dbdir is None: self = cls(store=store, storepath=None) else: storepath = store.newDirectory(*pathSegments)...
Create a new SubStore, allocating a new file space for it.
337,445
def load(self, path: str, k: Optional[int] = None): load_time_start = time.time() with open(path, ) as inp: _lex = np.load(inp) loaded_k = _lex.shape[1] if k is not None: top_k = min(k, loaded_k) if k > loaded_k: logger.warning...
Load lexicon from Numpy array file. The top-k target ids will be sorted by increasing target id. :param path: Path to Numpy array file. :param k: Optionally load less items than stored in path.
337,446
def makeLinearcFunc(self,mLvl,pLvl,cLvl): cFunc_by_pLvl_list = [] for j in range(pLvl.shape[0]): pLvl_j = pLvl[j,0] m_temp = mLvl[j,:] - self.BoroCnstNat(pLvl_j) c_temp = cLvl[j,:] if pLvl_j > 0: cFunc_by_pLvl_list.append(LinearI...
Makes a quasi-bilinear interpolation to represent the (unconstrained) consumption function. Parameters ---------- mLvl : np.array Market resource points for interpolation. pLvl : np.array Persistent income level points for interpolation. cLvl : np...
337,447
def validate(self, name, value): validator = self.attribute_validators.get(name, None) if validator: return True if validator(value) else False return True
Validate a cookie attribute with an appropriate validator. The value comes in already parsed (for example, an expires value should be a datetime). Called automatically when an attribute value is set.
337,448
def remove_subkey(self, subkey): if len(self.subkeys) > 0: key = subkey if isinstance(subkey, str) else subkey.key for i in range(len(self.subkeys)): if self.subkeys[i].key == key: self.subkeys.pop(i) break
Remove the given subkey, if existed, from this AdfKey. Parameters ---------- subkey : str or AdfKey The subkey to remove.
337,449
def _is_trivial_angle(rad: float, atol: float) -> bool: return abs(rad) < atol or abs(abs(rad) - np.pi / 4) < atol
Tests if a circuit for an operator exp(i*rad*XX) (or YY, or ZZ) can be performed with a whole CZ. Args: rad: The angle in radians, assumed to be in the range [-pi/4, pi/4]
337,450
def types(self): output = set() for var in self.values(): if var.has_value(): output.update(var.types()) return list(output)
Return a list of all the variable types that exist in the Variables object.
337,451
def gaussianeb_fit_magseries(times, mags, errs, ebparams, sigclip=10.0, plotfit=False, magsarefluxes=False, verbose=True): asymmetricfittypegaussianebfitinfoinitialparamsf...
This fits a double inverted gaussian EB model to a magnitude time series. Parameters ---------- times,mags,errs : np.array The input mag/flux time-series to fit the EB model to. period : float The period to use for EB fit. ebparams : list of float This is a list containin...
337,452
def status(self, record=None): if record is not None: self.last_status = {: ustr(record[]), : ustr(record[]), : record[], : ustr(record[]), : ustr(record[])} ...
Extract status from the retrieved data and save it as a property of an object. If record with data is not specified then the status of previous operation is returned. status - dictionary with data source, string with request and status type, code and message. ...
337,453
def _connect(self, context): if __debug__: log.info("Connecting " + self.engine.partition()[0] + " database layer.", extra=dict( uri = redact_uri(self.uri, self.protect), config = self.config, alias = self.alias, )) self.connection = context.db[self.alias] = self._connector(self.uri, ...
Initialize the database connection.
337,454
def add_vcf_info(keyword, variant_line=None, variant_dict=None, annotation=None): logger = logging.getLogger(__name__) if annotation: new_info = .format(keyword, annotation) else: new_info = keyword logger.debug("Adding new variant information {0}".format(new_info)) ...
Add information to the info field of a vcf variant line. Arguments: variant_line (str): A vcf formatted variant line keyword (str): The info field key annotation (str): If the annotation is a key, value pair this is the string that represents the value ...
337,455
def add_exclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", default=None, node_id=None): exclusive_gateway_id, exclusive_gateway = self.add_gateway_to_diagram(process_id, ...
Adds an exclusiveGateway element to BPMN diagram. :param process_id: string object. ID of parent process, :param gateway_name: string object. Name of exclusive gateway, :param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed". Defa...
337,456
def word_probability(self, word, total_words=None): if total_words is None: total_words = self._word_frequency.total_words return self._word_frequency.dictionary[word] / total_words
Calculate the probability of the `word` being the desired, correct word Args: word (str): The word for which the word probability is \ calculated total_words (int): The total number of words to use in the \ calculation; use the def...
337,457
def _process_change(self, server_description): td_old = self._description if self._publish_server: old_server_description = td_old._server_descriptions[ server_description.address] self._events.put(( self._listeners.publish_server_descript...
Process a new ServerDescription on an opened topology. Hold the lock when calling this.
337,458
def _is_call2custom_manager(node): called = safe_infer(node.func) funcdef = getattr(called, , None) return _is_custom_qs_manager(funcdef)
Checks if the call is being done to a custom queryset manager.
337,459
def _read_header(self): data = np.fromfile(self.filename, dtype=native_header, count=1) self.header.update(recarray2dict(data)) data15hd = self.header[] sec15hd = self.header[] self.mda[] = get_available_channels(self.header) ...
Read the header info
337,460
def raw_pull(self, topic): assert topic is not None, kwargs = {} if not self.user else {: (self.user, self.token)} my_req = requests.get( % ( self.base_url, topic), **kwargs) return my_req
Do a raw pull of data for given topic down from github. :arg topic: String topic (i.e., issue title). ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: Result of request data from github API. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPO...
337,461
def _get_root(cls, order: Optional[str] = None) -> "Console": global _root_console if _root_console is None: _root_console = object.__new__(cls) self = _root_console if order is not None: self._order = order self.console_c = ffi.NULL sel...
Return a root console singleton with valid buffers. This function will also update an already active root console.
337,462
def get_buckets(self, job_id, timestamp=None, body=None, params=None): if job_id in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument .") return self.transport.perform_request( "GET", _make_path( "_ml", "anomaly_detect...
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-bucket.html>`_ :arg job_id: ID of the job to get bucket results from :arg timestamp: The timestamp of the desired single bucket result :arg body: Bucket selection details if not provided in URI :arg anomaly_score: F...
337,463
def parse_resource_entry(self, rva): try: data = self.get_data( rva, Structure(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__).sizeof() ) except PEFormatError, excp: return None resource = self.__unpack_data__( self.__IMAGE_RESOURCE_DIR...
Parse a directory entry from the resources directory.
337,464
def shutdown(opts): try: if not NETWORK_DEVICE.get(, False): raise Exception() NETWORK_DEVICE.get().close() except Exception as error: port = NETWORK_DEVICE.get(, {}).get() log.error( , NETWORK_DEVICE.get(, ), .format(port) if ...
Closes connection with the device.
337,465
def makeLeu(segID, N, CA, C, O, geo): CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_CG_length=geo.CB_CG_length CA_CB_CG_angle= geo.CA_CB_CG_angle N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle CG_CD1_length=geo.CG_CD1_leng...
Creates a Leucine residue
337,466
def submit_indicators(self, indicators, enclave_ids=None, tags=None): if enclave_ids is None: enclave_ids = self.enclave_ids if tags is not None: tags = [tag.to_dict() for tag in tags] body = { "enclaveIds": enclave_ids, "content": [ind...
Submit indicators directly. The indicator field ``value`` is required; all other metadata fields are optional: ``firstSeen``, ``lastSeen``, ``sightings``, ``notes``, and ``source``. The submission must specify enclaves for the indicators to be submitted to, and can optionally specify tags to assign to ...
337,467
def publish(self, topic, message, qos=None, retain=None, ack_timeout=None): def get_retain_and_qos(): if qos: assert qos in (QOS_0, QOS_1, QOS_2) _qos = qos else: _qos = self.config[] try: _qos ...
Publish a message to the broker. Send a MQTT `PUBLISH <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037>`_ message and wait for acknowledgment depending on Quality Of Service This method is a *coroutine*. :param topic: topic name to which message da...
337,468
def hex_to_rgb(hex_value): hex_value = normalize_hex(hex_value) hex_value = int(hex_value[1:], 16) return IntegerRGB( hex_value >> 16, hex_value >> 8 & 0xff, hex_value & 0xff )
Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an ``rgb()`` triplet specifying that color.
337,469
def read_properties(self, audio_file_path): if audio_file_path is None: self.log_exc(u"The audio file path is None", None, True, TypeError) if not gf.file_can_be_read(audio_file_path): self.log_exc(u"Input file cannot be read" % (audio_file_path), None, True, ...
Read the properties of an audio file and return them as a dictionary. Example: :: d["index"]=0 d["codec_name"]=mp3 d["codec_long_name"]=MP3 (MPEG audio layer 3) d["profile"]=unknown d["codec_type"]=audio d["codec_time_base"]=1/441...
337,470
async def cancel(self): self.is_cancelled = True if self.future is not None: self.future.cancel() if self.task_process is not None: log.warning("Worker is shutting down, but a task is running. Terminating task") await self.task_process.worker_shutdown...
Cancel current work.
337,471
def podcast_episode(self, podcast_episode_id): response = self._call( mc_calls.PodcastFetchEpisode, podcast_episode_id ) podcast_episode_info = [ podcast_episode for podcast_episode in response.body if not podcast_episode[] ] return podcast_episode_info
Get information about a podcast_episode. Parameters: podcast_episode_id (str): A podcast episode ID. Returns: dict: Podcast episode information.
337,472
def read(cls, data): if isinstance(data, pd.DataFrame): output = OrderedDict({}) output[] = output[] = [label] = [x for x in list(data.columns.values) if x not in [, ]] output[] = label output[] = OrderedDi...
Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON string, a JSON file, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class Dimension populated with data.
337,473
def _plugins_to_export(self): ret = self.exportable_plugins for p in ret: if getattr(self.args, + p): ret.remove(p) return ret
Return the list of plugins to export.
337,474
def streamify(self, state, frame): return % (self.fmt.pack(len(frame)), frame)
Prepare frame for output as a length/frame stream.
337,475
def encode_offset_fetch_request(cls, group, payloads, from_kafka=False): version = 1 if from_kafka else 0 return kafka.protocol.commit.OffsetFetchRequest[version]( consumer_group=group, topics=[( topic, list(topic_payloads.keys())) ...
Encode an OffsetFetchRequest struct. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request for Kafka offsets. Arguments: group: string, the consumer group you a...
337,476
def serialize_m2m_on_save(sender, action, instance, using, **kwargs): if action == "post_add": try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(us...
Part of the serialize transaction process that ensures m2m are serialized correctly. Skip those not registered.
337,477
def _collapse_pc(master, current, dsn, pc): logger_ts.info("enter collapse_paleo") _table_name, _variable_name = _get_current_names(current, dsn, pc) try: _m = re.match(re_sheet_w_number, _table_name) _switch = {"meas": "measurementTable", "summ": "summaryTable", "en...
Collapse the paleo or chron for the current time series entry :param dict master: LiPD data (so far) :param dict current: Current time series entry :param str dsn: Dataset name :param str pc: paleoData or chronData :return dict master:
337,478
def pad_to_power2(data, axis = None, mode="constant"): if axis is None: axis = list(range(data.ndim)) if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]): return data else: return pad_to_shape(data,[(_next_power_of_2(n) if i in axis else n) for i,n in enum...
pad data to a shape of power 2 if axis == None all axis are padded
337,479
def update(self, **kwargs): self.reload_context(es_based=False, **kwargs) return super(ESCollectionView, self).update(**kwargs)
Explicitly reload context with DB usage to get access to complete DB object.
337,480
def scale_dihedrals(mol, dihedrals, scale, banned_lines=None): if banned_lines is None: banned_lines = [] new_dihedrals = [] for dh in mol.dihedrals: atypes = dh.atom1.get_atomtype(), dh.atom2.get_atomtype(), dh.atom3.get_atomtype(), dh.atom4.get_atomtyp...
Scale dihedral angles
337,481
def lemma(lemma_key): if lemma_key in LEMMAS_DICT: return LEMMAS_DICT[lemma_key] split_lemma_key = lemma_key.split() synset_key = .join(split_lemma_key[:3]) lemma_literal = split_lemma_key[3] lemma_obj = Lemma(synset_key,lemma_literal) LEMMAS_DICT[lemma_key] = lemma_obj return...
Returns the Lemma object with the given key. Parameters ---------- lemma_key : str Key of the returned lemma. Returns ------- Lemma Lemma matching the `lemma_key`.
337,482
def get_version_url(self, full_name, packaging, version, descriptor=None): group, artifact = _parse_full_name(full_name) return self._urls.get_url(group, artifact, packaging, version, descriptor)
Get the URL to a specific version of the given project, optionally using a descriptor to get a particular variant of the version (sources, javadocs, etc.). The name of the artifact should be composed of the group ID and artifact ID (if available). E.g. "com.example.project.service". Depending o...
337,483
def clip_by_value(t, clip_value_min, clip_value_max, name=None): def cast_clip(clip): if t.dtype in (tf.float32, tf.float64): if hasattr(clip, ): clip_dtype = tf.as_dtype(clip.dtype) if clip_dtype != t.dtype: return tf.cast(clip, t.dtype) return clip clip_va...
A wrapper for clip_by_value that casts the clipping range if needed.
337,484
def event_source_mapping_exists(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): desc = describe_event_source_mapping(UUID=UUID, EventSourceArn=EventSour...
Given an event source mapping ID or an event source ARN and FunctionName, check whether the mapping exists. Returns True if the given alias exists and returns False if the given alias does not exist. CLI Example: .. code-block:: bash salt myminion boto_lambda.alias_exists myfunction myal...
337,485
def diff_for_humans(self, other=None, absolute=False, locale=None): is_now = other is None if is_now: other = self.today() diff = self.diff(other) return pendulum.format_diff(diff, is_now, absolute, locale)
Get the difference in a human readable format in the current locale. When comparing a value in the past to default now: 1 day ago 5 months ago When comparing a value in the future to default now: 1 day from now 5 months from now When comparing a value in the pa...
337,486
def login(self, username=None, password=None): if username is None: username = self.username if password is None: password = self.password logger.debug("Logging into server") self.sc.sessionManager.Login(userName=username, password=password) self....
Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type password: str
337,487
def opensignals_hierarchy(root=None, update=False, clone=False): if root is None: root = os.getcwd() categories = list(NOTEBOOK_KEYS.keys()) current_dir = root + "/biosignalsnotebooks_environment" if not os.path.isdir(current_dir): os.makedirs(current_dir) package_...
----- Brief ----- Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically. ----------- Description ----------- OpenSignalsTools Notebooks folder obey to a predefined hierarchy that allows to run the code of online available notebooks and using the sample fi...
337,488
def add_parens(line, maxline, indent, statements=statements, count=count): if line[0] in statements: index = 1 if not line[0].endswith(): index = 2 assert line[1] == line.insert(index, ) if line[-1] == : line.insert(-1, ) else: ...
Attempt to add parentheses around the line in order to make it splittable.
337,489
def to_text(path): import subprocess from distutils import spawn if not spawn.find_executable(): raise EnvironmentError() if not spawn.find_executable(): raise EnvironmentError() convert = [, , , path, , , ] p1 = subprocess.Popen(convert, stdout=subprocess.PIPE) ...
Wraps Tesseract OCR. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format
337,490
def traverse_one(self, attribute, source, target, visitor): if __debug__: self.__log_traverse_one(self.__trv_path, attribute, source, target) prx = source or target rel_op = RELATION_OPERATIONS.check(source, target) if prx.do_traverse() \ and (rel_op == pr...
:param source: source data proxy :type source: instance of `DataTraversalProxy` or None :param target: target data proxy :type target: instance of `DataTraversalProxy` or None
337,491
def sched(self): if len(self.procs) > 1: logger.debug("SCHED:") logger.debug(f"\tProcess: {self.procs!r}") logger.debug(f"\tRunning: {self.running!r}") logger.debug(f"\tRWait: {self.rwait!r}") logger.debug(f"\tTWait: {self.twait!r}") ...
Yield CPU. This will choose another process from the running list and change current running process. May give the same cpu if only one running process.
337,492
def add_child(self, child_type, *args, **kwargs): try: baseplate = kwargs[] except: if self.baseplate is None: baseplate = self.actor_ref else: baseplate = self.baseplate try: lock = kwargs[] except:...
Initialize and keep track of a child. :param child_type: a class inheriting from Lego to initialize \ an instance of :param args: arguments for initializing the child :param kwargs: keyword arguments for initializing the child :return:
337,493
def amplitude_from_polarizations(h_plus, h_cross): amp = (h_plus.squared_norm() + h_cross.squared_norm()) ** (0.5) return TimeSeries(amp, delta_t=h_plus.delta_t, epoch=h_plus.start_time)
Return gravitational wave amplitude Return the gravitation-wave amplitude from the h_plus and h_cross polarizations of the waveform. Parameters ---------- h_plus : TimeSeries An PyCBC TmeSeries vector that contains the plus polarization of the gravitational waveform. h_cross : ...
337,494
def module_refresh(self): log.debug() if self.opts[].get() != : try: reload_module(site) except RuntimeError: log.error() except TypeError: log.error() self.load_mo...
Refresh all the modules
337,495
def cut_value(graph, flow, cut): S = [] T = [] for node in cut.keys(): if cut[node] == 0: S.append(node) elif cut[node] == 1: T.append(node) value = 0 for node in S: for neigh in graph.neighbors(node): if neigh in T: ...
Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function only considers the flow between nodes with ...
337,496
def create_local_socket (self): sock = create_socket(socket.AF_UNIX, socket.SOCK_STREAM) addr = self[] try: sock.connect(addr) except socket.error: sock.close() raise return sock
Create local socket, connect to it and return socket object.
337,497
def replace_row(self, line, ndx): for col in range(len(line)): self.set_tile(ndx, col, line[col])
replace a grids row at index 'ndx' with 'line'
337,498
def rrtmg_lw_gen_source(ext, build_dir): thispath = config.local_path module_src = [] for item in modules: fullname = join(thispath,,,,item) module_src.append(fullname) for item in src: if item in mod_src: fullname = join(thispath,,item) else: ...
Add RRTMG_LW fortran source if Fortran 90 compiler available, if no compiler is found do not try to build the extension.
337,499
def get_3_3_tuple_list(self,obj,default=None): if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,default)]
Return list of 3x3-tuples.