code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pagination_for(context, current_page, page_var="page", exclude_vars=""): """ Include the pagination template and data for persisting querystring in pagination links. Can also contain a comma separated string of var names in the current querystring to exclude from the pagination links, via the ``...
Include the pagination template and data for persisting querystring in pagination links. Can also contain a comma separated string of var names in the current querystring to exclude from the pagination links, via the ``exclude_vars`` arg.
def arquire_attributes(self, attributes, active=True): """ Claims a list of attributes for the current client. Can also disable attributes. Returns update response object. """ attribute_update = self._post_object(self.update_api.attributes.acquire, attributes) return Exis...
Claims a list of attributes for the current client. Can also disable attributes. Returns update response object.
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: """Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1""" assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1...
Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1
def transmission_rate(self): """ Returns the upstream, downstream values as a tuple in bytes per second. Use this for periodical calling. """ sent = self.bytes_sent received = self.bytes_received traffic_call = time.time() time_delta = traffic_call - self....
Returns the upstream, downstream values as a tuple in bytes per second. Use this for periodical calling.
def encode_request(request_line, **headers): '''Creates the data for a SSDP request. Args: request_line (string): The request line for the request (e.g. ``"M-SEARCH * HTTP/1.1"``). headers (dict of string -> string): Dictionary of header name - header value pairs to pres...
Creates the data for a SSDP request. Args: request_line (string): The request line for the request (e.g. ``"M-SEARCH * HTTP/1.1"``). headers (dict of string -> string): Dictionary of header name - header value pairs to present in the request. Returns: bytes: The...
def runGetReference(self, id_): """ Runs a getReference request for the specified ID. """ compoundId = datamodel.ReferenceCompoundId.parse(id_) referenceSet = self.getDataRepository().getReferenceSet( compoundId.reference_set_id) reference = referenceSet.getRe...
Runs a getReference request for the specified ID.
def status(**connection_args): ''' Return the status of a MySQL server using the output from the ``SHOW STATUS`` query. CLI Example: .. code-block:: bash salt '*' mysql.status ''' dbc = _connect(**connection_args) if dbc is None: return {} cur = dbc.cursor() qr...
Return the status of a MySQL server using the output from the ``SHOW STATUS`` query. CLI Example: .. code-block:: bash salt '*' mysql.status
def iou_coe(output, target, threshold=0.5, axis=(1, 2, 3), smooth=1e-5): """Non-differentiable Intersection over Union (IoU) for comparing the similarity of two batch of data, usually be used for evaluating binary image segmentation. The coefficient between 0 to 1, and 1 means totally match. Parameters...
Non-differentiable Intersection over Union (IoU) for comparing the similarity of two batch of data, usually be used for evaluating binary image segmentation. The coefficient between 0 to 1, and 1 means totally match. Parameters ----------- output : tensor A batch of distribution with shape:...
def human_size(size): """ Return a human-readable representation of a byte size. @param size: Number of bytes as an integer or string. @return: String of length 10 with the formatted result. """ if isinstance(size, string_types): size = int(size, 10) if size < 0: return...
Return a human-readable representation of a byte size. @param size: Number of bytes as an integer or string. @return: String of length 10 with the formatted result.
def is_analysis_edition_allowed(self, analysis_brain): """Returns if the analysis passed in can be edited by the current user :param analysis_brain: Brain that represents an analysis :return: True if the user can edit the analysis, otherwise False """ if not self.context_active:...
Returns if the analysis passed in can be edited by the current user :param analysis_brain: Brain that represents an analysis :return: True if the user can edit the analysis, otherwise False
def get_feature(self, ds, feat): """Return filtered feature data The features are filtered according to the user-defined filters, using the information in `ds._filter`. In addition, all `nan` and `inf` values are purged. Parameters ---------- ds: dclab.rtdc_data...
Return filtered feature data The features are filtered according to the user-defined filters, using the information in `ds._filter`. In addition, all `nan` and `inf` values are purged. Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset contain...
def error(self, instance, value, error_class=None, extra=''): """Generates a ValueError on setting property to an invalid value""" error_class = error_class or ValidationError if not isinstance(value, (list, tuple, np.ndarray)): super(Array, self).error(instance, value, error_class, ...
Generates a ValueError on setting property to an invalid value
def connectToBroker(self, protocol): ''' Connect to MQTT broker ''' self.protocol = protocol self.protocol.onPublish = self.onPublish self.protocol.onDisconnection = self.onDisconnection self.protocol.setWindowSize(3) try: ...
Connect to MQTT broker
def convertColors(element): """ Recursively converts all color properties into #RRGGBB format if shorter """ numBytes = 0 if element.nodeType != Node.ELEMENT_NODE: return 0 # set up list of color attributes for each element type attrsToConvert = [] if element.nodeName in ['r...
Recursively converts all color properties into #RRGGBB format if shorter
def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent, name: str = None) -> Schedule: """Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`. Args: parent: Schedule to be inserted into time: Time to be inserted defined with r...
Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`. Args: parent: Schedule to be inserted into time: Time to be inserted defined with respect to `parent` child: Schedule to insert name: Name of the new schedule. Defaults to name of parent
def provideCustomerReferralCode(sender,**kwargs): ''' If the vouchers app is installed and referrals are enabled, then the customer's profile page can show their voucher referral code. ''' customer = kwargs.pop('customer') if getConstant('vouchers__enableVouchers') and getConstant('referrals__e...
If the vouchers app is installed and referrals are enabled, then the customer's profile page can show their voucher referral code.
def _update_statuses(self, sub_job_num=None): """ Update statuses of jobs nodes in workflow. """ # initialize status dictionary status_dict = dict() for val in CONDOR_JOB_STATUSES.values(): status_dict[val] = 0 for node in self.node_set: ...
Update statuses of jobs nodes in workflow.
def runserver(ctx, conf, port, foreground): """Run the fnExchange server""" config = read_config(conf) debug = config['conf'].get('debug', False) click.echo('Debug mode {0}.'.format('on' if debug else 'off')) port = port or config['conf']['server']['port'] app_settings = { 'debug': de...
Run the fnExchange server
def p_const_vector_vector_list(p): """ const_vector_list : const_vector_list COMMA const_vector """ if len(p[3]) != len(p[1][0]): syntax_error(p.lineno(2), 'All rows must have the same number of elements') p[0] = None return p[0] = p[1] + [p[3]]
const_vector_list : const_vector_list COMMA const_vector
def string_to_int( s ): """Convert a string of bytes into an integer, as per X9.62.""" result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result
Convert a string of bytes into an integer, as per X9.62.
def validate(self, value, model=None, context=None): """ Perform validation """ from boiler.user.services import user_service self_id = None if model: if isinstance(model, dict): self_id = model.get('id') else: self_id = getattr(mo...
Perform validation
def _execute(self, query, commit=False, working_columns=None): """ Execute a query with provided parameters Parameters :query: SQL string with parameter placeholders :commit: If True, the query will commit :returns: List of rows """ log.debug(...
Execute a query with provided parameters Parameters :query: SQL string with parameter placeholders :commit: If True, the query will commit :returns: List of rows
def configure_logging(info=False, debug=False): """Configure logging The function configures log messages. By default, log messages are sent to stderr. Set the parameter `debug` to activate the debug mode. :param debug: set the debug mode """ if info: logging.basicConfig(level=loggin...
Configure logging The function configures log messages. By default, log messages are sent to stderr. Set the parameter `debug` to activate the debug mode. :param debug: set the debug mode
def cwd(self, new_path): '''Sets the cwd during reads and writes''' old_cwd = self._cwd self._cwd = new_path return old_cwd
Sets the cwd during reads and writes
def freeSave(self, obj) : """THIS IS WHERE COMMITS TAKE PLACE! Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session""" if self.saveIniator is obj and not self.inTransaction : self.saveIniator = None self.savedObject = set() self.connection.commit(...
THIS IS WHERE COMMITS TAKE PLACE! Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session
def check_params(**kwargs): """check_params: check whether some parameters are missing """ missing_params = [] check = True for param in kwargs: if kwargs[param] is None: missing_params.append(param) if len(missing_params) > 0: print("POT - Warning: following neces...
check_params: check whether some parameters are missing
def _hjoin_multiline(join_char, strings): """Horizontal join of multiline strings """ cstrings = [string.split("\n") for string in strings] max_num_lines = max(len(item) for item in cstrings) pp = [] for k in range(max_num_lines): p = [cstring[k] for cstring in cstrings] pp.appen...
Horizontal join of multiline strings
def add_int(self, name, min, max, warp=None): """An integer-valued dimension bounded between `min` <= x <= `max`. Note that the right endpoint of the interval includes `max`. When `warp` is None, the base measure associated with this dimension is a categorical distribution with each wei...
An integer-valued dimension bounded between `min` <= x <= `max`. Note that the right endpoint of the interval includes `max`. When `warp` is None, the base measure associated with this dimension is a categorical distribution with each weight on each of the integers in [min, max]. With `...
def get_authenticated_user(self, redirect_uri, callback, scope=None, **args): """ class RenrenHandler(tornado.web.RequestHandler, RenrenGraphMixin): @tornado.web.asynchronous @gen.engine def get(self): self.get_authenticated_user( c...
class RenrenHandler(tornado.web.RequestHandler, RenrenGraphMixin): @tornado.web.asynchronous @gen.engine def get(self): self.get_authenticated_user( callback=(yield gen.Callback('key')), redirect_uri=url) user = ...
async def cancel_task(app: web.Application, task: asyncio.Task, *args, **kwargs ) -> Any: """ Convenience function for calling `TaskScheduler.cancel(task)` This will use the default `TaskScheduler` to cancel the given task. Example: ...
Convenience function for calling `TaskScheduler.cancel(task)` This will use the default `TaskScheduler` to cancel the given task. Example: import asyncio from datetime import datetime from brewblox_service import scheduler, service async def current_time(interval): ...
def _organize_variants(samples, batch_id): """Retrieve variant calls for all samples, merging batched samples into single VCF. """ caller_names = [x["variantcaller"] for x in samples[0]["variants"]] calls = collections.defaultdict(list) for data in samples: for vrn in data["variants"]: ...
Retrieve variant calls for all samples, merging batched samples into single VCF.
def clone(self, new_object): """ Returns an object that re-binds the underlying "method" to the specified new object. """ return self.__class__(new_object, self.method, self.name)
Returns an object that re-binds the underlying "method" to the specified new object.
def response(self, model=None, code=HTTPStatus.OK, description=None, **kwargs): """ Endpoint response OpenAPI documentation decorator. It automatically documents HTTPError%(code)d responses with relevant schemas. Arguments: model (flask_marshmallow.Schema) - it can ...
Endpoint response OpenAPI documentation decorator. It automatically documents HTTPError%(code)d responses with relevant schemas. Arguments: model (flask_marshmallow.Schema) - it can be a class or an instance of the class, which will be used for OpenAPI documentation...
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. ...
Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons.
def doc(self): """ Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: ...
Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: - Real names ...
def statuses_show(self, id, trim_user=None, include_my_retweet=None, include_entities=None): """ Returns a single Tweet, specified by the id parameter. https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid :param str id: (*required*) The numeric...
Returns a single Tweet, specified by the id parameter. https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param bool trim_user: When set to ``True``, the tweet's user object includes only the...
def get_files(self): """ :calls: `GET /repos/:owner/:repo/pulls/:number/files <http://developer.github.com/v3/pulls>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.File.File` """ return github.PaginatedList.PaginatedList( github.File.File, ...
:calls: `GET /repos/:owner/:repo/pulls/:number/files <http://developer.github.com/v3/pulls>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.File.File`
def create_ellipse(self,xcen,ycen,a,b,ang,resolution=40.0): """Plot ellipse at x,y with size a,b and orientation ang""" import math e1=[] e2=[] ang=ang-math.radians(90) for i in range(0,int(resolution)+1): x=(-1*a+2*a*float(i)/resolution) y=1-(x/a...
Plot ellipse at x,y with size a,b and orientation ang
def decryptWithSessionRecord(self, sessionRecord, cipherText): """ :type sessionRecord: SessionRecord :type cipherText: WhisperMessage """ previousStates = sessionRecord.getPreviousSessionStates() exceptions = [] try: sessionState = SessionState(sessi...
:type sessionRecord: SessionRecord :type cipherText: WhisperMessage
def deploy_image(self, image_name, oc_new_app_args=None, project=None, name=None): """ Deploy image in OpenShift cluster using 'oc new-app' :param image_name: image name with tag :param oc_new_app_args: additional parameters for the `oc new-app`, env variables etc. :param project...
Deploy image in OpenShift cluster using 'oc new-app' :param image_name: image name with tag :param oc_new_app_args: additional parameters for the `oc new-app`, env variables etc. :param project: project where app should be created, default: current project :param name:str, name of applic...
def create_or_bind_with_claims(self, source_identity): """CreateOrBindWithClaims. [Preview API] :param :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>` source_identity: :rtype: :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>` """ content = ...
CreateOrBindWithClaims. [Preview API] :param :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>` source_identity: :rtype: :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>`
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one r...
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the ...
def fit(self, x, y, **kwargs): """ Fit a naive model :param x: Predictors to use for fitting the data (this will not be used in naive models) :param y: Outcome """ self.mean = numpy.mean(y) return {}
Fit a naive model :param x: Predictors to use for fitting the data (this will not be used in naive models) :param y: Outcome
def _validate(self, inst: "InstanceNode", scope: ValidationScope, ctype: ContentType) -> None: """Extend the superclass method.""" if (scope.value & ValidationScope.syntax.value and inst.value not in self.type): raise YangTypeError(inst.json_pointer(), self....
Extend the superclass method.
def setup_driver(scenario): """Scenario initialization :param scenario: running scenario """ if not hasattr(world, 'config_files'): world.config_files = ConfigFiles() # By default config directory is located in terrain path if not world.config_files.config_directory: world.conf...
Scenario initialization :param scenario: running scenario
def PCA(x, n=False): """ Principal component analysis function. **Args:** * `x` : input matrix (2d array), every row represents new sample **Kwargs:** * `n` : number of features returned (integer) - how many columns should the output keep **Returns:** * `new_x` : matrix ...
Principal component analysis function. **Args:** * `x` : input matrix (2d array), every row represents new sample **Kwargs:** * `n` : number of features returned (integer) - how many columns should the output keep **Returns:** * `new_x` : matrix with reduced size (lower number o...
def get_filestats(cluster, environ, topology, container, path, role=None): ''' :param cluster: :param environ: :param topology: :param container: :param path: :param role: :return: ''' params = dict( cluster=cluster, environ=environ, topology=topology, container=container, ...
:param cluster: :param environ: :param topology: :param container: :param path: :param role: :return:
def _set_traffic_class_mutation(self, v, load=False): """ Setter method for traffic_class_mutation, mapped from YANG variable /qos/map/traffic_class_mutation (list) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_class_mutation is considered as a private meth...
Setter method for traffic_class_mutation, mapped from YANG variable /qos/map/traffic_class_mutation (list) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_class_mutation is considered as a private method. Backends looking to populate this variable should do so vi...
def create_credentials(self, environment_id, source_type=None, credential_details=None, **kwargs): """ Create credentials. Creates a set of credentials to connect to a remote source. Crea...
Create credentials. Creates a set of credentials to connect to a remote source. Created credentials are used in a configuration to associate a collection with the remote source. **Note:** All credentials are sent over an encrypted connection and encrypted at rest. :param str en...
def update_status(self, card_id, code, reimburse_status): """ 更新发票卡券的状态 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1497082828_r1cI2 :param card_id: 发票卡券模板的编号 :param code: 发票卡券的编号 :param reimburse_status: 发票报销状态 """ return self._post( 'pl...
更新发票卡券的状态 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1497082828_r1cI2 :param card_id: 发票卡券模板的编号 :param code: 发票卡券的编号 :param reimburse_status: 发票报销状态
def _sorted_keys(self): """ Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version` """ try: keys = self._cache['sorted_keys'] except KeyError: keys = self._cache['sorted_keys'] = sorted(self.keys(), ...
Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version`
def update_entity(self, entity, if_match='*'): ''' Adds an update entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.update_entity` for more information on updates. The operation will not be executed until the batch is committed. ...
Adds an update entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.update_entity` for more information on updates. The operation will not be executed until the batch is committed. :param entity: The entity to update. Could be a...
def uninstalled(name): ''' Ensure that the named package is not installed. Args: name (str): The flatpak package. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml uninstall_package: flatpack.uninstalled: - name: gimp ...
Ensure that the named package is not installed. Args: name (str): The flatpak package. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml uninstall_package: flatpack.uninstalled: - name: gimp
def typed_node_from_id(id: str) -> TypedNode: """ Get typed node from id :param id: id as curie :return: TypedNode object """ filter_out_types = [ 'cliqueLeader', 'Class', 'Node', 'Individual', 'quality', 'sequence feature' ] node = next(g...
Get typed node from id :param id: id as curie :return: TypedNode object
def clear(self): """ Clears the display and resets the cursor position to ``(0, 0)``. """ self._cx, self._cy = (0, 0) self._canvas.rectangle(self._device.bounding_box, fill=self.default_bgcolor) self.flush()
Clears the display and resets the cursor position to ``(0, 0)``.
def set_attrs(self, **attrs): """Set model attributes, e.g. input resistance of a cell.""" self.attrs.update(attrs) self._backend.set_attrs(**attrs)
Set model attributes, e.g. input resistance of a cell.
def dre_dc(self, pars): r""" :math:Add formula """ self._set_parameters(pars) # term 1 num1a = np.log(self.w * self.tau) * self.otc * np.sin(self.ang) num1b = self.otc * np.cos(self.ang) * np.pi / 2.0 term1 = (num1a + num1b) / self.denom # term 2 ...
r""" :math:Add formula
def _capitalize_word(text, pos): """Capitalize the current (or following) word.""" while pos < len(text) and not text[pos].isalnum(): pos += 1 if pos < len(text): text = text[:pos] + text[pos].upper() + text[pos + 1:] while pos < len(text) and text[pos].isalnum(): pos += 1 re...
Capitalize the current (or following) word.
def get_class_from_settings(settings_key): """Gets a class from a setting key. This will first check loaded models, then look in installed apps, then fallback to import from lib. :param settings_key: the key defined in settings to the value for """ cls_path = getattr(settings, settings_key, None) ...
Gets a class from a setting key. This will first check loaded models, then look in installed apps, then fallback to import from lib. :param settings_key: the key defined in settings to the value for
def generate_wildcard_pem_bytes(): """ Generate a wildcard (subject name '*') self-signed certificate valid for 10 years. https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate :return: Bytes representation of the PEM certificate data """ key = generate_private...
Generate a wildcard (subject name '*') self-signed certificate valid for 10 years. https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate :return: Bytes representation of the PEM certificate data
def validate(self, schema): """ Validate VDOM against given JSON Schema Raises ValidationError if schema does not match """ try: validate(instance=self.to_dict(), schema=schema, cls=Draft4Validator) except ValidationError as e: raise ValidationErr...
Validate VDOM against given JSON Schema Raises ValidationError if schema does not match
def namespace_map(self, target): """Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: d...
Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: dictionary
def set_format(self, column_or_columns, formatter): """Set the format of a column.""" if inspect.isclass(formatter): formatter = formatter() if callable(formatter) and not hasattr(formatter, 'format_column'): formatter = _formats.FunctionFormatter(formatter) if no...
Set the format of a column.
def get_category_or_404(path): """ Retrieve a Category instance by a path. """ path_bits = [p for p in path.split('/') if p] return get_object_or_404(Category, slug=path_bits[-1])
Retrieve a Category instance by a path.
def build_application(conf): """Do some setup and return the wsgi app.""" if isinstance(conf.adapter_options, list): conf['adapter_options'] = {key: val for _dict in conf.adapter_options for key, val in _dict.items()} elif conf.adapter_options is None: conf...
Do some setup and return the wsgi app.
def var(self, ddof=0): '''Calculate variance of timeseries. Return a vector containing the variances of each series in the timeseries. :parameter ddof: delta degree of freedom, the divisor used in the calculation is given by ``N - ddof`` where ``N`` represents the length ...
Calculate variance of timeseries. Return a vector containing the variances of each series in the timeseries. :parameter ddof: delta degree of freedom, the divisor used in the calculation is given by ``N - ddof`` where ``N`` represents the length of timeseries. Default ``0``. ....
def show_in_view(self, sourceview, matches, targetname=None): """ Show search result in ncurses view. """ append = self.options.append_view or self.options.alter_view == 'append' remove = self.options.alter_view == 'remove' action_name = ', appending to' if append else ', removin...
Show search result in ncurses view.
def set_provider_links(self, resource_ids=None): """Sets a provider chain in order from the most recent source to the originating source. :param resource_ids: the new source :type resource_ids: ``osid.id.Id[]`` :raise: ``InvalidArgument`` -- ``resource_ids`` is invalid :...
Sets a provider chain in order from the most recent source to the originating source. :param resource_ids: the new source :type resource_ids: ``osid.id.Id[]`` :raise: ``InvalidArgument`` -- ``resource_ids`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``...
def process_file(self, filename): """Processing one file.""" if self.config.dry_run: if not self.config.internal: self.logger.info("Dry run mode for script %s", filename) with open(filename) as handle: for line in handle: yield ...
Processing one file.
def _on_new_data_received(self, data: bytes): """ Gets called whenever we get a whole new XML element from kik's servers. :param data: The data received (bytes) """ if data == b' ': # Happens every half hour. Disconnect after 10th time. Some kind of keep-alive? Let's ...
Gets called whenever we get a whole new XML element from kik's servers. :param data: The data received (bytes)
def expl_var(self, greenacre=True, N=None): """ Return proportion of explained inertia (variance) for each factor. :param greenacre: Perform Greenacre correction (default: True) """ if greenacre: greenacre_inertia = (self.K / (self.K - 1.) * (sum(self.s**4) - (self.J - self.K) / self.K**2.)) r...
Return proportion of explained inertia (variance) for each factor. :param greenacre: Perform Greenacre correction (default: True)
def get(**kwargs): """ Safe sensor wrapper """ sensor = None tick = 0 driver = DHTReader(**kwargs) while not sensor and tick < TIME_LIMIT: try: sensor = driver.receive_data() except DHTException: tick += 1 return sensor
Safe sensor wrapper
def register_plugin(manager): ''' Register blueprints and actions using given plugin manager. :param manager: plugin manager :type manager: browsepy.manager.PluginManager ''' manager.register_blueprint(player) manager.register_mimetype_function(detect_playable_mimetype) # add style tag...
Register blueprints and actions using given plugin manager. :param manager: plugin manager :type manager: browsepy.manager.PluginManager
def link_contentkey_authorization_policy(access_token, ckap_id, options_id, \ ams_redirected_rest_endpoint): '''Link Media Service Content Key Authorization Policy. Args: access_token (str): A valid Azure authentication token. ckap_id (str): A Media Service Asset Content Key Authorization Polic...
Link Media Service Content Key Authorization Policy. Args: access_token (str): A valid Azure authentication token. ckap_id (str): A Media Service Asset Content Key Authorization Policy ID. options_id (str): A Media Service Content Key Authorization Policy Options . ams_redirected_re...
def chop_into_sequences(episode_ids, unroll_ids, agent_indices, feature_columns, state_columns, max_seq_len, dynamic_max=True, _extra_padding=0): ""...
Truncate and pad experiences into fixed-length sequences. Arguments: episode_ids (list): List of episode ids for each step. unroll_ids (list): List of identifiers for the sample batch. This is used to make sure sequences are cut between sample batches. agent_indices (list): List...
def LookupNamespace(self, prefix): """Resolves a namespace prefix in the scope of the current element. """ ret = libxml2mod.xmlTextReaderLookupNamespace(self._o, prefix) return ret
Resolves a namespace prefix in the scope of the current element.
def build_data_availability(datasets_json): """ Given datasets in JSON format, get the data availability from it if present """ data_availability = None if 'availability' in datasets_json and datasets_json.get('availability'): # only expect one paragraph of text data_availability = d...
Given datasets in JSON format, get the data availability from it if present
def param_sweep(model, sequences, param_grid, n_jobs=1, verbose=0): """Fit a series of models over a range of parameters. Parameters ---------- model : msmbuilder.BaseEstimator An *instance* of an estimator to be used to fit data. sequences : list of array-like List of seque...
Fit a series of models over a range of parameters. Parameters ---------- model : msmbuilder.BaseEstimator An *instance* of an estimator to be used to fit data. sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable o...
def get_conn(self): """ Returns a Google Cloud Storage service object. """ if not self._conn: self._conn = storage.Client(credentials=self._get_credentials()) return self._conn
Returns a Google Cloud Storage service object.
def _data_from_dotnotation(self, key, default=None): """ Returns the MongoDB data from a key using dot notation. Args: key (str): The key to the field in the workflow document. Supports MongoDB's dot notation for embedded fields. default (object): The default val...
Returns the MongoDB data from a key using dot notation. Args: key (str): The key to the field in the workflow document. Supports MongoDB's dot notation for embedded fields. default (object): The default value that is returned if the key does not exist. ...
def snapshot(self, channel=0, path_file=None, timeout=None): """ Args: channel: Values according with Amcrest API: 0 - regular snapshot 1 - motion detection snapshot 2 - alarm snapshot If no channel param is us...
Args: channel: Values according with Amcrest API: 0 - regular snapshot 1 - motion detection snapshot 2 - alarm snapshot If no channel param is used, default is 0 path_file: If path_file is provided...
def get_extension_rights(self): """GetExtensionRights. [Preview API] :rtype: :class:`<ExtensionRightsResult> <azure.devops.v5_0.licensing.models.ExtensionRightsResult>` """ response = self._send(http_method='GET', location_id='5f1dbe21-f748-47c7-b5fd...
GetExtensionRights. [Preview API] :rtype: :class:`<ExtensionRightsResult> <azure.devops.v5_0.licensing.models.ExtensionRightsResult>`
def expand(self, vs=None, conj=False): """Return the Shannon expansion with respect to a list of variables.""" vs = self._expect_vars(vs) if vs: outer, inner = (And, Or) if conj else (Or, And) terms = [inner(self.restrict(p), *boolfunc.point2ter...
Return the Shannon expansion with respect to a list of variables.
def _matches(self, url, options, general_re, domain_required_rules, rules_with_options): """ Return if ``url``/``options`` are matched by rules defined by ``general_re``, ``domain_required_rules`` and ``rules_with_options``. ``general_re`` is a compiled regex for rules ...
Return if ``url``/``options`` are matched by rules defined by ``general_re``, ``domain_required_rules`` and ``rules_with_options``. ``general_re`` is a compiled regex for rules without options. ``domain_required_rules`` is a {domain: [rules_which_require_it]} mapping. ``rules...
def _checkDragDropEvent(self, ev): """Checks if event contains a file URL, accepts if it does, ignores if it doesn't""" mimedata = ev.mimeData() if mimedata.hasUrls(): urls = [str(url.toLocalFile()) for url in mimedata.urls() if url.toLocalFile()] else: urls = [] ...
Checks if event contains a file URL, accepts if it does, ignores if it doesn't
def container_move(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /container-xxxx/move API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2Fmove """ return DXHTTPRequest('/%s/move' % object_...
Invokes the /container-xxxx/move API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2Fmove
def append(self, item): """Add new item to the list. If needed, append will first flush existing items and clear existing items. Args: item: an item to add to the list. """ if self.should_flush(): self.flush() self.items.append(item)
Add new item to the list. If needed, append will first flush existing items and clear existing items. Args: item: an item to add to the list.
def get_response_example(cls, operation, response): """ Get example for response object by operation object :param Operation operation: operation object :param Response response: response object """ path = "#/paths/'{}'/{}/responses/{}".format( operation.path, operat...
Get example for response object by operation object :param Operation operation: operation object :param Response response: response object
def _run(self, bundle, container_id=None, empty_process=False, log_path=None, pid_file=None, sync_socket=None, command="run", log_format="kubernetes"): ''' _run is the base function for run and create, the onl...
_run is the base function for run and create, the only difference between the two being that run does not have an option for sync_socket. Equivalent command line example: singularity oci create [create options...] <container_ID> Parameters ========== bundle: th...
def visitFunctionCall(self, ctx): """ expression : fnname LPAREN parameters? RPAREN """ func_name = ctx.fnname().getText() if ctx.parameters() is not None: parameters = self.visit(ctx.parameters()) else: parameters = [] return self._funct...
expression : fnname LPAREN parameters? RPAREN
def LazyField(lookup_name, scope): """Super non-standard stuff here. Dynamically changing the base class using the scope and the lazy name when the class is instantiated. This works as long as the original base class is not directly inheriting from object (which we're not, since our original base cl...
Super non-standard stuff here. Dynamically changing the base class using the scope and the lazy name when the class is instantiated. This works as long as the original base class is not directly inheriting from object (which we're not, since our original base class is fields.Field).
def static_serve(request, path, client): """ Given a request for a media asset, this view does the necessary wrangling to get the correct thing delivered to the user. This can also emulate the combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True. """ if msettings['SERVE_...
Given a request for a media asset, this view does the necessary wrangling to get the correct thing delivered to the user. This can also emulate the combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True.
def generate_pagerank_graph(num_vertices=250, **kwargs): """Creates a random graph where the vertex types are selected using their pagerank. Calls :func:`.minimal_random_graph` and then :func:`.set_types_rank` where the ``rank`` keyword argument is given by :func:`networkx.pagerank`. Parameter...
Creates a random graph where the vertex types are selected using their pagerank. Calls :func:`.minimal_random_graph` and then :func:`.set_types_rank` where the ``rank`` keyword argument is given by :func:`networkx.pagerank`. Parameters ---------- num_vertices : int (optional, the default i...
def write(self, process_tile, data): """ Write data from process tiles into PNG file(s). Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid`` """ data = self._prepare_array(data) if data.mask.all(): ...
Write data from process tiles into PNG file(s). Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid``
def readWiggleLine(self, line): """ Read a wiggle line. If it is a data line, add values to the protocol object. """ if(line.isspace() or line.startswith("#") or line.startswith("browser") or line.startswith("track")): return elif line.startswi...
Read a wiggle line. If it is a data line, add values to the protocol object.
def field_xpath(field, attribute): """ Field helper functions to locate select, textarea, and the other types of input fields (text, checkbox, radio) :param field: One of the values 'select', 'textarea', 'option', or 'button-element' to match a corresponding HTML element (and to match a <button...
Field helper functions to locate select, textarea, and the other types of input fields (text, checkbox, radio) :param field: One of the values 'select', 'textarea', 'option', or 'button-element' to match a corresponding HTML element (and to match a <button> in the case of 'button-element'). Otherwise a...
def list_mapping(html_cleaned): """将预处理后的网页文档映射成列表和字典,并提取虚假标题 Keyword arguments: html_cleaned -- 预处理后的网页源代码,字符串类型 Return: unit_raw -- 网页文本行 init_dict -- 字典的key是索引,value是网页文本行,并按照网页文本行长度降序排序 fake_title -- 虚假标题,即网页源代码<title>中的文本...
将预处理后的网页文档映射成列表和字典,并提取虚假标题 Keyword arguments: html_cleaned -- 预处理后的网页源代码,字符串类型 Return: unit_raw -- 网页文本行 init_dict -- 字典的key是索引,value是网页文本行,并按照网页文本行长度降序排序 fake_title -- 虚假标题,即网页源代码<title>中的文本行
def unmake(self): """This method is equivalent to delete except that it uses message-passing instead of directly deleting the instance. """ if lib.EnvUnmakeInstance(self._env, self._ist) != 1: raise CLIPSError(self._env)
This method is equivalent to delete except that it uses message-passing instead of directly deleting the instance.
def destroy(name): ''' removes a container [stops a container if it's running and] raises ContainerNotExists exception if the specified name is not created ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-destroy', '-f', '-...
removes a container [stops a container if it's running and] raises ContainerNotExists exception if the specified name is not created
def conditional_distribution(self, values, inplace=True): """ Returns Conditional Probability Distribution after setting values to 1. Parameters ---------- values: list or array_like A list of tuples of the form (variable_name, variable_state). The values...
Returns Conditional Probability Distribution after setting values to 1. Parameters ---------- values: list or array_like A list of tuples of the form (variable_name, variable_state). The values on which to condition the Joint Probability Distribution. inplace: Bo...