code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def GetDomain(self): """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree])
Returns the domain of the B-Spline
def DEFINE_choice(self, name, default, choices, help, constant=False): """A helper for defining choice string options.""" self.AddOption( type_info.Choice( name=name, default=default, choices=choices, description=help), constant=constant)
A helper for defining choice string options.
def connectionLost(self, reason): """ Mostly handles clean-up of node + candidate structures. Avoids memory exhaustion for a large number of connections. """ try: self.connected = False if debug: print(self.log_entry("CLOSED =", "no...
Mostly handles clean-up of node + candidate structures. Avoids memory exhaustion for a large number of connections.
def consume_token(self, tokens, index, tokens_len): """Consume a token. Returns a tuple of (tokens, tokens_len, index) when consumption is completed and tokens have been merged together. """ del tokens_len if tokens[index].type == TokenType.EndInlineRST: ret...
Consume a token. Returns a tuple of (tokens, tokens_len, index) when consumption is completed and tokens have been merged together.
def boolean_flag(parser, name, default=False, help=None): """Add a boolean flag to argparse parser. Parameters ---------- parser: argparse.Parser parser to add the flag to name: str --<name> will enable the flag, while --no-<name> will disable it default: bool or None de...
Add a boolean flag to argparse parser. Parameters ---------- parser: argparse.Parser parser to add the flag to name: str --<name> will enable the flag, while --no-<name> will disable it default: bool or None default value of the flag help: str help string for the...
def del_permission_role(self, role, perm_view): """ Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view in role.permissions: try: ...
Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
def worker_id(self): """A unique identifier for this queue instance and the items it owns.""" if self._worker_id is not None: return self._worker_id return self._get_worker_id(self._conn())
A unique identifier for this queue instance and the items it owns.
def one(self, filter_by=None): """ Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of table), and return True to keep record, or False to skip it. Example : .one(lambda x: x.name == "my_name"). If None,...
Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of table), and return True to keep record, or False to skip it. Example : .one(lambda x: x.name == "my_name"). If None, records are not filtered. Returns ...
def gradient(self, ts): """ Find the gradient of the log likelihood with respect to the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf Returns an 3-element array containing the gradient for the alpha, beta, and omega parameters. ...
Find the gradient of the log likelihood with respect to the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf Returns an 3-element array containing the gradient for the alpha, beta, and omega parameters.
def quantity(*args): """Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s") """ if len(args) == 1: if isinstance(args[0], str): # use copy constructor to create quant...
Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s")
def load_and_init(self, modules): """Import, instantiate & "init" the modules we manage :param modules: list of the managed modules :return: True if no errors """ self.load(modules) self.get_instances() return len(self.configuration_errors) == 0
Import, instantiate & "init" the modules we manage :param modules: list of the managed modules :return: True if no errors
def register_hook(self, hook_name, fn): """Register a function to be called on a GitHub event.""" if hook_name not in self._hooks: self._hooks[hook_name] = fn else: raise Exception('%s hook already registered' % hook_name)
Register a function to be called on a GitHub event.
def _create_prelim(self): """ Step 0: Register intent to upload files """ self._verify(self.payload) if "key" in self.payload[0] and self.payload[0]["key"]: if next((i for i in self.payload if "key" not in i), False): raise ze.UnsupportedParams( ...
Step 0: Register intent to upload files
def clear_feature(dev, feature, recipient = None): r"""Clear/disable a specific feature. dev is the Device object to which the request will be sent to. feature is the feature you want to disable. The recipient can be None (on which the status will be queried from the device), an Interface or ...
r"""Clear/disable a specific feature. dev is the Device object to which the request will be sent to. feature is the feature you want to disable. The recipient can be None (on which the status will be queried from the device), an Interface or Endpoint descriptors.
def check_ace(path, objectType, user, permission=None, acetype=None, propagation=None, exactPermissionMatch=False): ''' Checks a path to verify the ACE (access control entry) specified exists Args: path: path to the file/reg key objectType: The type of object (FILE, DIRECTORY, REGISTRY) ...
Checks a path to verify the ACE (access control entry) specified exists Args: path: path to the file/reg key objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: user that the ACL is for permission: permission to test for (READ, FULLCONTROL, etc) acetype: the...
def plot(args): """ %prog plot workdir sample chr1,chr2 Plot some chromosomes for visual proof. Separate multiple chromosomes with comma. Must contain folder workdir/sample-cn/. """ from jcvi.graphics.base import savefig p = OptionParser(plot.__doc__) opts, args, iopts = p.set_image_op...
%prog plot workdir sample chr1,chr2 Plot some chromosomes for visual proof. Separate multiple chromosomes with comma. Must contain folder workdir/sample-cn/.
def construct_channel(self, *args, **kwargs): """ Create ChannelNode and build topic tree. """ channel = self.get_channel(*args, **kwargs) # creates ChannelNode from data in self.channel_info _build_tree(channel, SAMPLE_TREE) raise_for_invalid_channel(channel) ...
Create ChannelNode and build topic tree.
def get_transition_viewset_method(transition_name, **kwargs): ''' Create a viewset method for the provided `transition_name` ''' @detail_route(methods=['post'], **kwargs) def inner_func(self, request, pk=None, **kwargs): object = self.get_object() transition_method = getattr(object, ...
Create a viewset method for the provided `transition_name`
def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True): """Wrap layers with residual, normalization and dropout. :param name: Prefix of names for internal layers. :param input_layer: Input layer. :param build_func: A callable that takes the input tensor and generates the outpu...
Wrap layers with residual, normalization and dropout. :param name: Prefix of names for internal layers. :param input_layer: Input layer. :param build_func: A callable that takes the input tensor and generates the output tensor. :param dropout_rate: Dropout rate. :param trainable: Whether the layers...
def get(self, specification, *args, **kwargs): """ A more convenient version of :py:meth:`acquire()` for when you can provide positional arguments in a right order. """ arguments = dict(enumerate(args)) arguments.update(kwargs) return self.acquire(specification, a...
A more convenient version of :py:meth:`acquire()` for when you can provide positional arguments in a right order.
def contour_mask(self, contour): """ Generates a binary image with only the given contour filled in. """ # fill in new data new_data = np.zeros(self.data.shape) num_boundary = contour.boundary_pixels.shape[0] boundary_px_ij_swapped = np.zeros([num_boundary, 1, 2]) boundar...
Generates a binary image with only the given contour filled in.
def cmServiceAbort(): """CM SERVICE ABORT Section 9.2.7""" a = TpPd(pd=0x5) b = MessageType(mesType=0x23) # 00100011 packet = a / b return packet
CM SERVICE ABORT Section 9.2.7
def step_command_output_should_not_contain_log_records(context): """ Verifies that the command output contains the specified log records (in any order). .. code-block: gherkin Then the command output should contain the following log records: | category | level | message | ...
Verifies that the command output contains the specified log records (in any order). .. code-block: gherkin Then the command output should contain the following log records: | category | level | message | | bar | CURRENT | xxx |
def OnButtonCell(self, event): """Event handler for cell button toggle button""" if self.button_cell_button_id == event.GetId(): if event.IsChecked(): label = self._get_button_label() post_command_event(self, self.ButtonCellMsg, text=label) else: ...
Event handler for cell button toggle button
def kappa_se_calc(PA, PE, POP): """ Calculate kappa standard error. :param PA: observed agreement among raters (overall accuracy) :type PA : float :param PE: hypothetical probability of chance agreement (random accuracy) :type PE : float :param POP: population :type POP:int :return...
Calculate kappa standard error. :param PA: observed agreement among raters (overall accuracy) :type PA : float :param PE: hypothetical probability of chance agreement (random accuracy) :type PE : float :param POP: population :type POP:int :return: kappa standard error as float
def syslog(server, enable=True): ''' Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell drac.s...
Configure syslog remote logging, by default syslog will automatically be enabled if a server is specified. However, if you want to disable syslog you will need to specify a server followed by False CLI Example: .. code-block:: bash salt dell drac.syslog [SYSLOG IP] [ENABLE/DISABLE] sa...
def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None): r'''Calculates Lewis number or `Le` for a fluid with the given parameters. .. math:: Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D} Inputs can be either of the following sets: * Diffusivity and Thermal diffusivity * Diffusivity, heat...
r'''Calculates Lewis number or `Le` for a fluid with the given parameters. .. math:: Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D} Inputs can be either of the following sets: * Diffusivity and Thermal diffusivity * Diffusivity, heat capacity, thermal conductivity, and density Parameters ...
def parse_media_type(media_type): '''Returns type, subtype, parameter tuple from an http media_type. Can be applied to the 'Accept' or 'Content-Type' http header fields. ''' media_type, sep, parameter = str(media_type).partition(';') media_type, sep, subtype = media_type.partition('/') return tu...
Returns type, subtype, parameter tuple from an http media_type. Can be applied to the 'Accept' or 'Content-Type' http header fields.
def sample_indexes_by_sequence(indexes, sequence): """Samples trajectory/time indexes according to the given sequence of states Parameters ---------- indexes : list of ndarray( (N_i, 2) ) For each state, all trajectory and time indexes where this state occurs. Each matrix has a number o...
Samples trajectory/time indexes according to the given sequence of states Parameters ---------- indexes : list of ndarray( (N_i, 2) ) For each state, all trajectory and time indexes where this state occurs. Each matrix has a number of rows equal to the number of occurrences of the correspon...
def receive(self): ''' Return the message received and the address. ''' try: msg, addr = self.skt.recvfrom(self.buffer_size) except socket.error as error: log.error('Received listener socket error: %s', error, exc_info=True) raise ListenerExcep...
Return the message received and the address.
def get_segmentize_value(input_file=None, tile_pyramid=None): """ Return the recommended segmentation value in input file units. It is calculated by multiplyling raster pixel size with tile shape in pixels. Parameters ---------- input_file : str location of a file readable by raste...
Return the recommended segmentation value in input file units. It is calculated by multiplyling raster pixel size with tile shape in pixels. Parameters ---------- input_file : str location of a file readable by rasterio tile_pyramied : ``TilePyramid`` or ``BufferedTilePyramid`` ...
def main(global_config, **settings): """ Get a PyShop WSGI application configured with settings. """ if sys.version_info[0] < 3: reload(sys) sys.setdefaultencoding('utf-8') settings = dict(settings) # Scoping sessions for Pyramid ensure session are commit/rollback # after th...
Get a PyShop WSGI application configured with settings.
def clear_messages(self): """ Clears all messages. """ while len(self._messages): msg = self._messages.pop(0) usd = msg.block.userData() if usd and hasattr(usd, 'messages'): usd.messages[:] = [] if msg.decoration: ...
Clears all messages.
def p_block_replace(self, p): """ block_decl : identifier t_semicolon """ m = p[1].parse(None) block = self.scope.blocks(m.raw()) if block: p[0] = block.copy_inner(self.scope) else: # fallback to mixin. Allow calls to mixins without p...
block_decl : identifier t_semicolon
def model_to_owl(model, fname): """Save a BioPAX model object as an OWL file. Parameters ---------- model : org.biopax.paxtools.model.Model A BioPAX model object (java object). fname : str The name of the OWL file to save the model in. """ io_class = autoclass('org.biopax.pa...
Save a BioPAX model object as an OWL file. Parameters ---------- model : org.biopax.paxtools.model.Model A BioPAX model object (java object). fname : str The name of the OWL file to save the model in.
def create_notification_plan(self, label=None, name=None, critical_state=None, ok_state=None, warning_state=None): """ Creates a notification plan to be executed when a monitoring check triggers an alarm. """ return self._notification_plan_manager.create(label=label, ...
Creates a notification plan to be executed when a monitoring check triggers an alarm.
def get_root_subject(self): 'Returns the BNode which describes the topmost subject of the graph.' manifest = URIRef(self.manifest) if list(self.rdf.triples((manifest, None, None))): return manifest else: return self.rdf.subjects(None, self.manifest).next()
Returns the BNode which describes the topmost subject of the graph.
def config_absent(name): ''' Ensure configuration property is absent in /usbkey/config name : string name of property ''' name = name.lower() ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # load configuration config = _load...
Ensure configuration property is absent in /usbkey/config name : string name of property
def _getfunctionlist(self): """(internal use) """ try: eventhandler = self.obj.__eventhandler__ except AttributeError: eventhandler = self.obj.__eventhandler__ = {} return eventhandler.setdefault(self.event, [])
(internal use)
def vcenter_interval(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch") id_key = ET.SubElement(vcenter, "id") id_key.text = kwargs.pop('id') interval = ...
Auto Generated Code
def initialize_concept_scheme(rdf, cs, label, language, set_modified): """Initialize a concept scheme: Optionally add a label if the concept scheme doesn't have a label, and optionally add a dct:modified timestamp.""" # check whether the concept scheme is unlabeled, and label it if possible labels ...
Initialize a concept scheme: Optionally add a label if the concept scheme doesn't have a label, and optionally add a dct:modified timestamp.
def validate_block(self, block: BaseBlock) -> None: """ Validate the the given block. """ if not isinstance(block, self.get_block_class()): raise ValidationError( "This vm ({0!r}) is not equipped to validate a block of type {1!r}".format( s...
Validate the the given block.
def insert(self, context): """ Create connection pool. :param resort.engine.execution.Context context: Current execution context. """ status_code, msg = self.__endpoint.post( "/resources/jdbc-connection-pool", data={ "id": self.__name, "resType": self.__res_type, "datasourceClas...
Create connection pool. :param resort.engine.execution.Context context: Current execution context.
def convert_advanced_relu(builder, layer, input_names, output_names, keras_layer): """ Convert an ReLU layer with maximum value from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. ...
Convert an ReLU layer with maximum value from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
def set_key(cls, k, v): """Allows attaching stateless information to the class using the flask session dict """ k = cls.__name__ + "__" + k session[k] = v
Allows attaching stateless information to the class using the flask session dict
def request_ride( self, ride_type=None, start_latitude=None, start_longitude=None, start_address=None, end_latitude=None, end_longitude=None, end_address=None, primetime_confirmation_token=None, ): """Request a ride on behalf of an Lyft...
Request a ride on behalf of an Lyft user. Parameters ride_type (str) Name of the type of ride you're requesting. E.g., lyft, lyft_plus start_latitude (float) Latitude component of a start location. start_longitude (float) ...
def cli(env, identifier): """Remove SSL certificate.""" manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.remove_certificate(identifier)
Remove SSL certificate.
def delete_instance(self, instance_id, project_id=None): """ Deletes the specified Cloud Bigtable instance. Raises google.api_core.exceptions.NotFound if the Cloud Bigtable instance does not exist. :param project_id: Optional, Google Cloud Platform project ID where the ...
Deletes the specified Cloud Bigtable instance. Raises google.api_core.exceptions.NotFound if the Cloud Bigtable instance does not exist. :param project_id: Optional, Google Cloud Platform project ID where the BigTable exists. If set to None or missing, the default projec...
def fix_whitespace(tokens, start, result): """Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts.""" for e in result: for child in e.iter(): child.text = child.text.replace(' , ', ', ') for hyphen in HYPHENS: child.te...
Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts.
def authenticate(self, bound_route, actual_params) -> bool: """ Runs the pre-defined authenticaton service :param bound_route str route matched :param actual_params dict actual url parameters :rtype: bool """ if self.__auth_service is not None: auth_ro...
Runs the pre-defined authenticaton service :param bound_route str route matched :param actual_params dict actual url parameters :rtype: bool
def read_api_service_status(self, name, **kwargs): # noqa: E501 """read_api_service_status # noqa: E501 read status of the specified APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
read_api_service_status # noqa: E501 read status of the specified APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_api_service_status(name, async_req=True) >>...
def get_states(self, action_name, config_name, instances=None, map_name=None, **kwargs): """ Returns a generator of states in relation to the indicated action. :param action_name: Action name. :type action_name: unicode | str :param config_name: Name(s) of container configuratio...
Returns a generator of states in relation to the indicated action. :param action_name: Action name. :type action_name: unicode | str :param config_name: Name(s) of container configuration(s) or MapConfigId tuple(s). :type config_name: unicode | str | collections.Iterable[unicode | str] ...
def combine_HSPs(a): """ Combine HSPs into a single BlastLine. """ m = a[0] if len(a) == 1: return m for b in a[1:]: assert m.query == b.query assert m.subject == b.subject m.hitlen += b.hitlen m.nmismatch += b.nmismatch m.ngaps += b.ngaps ...
Combine HSPs into a single BlastLine.
def set_status(self, value): """ Set the status of the motor to the specified value if not already set. """ if not self._status == value: old = self._status self._status = value logger.info("{} changing status from {} to {}".format(self, old.name, valu...
Set the status of the motor to the specified value if not already set.
def full_y(self, Y): """Add self(shunt) into full Jacobian Y""" if not self.n: return Ysh = matrix(self.g, (self.n, 1), 'd') + 1j * matrix(self.b, (self.n, 1), 'd') uYsh = mul(self.u, Ysh) Y += spmatrix(uYsh, self.a, self.a, Y.size, 'z')
Add self(shunt) into full Jacobian Y
def targets(self): """ Search the targets folder for FASTA files, create the multi-FASTA file of all targets if necessary, and populate objects """ logging.info('Performing analysis with {} targets folder'.format(self.analysistype)) for sample in self.runmetadata: ...
Search the targets folder for FASTA files, create the multi-FASTA file of all targets if necessary, and populate objects
def put(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ headers = None return self.service.invoke(headers, obj)
resource can be a URL or a ResourceLocator
def facets(self, *args, **kwargs): """ Returns a dictionary with the requested facets. The facets function supports string args, and keyword args. q.facets('field_1', 'field_2') will return facets for field_1 and field_2. q.facets(field_1={'limit': 0}, field_2={...
Returns a dictionary with the requested facets. The facets function supports string args, and keyword args. q.facets('field_1', 'field_2') will return facets for field_1 and field_2. q.facets(field_1={'limit': 0}, field_2={'limit': 10}) will return all facets for field_...
def stop(self): """ Stops the ``Pipers`` according to pipeline topology. """ self.log.debug('%s begins stopping routine' % repr(self)) self.log.debug('%s triggers stopping in input pipers' % repr(self)) inputs = self.get_inputs() for piper in inputs: ...
Stops the ``Pipers`` according to pipeline topology.
def lookup(self, asn=None, inc_raw=False, retry_count=3, response=None, field_list=None, asn_alts=None, asn_methods=None): """ The function for retrieving and parsing ASN origin whois information via port 43/tcp (WHOIS). Args: asn (:obj:`str`): The ASN (requir...
The function for retrieving and parsing ASN origin whois information via port 43/tcp (WHOIS). Args: asn (:obj:`str`): The ASN (required). inc_raw (:obj:`bool`): Whether to include the raw results in the returned dictionary. Defaults to False. retry_co...
def simulate(self, data, mime=None): """Simulate the arrival of feeddata into the feed. Useful if the remote Thing doesn't publish very often. `data` (mandatory) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime ty...
Simulate the arrival of feeddata into the feed. Useful if the remote Thing doesn't publish very often. `data` (mandatory) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime type of your data. See: [share()](./Point...
def idxterms(self): """List of index terms.""" try: terms = listify(self._json.get("idxterms", {}).get('mainterm', [])) except AttributeError: # idxterms is empty return None try: return [d['$'] for d in terms] except AttributeError: ...
List of index terms.
def readadd(file, system): """read DYR file""" dyr = {} data = [] end = 0 retval = True sep = ',' fid = open(file, 'r') for line in fid.readlines(): if line.find('/') >= 0: line = line.split('/')[0] end = 1 if line.find(',') >= 0: # mixed comma a...
read DYR file
def _start_console(self): """ Start streaming the console via telnet """ class InputStream: def __init__(self): self._data = b"" def write(self, data): self._data += data @asyncio.coroutine def drain(self...
Start streaming the console via telnet
def damerau_levenshtein_distance(self, s1, s2): """ Dervied algorithm from the following website: https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/ Gives us the distance between two words. """ d = {} lenstr1 = len(s1) lenstr2 = len(s2...
Dervied algorithm from the following website: https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/ Gives us the distance between two words.
def render_math(self, token): """ Ensure Math tokens are all enclosed in two dollar signs. """ if token.content.startswith('$$'): return self.render_raw_text(token) return '${}$'.format(self.render_raw_text(token))
Ensure Math tokens are all enclosed in two dollar signs.
def update_firewall_rule(self, server_name, name, start_ip_address, end_ip_address): ''' Update a firewall rule for an Azure SQL Database server. server_name: Name of the server to set the firewall rule on. name: The name of the fire...
Update a firewall rule for an Azure SQL Database server. server_name: Name of the server to set the firewall rule on. name: The name of the firewall rule to update. start_ip_address: The lowest IP address in the range of the server-level firewall ...
def delete_webhook(self, webhook): """ Deletes the specified webhook from this policy. """ return self.manager.delete_webhook(self.scaling_group, self, webhook)
Deletes the specified webhook from this policy.
def _redirect(self, request, response): """Generic redirect for item editor.""" if '_addanother' in request.POST: return HttpResponseRedirect('../item_add/') elif '_save' in request.POST: return HttpResponseRedirect('../') elif '_continue' in request.POST: ...
Generic redirect for item editor.
def visit_Include(self, node, frame): """Handles includes.""" if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.value, string_types)...
Handles includes.
def read_file(filepath, **kwargs): """ Read a data file into a DataFrameModel. :param filepath: The rows/columns filepath to read. :param kwargs: xls/x files - see pandas.read_excel(**kwargs) .csv/.txt/etc - see pandas.read_csv(**kwargs) :return: DataFrameModel """ r...
Read a data file into a DataFrameModel. :param filepath: The rows/columns filepath to read. :param kwargs: xls/x files - see pandas.read_excel(**kwargs) .csv/.txt/etc - see pandas.read_csv(**kwargs) :return: DataFrameModel
def calc_acceleration_bca(jackknife_replicates): """ Calculate the acceleration constant for the Bias Corrected and Accelerated (BCa) bootstrap confidence intervals. Parameters ---------- jackknife_replicates : 2D ndarray. Each row should correspond to a different jackknife parameter sa...
Calculate the acceleration constant for the Bias Corrected and Accelerated (BCa) bootstrap confidence intervals. Parameters ---------- jackknife_replicates : 2D ndarray. Each row should correspond to a different jackknife parameter sample, formed by deleting a particular observation and...
def bytes_array(self): '''Get the param as an array of raw byte strings.''' assert len(self.dimensions) == 2, \ '{}: cannot get value as bytes array!'.format(self.name) l, n = self.dimensions return [self.bytes[i*l:(i+1)*l] for i in range(n)]
Get the param as an array of raw byte strings.
def reload(self, client=None): """Update this notification from the server configuration. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:...
Update this notification from the server configuration. See: https://cloud.google.com/storage/docs/json_api/v1/notifications/get If :attr:`user_project` is set on the bucket, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ...
def new_parallel(self, function, *params): ''' Register a new thread executing a parallel method. ''' # Create a pool if not created (processes or Gevent...) if self.ppool is None: if core_type == 'thread': from multiprocessing.pool import ThreadPool ...
Register a new thread executing a parallel method.
def new(params, event_size, num_components, dtype=None, validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" with tf.compat.v1.name_scope(name, 'CategoricalMixtureOfOneHotCategorical', [params, event_size, num_components]): ...
Create the distribution instance from a `params` vector.
def encode_request(name, items): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, items)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_int(len(...
Encode request into client_message
def encrypt(self, data, nounce=None): """Encrypt data with counter or specified nounce.""" if nounce is None: nounce = self._out_counter.to_bytes(length=8, byteorder='little') self._out_counter += 1 return self._enc_out.seal(b'\x00\x00\x00\x00' + nounce, data, bytes())
Encrypt data with counter or specified nounce.
def at_line(self, line: FileLine) -> Iterator[InsertionPoint]: """ Returns an iterator over all of the insertion points located at a given line. """ logger.debug("finding insertion points at line: %s", str(line)) filename = line.filename # type: str line_num = li...
Returns an iterator over all of the insertion points located at a given line.
def cli(obj, roles): """List users.""" client = obj['client'] query = [('roles', r) for r in roles] if obj['output'] == 'json': r = client.http.get('/users', query) click.echo(json.dumps(r['users'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezon...
List users.
def delete_tag(context, id, tag_id): """delete_tag(context, id, tag_id) Delete a tag from a job. >>> dcictl job-delete-tag [OPTIONS] :param string id: ID of the job to attach the meta to [required] :param string tag_id: ID of the tag to be removed from the job [required] """ result = job...
delete_tag(context, id, tag_id) Delete a tag from a job. >>> dcictl job-delete-tag [OPTIONS] :param string id: ID of the job to attach the meta to [required] :param string tag_id: ID of the tag to be removed from the job [required]
def split_comma_argument(comma_sep_str): """Split a comma separated option into a list.""" terms = [] for term in comma_sep_str.split(','): if term: terms.append(term) return terms
Split a comma separated option into a list.
def _mkdirs_impacket(path, share='C$', conn=None, host=None, username=None, password=None): ''' Recursively create a directory structure on an SMB share Paths should be passed in with forward-slash delimiters, and should not start with a forward-slash. ''' if conn is None: conn = get_co...
Recursively create a directory structure on an SMB share Paths should be passed in with forward-slash delimiters, and should not start with a forward-slash.
def concatenate(x, other): """Returns the concatenation of the dimension in `x` and `other`. *Note:* If either `x` or `other` is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing. F...
Returns the concatenation of the dimension in `x` and `other`. *Note:* If either `x` or `other` is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing. For more details, see `help(tf.Te...
def transform(testtype): ''' A lot of these transformations are from tasks before task labels and some of them are if we grab data directly from Treeherder jobs endpoint instead of runnable jobs API. ''' # XXX: Evaluate which of these transformations are still valid if testtype.startswith('[funs...
A lot of these transformations are from tasks before task labels and some of them are if we grab data directly from Treeherder jobs endpoint instead of runnable jobs API.
def map_aliases_to_device_objects(self): """ A device object knows its rid, but not its alias. A portal object knows its device rids and aliases. This function adds an 'portals_aliases' key to all of the device objects so they can be sorted by alias. """...
A device object knows its rid, but not its alias. A portal object knows its device rids and aliases. This function adds an 'portals_aliases' key to all of the device objects so they can be sorted by alias.
def predict_proba(self, X): """Predict the distances for X to center of the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a spa...
Predict the distances for X to center of the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a...
def turn_on(host, did, token=None): """Turn on bulb or fixture""" urllib3.disable_warnings() if token: scheme = "https" if not token: scheme = "http" token = "1234567890" url = ( scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendCommand&data=<gip><version>1</ver...
Turn on bulb or fixture
async def async_delete_all_keys(session, host, port, api_key, api_keys=[]): """Delete all API keys except for the ones provided to the method.""" url = 'http://{}:{}/api/{}/config'.format(host, str(port), api_key) response = await async_request(session.get, url) api_keys.append(api_key) for key in...
Delete all API keys except for the ones provided to the method.
def cov_dvrpmllbb_to_vxyz(d,e_d,e_vr,pmll,pmbb,cov_pmllbb,l,b, plx=False,degree=False): """ NAME: cov_dvrpmllbb_to_vxyz PURPOSE: propagate distance, radial velocity, and proper motion uncertainties to Galactic coordinates INPUT: d - distance [kpc, as/m...
NAME: cov_dvrpmllbb_to_vxyz PURPOSE: propagate distance, radial velocity, and proper motion uncertainties to Galactic coordinates INPUT: d - distance [kpc, as/mas for plx] e_d - distance uncertainty [kpc, [as/mas] for plx] e_vr - low velocity uncertainty [km/s] ...
def mission_count_send(self, target_system, target_component, count, force_mavlink1=False): ''' This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item...
This message is emitted as response to MISSION_REQUEST_LIST by the MAV and to initiate a write transaction. The GCS can then request the individual mission item based on the knowledge of the total number of MISSIONs. target_system : System ID ...
def r(op, rc=None, r=None, iq=None, ico=None, pl=None): # pylint: disable=redefined-outer-name, invalid-name, invalid-name """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.References`. Instance-level use: Retrieve the association instances referencing a source instance. Cla...
This function is a wrapper for :meth:`~pywbem.WBEMConnection.References`. Instance-level use: Retrieve the association instances referencing a source instance. Class-level use: Retrieve the association classes referencing a source class. Parameters: op (:class:`~pywbem.CIMInstanceName`...
def get_configs( config_filepath, local_filepath_override='', ): """go and fetch the global/local configs from file and load them with configparser Args: config_filepath (str): path to config local_filepath_override (str): secondary place to locate config file Returns: ...
go and fetch the global/local configs from file and load them with configparser Args: config_filepath (str): path to config local_filepath_override (str): secondary place to locate config file Returns: ConfigParser: global_config ConfigParser: local_config
def setup_logger(log_level, log_file=None): """setup root logger with ColoredFormatter.""" level = getattr(logging, log_level.upper(), None) if not level: color_print("Invalid log level: %s" % log_level, "RED") sys.exit(1) # hide traceback when log level is INFO/WARNING/ERROR/CRITICAL ...
setup root logger with ColoredFormatter.
def _set_property(self, name, value): """ Set property `name` to `value`, but only if it is part of the mapping returned from `worker_mapping` (ie - data transported to frontend). This method is used from the REST API DB, so it knows what to set and what not, to prevent users fr...
Set property `name` to `value`, but only if it is part of the mapping returned from `worker_mapping` (ie - data transported to frontend). This method is used from the REST API DB, so it knows what to set and what not, to prevent users from setting internal values. Args: nam...
def convex_conj(self): """The convex conjugate functional of the group L1-norm.""" conj_exp = conj_exponent(self.pointwise_norm.exponent) return IndicatorGroupL1UnitBall(self.domain, exponent=conj_exp)
The convex conjugate functional of the group L1-norm.
def xywh_from_points(points): """ Constructs an dict representing a rectangle with keys x, y, w, h """ xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')] minx = sys.maxsize miny = sys.maxsize maxx = 0 maxy = 0 for xy in xys: if xy[0] < minx: m...
Constructs an dict representing a rectangle with keys x, y, w, h
def set_password(self, password, user='', note=None): """Sets the password for the current user or passed-in user. As a side effect, installs the "password" package. @param user: username to set the password for. Defaults to '' (i.e. current user) @...
Sets the password for the current user or passed-in user. As a side effect, installs the "password" package. @param user: username to set the password for. Defaults to '' (i.e. current user) @param password: password to set for the user @param note: See send()
def geoframe(self, *args, **kwargs): """Return a Geo dataframe""" from geopandas import GeoDataFrame import geopandas as gpd from shapely.geometry.polygon import BaseGeometry from shapely.wkt import loads gdf = None try: gdf = self.resolved_url.geofr...
Return a Geo dataframe
def ListFileEntries(self, base_path_specs, output_writer): """Lists file entries in the base path specification. Args: base_path_specs (list[dfvfs.PathSpec]): source path specification. output_writer (StdoutWriter): output writer. """ for base_path_spec in base_path_specs: file_system...
Lists file entries in the base path specification. Args: base_path_specs (list[dfvfs.PathSpec]): source path specification. output_writer (StdoutWriter): output writer.