code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def write_wrapped(self, s, extra_room=0): """Add a soft line break if needed, then write s.""" if self.room < len(s) + extra_room: self.write_soft_break() self.write_str(s)
Add a soft line break if needed, then write s.
def _login(self, csrf_token): """Attempt to login session on easyname.""" login_response = self.session.post( self.URLS['login'], data={ 'username': self._get_provider_option('auth_username') or '', 'password': self._get_provider_option('auth_passw...
Attempt to login session on easyname.
def _prep_binary_content(self): ''' Sets delivery method of either payload or header Favors Content-Location header if set Args: None Returns: None: sets attributes in self.binary and headers ''' # nothing present if not self.data and not self.location and 'Content-Location' not in self.resour...
Sets delivery method of either payload or header Favors Content-Location header if set Args: None Returns: None: sets attributes in self.binary and headers
def _cleanup(self): ''' Cleanup all the local data. ''' self._declare_cb = None self._bind_cb = None self._unbind_cb = None self._delete_cb = None self._purge_cb = None super(QueueClass, self)._cleanup()
Cleanup all the local data.
def choose_branch(exclude=None): # type: (List[str]) -> str """ Show the user a menu to pick a branch from the existing ones. Args: exclude (list[str]): List of branch names to exclude from the menu. By default it will exclude master and develop branches. To show all branche...
Show the user a menu to pick a branch from the existing ones. Args: exclude (list[str]): List of branch names to exclude from the menu. By default it will exclude master and develop branches. To show all branches pass an empty array here. Returns: str: The n...
def _qteUpdateLabelWidths(self): """ Ensure all but the last ``QLabel`` are only as wide as necessary. The width of the last label is manually set to a large value to ensure that it stretches as much as possible. The height of all widgets is also set appropriately. The method al...
Ensure all but the last ``QLabel`` are only as wide as necessary. The width of the last label is manually set to a large value to ensure that it stretches as much as possible. The height of all widgets is also set appropriately. The method also takes care or rearranging the widgets in t...
def publish(self, name, data, userList): """ Publish data """ # Publish data to all room users self.broadcast(userList, { "name": name, "data": SockJSDefaultHandler._parser.encode(data) })
Publish data
def provider(self, name, history=None): """ Find the provider of the property by I{name}. @param name: The property name. @type name: str @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return:...
Find the provider of the property by I{name}. @param name: The property name. @type name: str @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: The provider when found. Otherwise, None (when nested) ...
def AsPrimitiveProto(self): """Return an old style protocol buffer object.""" if self.protobuf: result = self.protobuf() result.ParseFromString(self.SerializeToString()) return result
Return an old style protocol buffer object.
def targetSigma2(self,R,log=False): """ NAME: targetSigma2 PURPOSE: evaluate the target Sigma_R^2(R) INPUT: R - radius at which to evaluate (can be Quantity) OUTPUT: target Sigma_R^2(R) log - if True, return the log ...
NAME: targetSigma2 PURPOSE: evaluate the target Sigma_R^2(R) INPUT: R - radius at which to evaluate (can be Quantity) OUTPUT: target Sigma_R^2(R) log - if True, return the log (default: False) HISTORY: 2010-03-2...
def _validate_arch(self, arch = None): """ @type arch: str @param arch: Name of the processor architecture. If not provided the current processor architecture is assumed. For more details see L{win32.version._get_arch}. @rtype: str @return: Name of the ...
@type arch: str @param arch: Name of the processor architecture. If not provided the current processor architecture is assumed. For more details see L{win32.version._get_arch}. @rtype: str @return: Name of the processor architecture. If not provided the cur...
def ver(self, value): """The ver property. Args: value (int). the property value. """ if value == self._defaults['ver'] and 'ver' in self._values: del self._values['ver'] else: self._values['ver'] = value
The ver property. Args: value (int). the property value.
def create_namespaced_endpoints(self, namespace, body, **kwargs): """ create Endpoints This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_endpoints(namespace, body, async_req...
create Endpoints This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_endpoints(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param...
def _call_geocoder( self, url, timeout=DEFAULT_SENTINEL, raw=False, requester=None, deserializer=json.loads, **kwargs ): """ For a generated query URL, get the results. """ if requester: ...
For a generated query URL, get the results.
def every_other(x, name=None): """Drops every other value from the tensor and returns a 1D tensor. This is useful if you are running multiple inputs through a model tower before splitting them and you want to line it up with some other data. Args: x: the target tensor. name: the name for this op, defa...
Drops every other value from the tensor and returns a 1D tensor. This is useful if you are running multiple inputs through a model tower before splitting them and you want to line it up with some other data. Args: x: the target tensor. name: the name for this op, defaults to every_other Returns: A...
def forum_topic_undelete(self, topic_id): """Un delete a topic (Login requries) (Moderator+) (UNTESTED). Parameters: topic_id (int): Where topic_id is the topic id. """ return self._get('forum_topics/{0}/undelete.json'.format(topic_id), method='POST'...
Un delete a topic (Login requries) (Moderator+) (UNTESTED). Parameters: topic_id (int): Where topic_id is the topic id.
def textwidth(self, text, config): """Calculates the width of the specified text. """ surface = cairo.SVGSurface(None, 1280, 200) ctx = cairo.Context(surface) ctx.select_font_face(config['font_face'], cairo.FONT_SLANT_NORMAL, ...
Calculates the width of the specified text.
def match_status_code(self, entry, status_code, regex=True): """ Helper function that returns entries with a status code matching then given `status_code` argument. NOTE: This is doing a STRING comparison NOT NUMERICAL :param entry: entry object to analyze :param status...
Helper function that returns entries with a status code matching then given `status_code` argument. NOTE: This is doing a STRING comparison NOT NUMERICAL :param entry: entry object to analyze :param status_code: ``str`` of status code to search for :param request_type: ``regex`...
def map(self, options=None): """Trigger find of serialized sources and build objects""" for path, data in self.paths.items(): references = data.get("references", []) for item in data["items"]: for obj in self.create_class(item, options, references=references): ...
Trigger find of serialized sources and build objects
def build_loss(model_logits, sparse_targets): """Compute the log loss given predictions and targets.""" time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size] flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1] xent = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=tf.reshape(model_lo...
Compute the log loss given predictions and targets.
def find_ports(device): """ Find the port chain a device is plugged on. This is done by searching sysfs for a device that matches the device bus/address combination. Useful when the underlying usb lib does not return device.port_number for whatever reason. """ bus_id = device.bus d...
Find the port chain a device is plugged on. This is done by searching sysfs for a device that matches the device bus/address combination. Useful when the underlying usb lib does not return device.port_number for whatever reason.
def initialize_page_data(self): """Initialize the page data for the given screen.""" if self.term.is_a_tty: self.display_initialize() self.character_generator = self.character_factory(self.screen.wide) page_data = list() while True: try: pa...
Initialize the page data for the given screen.
def labeled_intervals(intervals, labels, label_set=None, base=None, height=None, extend_labels=True, ax=None, tick=True, **kwargs): '''Plot labeled intervals with each label on its own row. Parameters ---------- intervals : np.ndarray, shape=(n, 2) se...
Plot labeled intervals with each label on its own row. Parameters ---------- intervals : np.ndarray, shape=(n, 2) segment intervals, in the format returned by :func:`mir_eval.io.load_intervals` or :func:`mir_eval.io.load_labeled_intervals`. labels : list, shape=(n,) ref...
def run(addr, *commands, **kwargs): """ Non-threaded batch command runner returning output results """ results = [] handler = VarnishHandler(addr, **kwargs) for cmd in commands: if isinstance(cmd, tuple) and len(cmd)>1: results.extend([getattr(handler, c[0].replace('.','_'))(...
Non-threaded batch command runner returning output results
def getWidget(self,**kwargs): """ Wrapper function that returns a new widget attached to this simulation. Widgets provide real-time 3D visualizations from within an Jupyter notebook. See the Widget class for more details on the possible arguments. Arguments ...
Wrapper function that returns a new widget attached to this simulation. Widgets provide real-time 3D visualizations from within an Jupyter notebook. See the Widget class for more details on the possible arguments. Arguments --------- All arguments passed to thi...
def find_warnings(content): """Look for lines containing warning/error/info strings instead of data.""" keywords = [k.lower() for k in [ "WARNING", "Couldn't find device", "Configuration setting", "read failed", "Was device resized?", "Invalid argument", "leaked on lvs", "Checksum error"...
Look for lines containing warning/error/info strings instead of data.
def add(self, value): """ Add a value to the reservoir The value will be casted to a floating-point, so a TypeError or a ValueError may be raised. """ if not isinstance(value, float): value = float(value) return self._do_add(value)
Add a value to the reservoir The value will be casted to a floating-point, so a TypeError or a ValueError may be raised.
def __create(self, options, collation, session): """Sends a create command with the given options. """ cmd = SON([("create", self.__name)]) if options: if "size" in options: options["size"] = float(options["size"]) cmd.update(options) with ...
Sends a create command with the given options.
def hangup_all_calls(self): """REST Hangup All Live Calls Helper """ path = '/' + self.api_version + '/HangupAllCalls/' method = 'POST' return self.request(path, method)
REST Hangup All Live Calls Helper
def argsort(self, axis=-1, kind="quicksort", order=None): """ Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km...
Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.ar...
def retweets(self, tweet_id): """ Retrieves up to the last 100 retweets for the provided tweet. """ log.info("retrieving retweets of %s", tweet_id) url = "https://api.twitter.com/1.1/statuses/retweets/""{}.json".format( tweet_id) resp = self.get(u...
Retrieves up to the last 100 retweets for the provided tweet.
def all(self, command, params=None): """ Возвращает строки ответа, полученного через query > db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID}) :param command: SQL запрос :param params: Параметры для prepared statements :rtype: list of dict """ ...
Возвращает строки ответа, полученного через query > db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID}) :param command: SQL запрос :param params: Параметры для prepared statements :rtype: list of dict
def try_handle_route(self, route_uri, method, request, uri, headers): """Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :p...
Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dic...
def decorate_client(api_client, func, name): """A helper for decorating :class:`bravado.client.SwaggerClient`. :class:`bravado.client.SwaggerClient` can be extended by creating a class which wraps all calls to it. This helper is used in a :func:`__getattr__` to check if the attr exists on the api_client...
A helper for decorating :class:`bravado.client.SwaggerClient`. :class:`bravado.client.SwaggerClient` can be extended by creating a class which wraps all calls to it. This helper is used in a :func:`__getattr__` to check if the attr exists on the api_client. If the attr does not exist raise :class:`Attri...
def set_state(self, state=None, **kwargs): """ Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict ...
Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict The camera state. **kwargs : dict ...
def change_svc_snapshot_command(self, service, snapshot_command): """Modify host snapshot command Format of the line that triggers function call:: CHANGE_HOST_SNAPSHOT_COMMAND;<host_name>;<event_handler_command> :param service: service to modify snapshot command :type service: ...
Modify host snapshot command Format of the line that triggers function call:: CHANGE_HOST_SNAPSHOT_COMMAND;<host_name>;<event_handler_command> :param service: service to modify snapshot command :type service: alignak.objects.service.Service :param snapshot_command: snapshot com...
def blastparse(self): """ Parse the blast results, and store necessary data in dictionaries in sample object """ logging.info('Parsing BLAST results') # Load the NCBI 16S reference database as a dictionary for sample in self.runmetadata.samples: if sample.gene...
Parse the blast results, and store necessary data in dictionaries in sample object
def _get_ctx(self): """ Get web.ctx object for the Template helper """ if self._WEB_CTX_KEY not in web.ctx: web.ctx[self._WEB_CTX_KEY] = { "javascript": {"footer": [], "header": []}, "css": []} return web.ctx.get(self._WEB_CTX_KEY)
Get web.ctx object for the Template helper
def get_resource(self, resource_key, **variables): """Get a resource. Attempts to get and return a cached version of the resource if available, otherwise a new resource object is created and returned. Args: resource_key (`str`): Name of the type of `Resources` to find ...
Get a resource. Attempts to get and return a cached version of the resource if available, otherwise a new resource object is created and returned. Args: resource_key (`str`): Name of the type of `Resources` to find variables: data to identify / store on the resource ...
def sph2cart(r, az, elev): """ Convert spherical to cartesian coordinates. Attributes ---------- r : float radius az : float aziumth (angle about z axis) elev : float elevation from xy plane Returns ------- float x-coordinate float y-coor...
Convert spherical to cartesian coordinates. Attributes ---------- r : float radius az : float aziumth (angle about z axis) elev : float elevation from xy plane Returns ------- float x-coordinate float y-coordinate float z-coordina...
def dataset_publication_finished(self, ignore_exception=False): ''' This is the "commit". It triggers the creation/update of handles. * Check if the set of files corresponds to the previously published set (if applicable, and if solr url given, and if solr replied) * The dataset...
This is the "commit". It triggers the creation/update of handles. * Check if the set of files corresponds to the previously published set (if applicable, and if solr url given, and if solr replied) * The dataset publication message is created and sent to the queue. * All file publicatio...
def prepare_payload(op, method, uri, data): """Return the URI (modified perhaps) and body and headers. - For GET requests, encode parameters in the query string. - Otherwise always encode parameters in the request body. - Except op; this can always go in the query string. :param method: The HTTP...
Return the URI (modified perhaps) and body and headers. - For GET requests, encode parameters in the query string. - Otherwise always encode parameters in the request body. - Except op; this can always go in the query string. :param method: The HTTP method. :param uri: The URI of the action. ...
def boxed(msg, ch="=", pad=5): """ Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** *********** """ ...
Returns a string in a box Args: msg: Input string. ch: Character used to form the box. pad: Number of characters ch added before and after msg. >>> print(boxed("hello", ch="*", pad=2)) *********** ** hello ** ***********
def get_results(self, metadata=False): """ Return results of the analysis. """ results_data = [] self.process_har() self.process_from_splash() for rt in sorted(self._results.get_results()): rdict = {'name': rt.name} if rt.version: rdict['...
Return results of the analysis.
def _get_json(endpoint, params, referer='scores'): """ Internal method to streamline our requests / json getting Args: endpoint (str): endpoint to be called from the API params (dict): parameters to be passed to the API Raises: HTTPError: if requests hits a status code != 200 ...
Internal method to streamline our requests / json getting Args: endpoint (str): endpoint to be called from the API params (dict): parameters to be passed to the API Raises: HTTPError: if requests hits a status code != 200 Returns: json (json): json object for selected API ...
def group_dict(self, group: str) -> Dict[str, Any]: """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') de...
The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_com...
def apply_connectivity_changes(self, request): """ Handle apply connectivity changes request json, trigger add or remove vlan methods, get responce from them and create json response :param request: json with all required action to configure or remove vlans from certain port :return Ser...
Handle apply connectivity changes request json, trigger add or remove vlan methods, get responce from them and create json response :param request: json with all required action to configure or remove vlans from certain port :return Serialized DriverResponseRoot to json :rtype json
def get_client(client=None): """ Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client """ global _client tmp_client = client is not None if not tmp_client: config = getattr(django_settings, "ELASTIC_APM", {}) client = config.get("CLIENT",...
Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client
def generate_password(self) -> list: """Generate a list of random characters.""" characterset = self._get_password_characters() if ( self.passwordlen is None or not characterset ): raise ValueError("Can't generate password: character set is " ...
Generate a list of random characters.
def _add_cloned_sers(self, plotArea, count): """ Add `c:ser` elements to the last xChart element in *plotArea*, cloned from the last `c:ser` child of that last xChart. """ def clone_ser(ser): new_ser = deepcopy(ser) new_ser.idx.val = plotArea.next_idx ...
Add `c:ser` elements to the last xChart element in *plotArea*, cloned from the last `c:ser` child of that last xChart.
def connectAlt(cls, redisConnectionParams): ''' connectAlt - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model. @param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS. @r...
connectAlt - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model. @param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS. @return - A class that can be used in all the same ways...
def copy(self): """ Deepcopy the parameter (with a new uniqueid). All other tags will remain the same... so some other tag should be changed before attaching back to a ParameterSet or Bundle. :return: the copied :class:`Parameter` object """ s = self.to_json() ...
Deepcopy the parameter (with a new uniqueid). All other tags will remain the same... so some other tag should be changed before attaching back to a ParameterSet or Bundle. :return: the copied :class:`Parameter` object
def get_mode_group(self, group): """While a reference is kept by the caller, the returned mode group will compare equal with mode group returned by each subsequent call of this method with the same index and mode group returned from :attr:`~libinput.event.TabletPadEvent.mode_group`, provided the event was gen...
While a reference is kept by the caller, the returned mode group will compare equal with mode group returned by each subsequent call of this method with the same index and mode group returned from :attr:`~libinput.event.TabletPadEvent.mode_group`, provided the event was generated by this mode group. Args: ...
def load_metadata_for_topics(self, *topics): """ Fetch broker and topic-partition metadata from the server, and update internal data: broker list, topic/partition list, and topic/parition -> broker map This method should be called after receiving any error Arguments: ...
Fetch broker and topic-partition metadata from the server, and update internal data: broker list, topic/partition list, and topic/parition -> broker map This method should be called after receiving any error Arguments: *topics (optional): If a list of topics is provided, ...
def ldirectory(inpath, outpath, args, scope): """Compile all *.less files in directory Args: inpath (str): Path to compile outpath (str): Output directory args (object): Argparse Object scope (Scope): Scope object or None """ yacctab = 'yacctab' if args.debug else None ...
Compile all *.less files in directory Args: inpath (str): Path to compile outpath (str): Output directory args (object): Argparse Object scope (Scope): Scope object or None
def close(self): """ Closes this IOU VM. """ if not (yield from super().close()): return False adapters = self._ethernet_adapters + self._serial_adapters for adapter in adapters: if adapter is not None: for nio in adapter.ports.va...
Closes this IOU VM.
def waitPuppetCatalogToBeApplied(self, key, sleepTime=5): """ Function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied @param key: The host name or ID @return RETURN: None """ # Wait for puppet catalog to be applied loop_stop = False wh...
Function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied @param key: The host name or ID @return RETURN: None
def get_resource(request): """Retrieve a file's data.""" hash = request.matchdict['hash'] # Do the file lookup with db_connect() as db_connection: with db_connection.cursor() as cursor: args = dict(hash=hash) cursor.execute(SQL['get-resource'], args) try: ...
Retrieve a file's data.
def watched_file_handler(name, logname, filename, mode='a', encoding=None, delay=False): """ A Bark logging handler logging output to a named file. If the file has changed since the last log message was written, it will be closed and reopened. Similar to logging.handlers.W...
A Bark logging handler logging output to a named file. If the file has changed since the last log message was written, it will be closed and reopened. Similar to logging.handlers.WatchedFileHandler.
def unregister(self, cleanup_mode): """Unregisters a machine previously registered with :py:func:`IVirtualBox.register_machine` and optionally do additional cleanup before the machine is unregistered. This method does not delete any files. It only changes the machine configurat...
Unregisters a machine previously registered with :py:func:`IVirtualBox.register_machine` and optionally do additional cleanup before the machine is unregistered. This method does not delete any files. It only changes the machine configuration and the list of registered machines...
def errcat(self): ''' List the posts to be modified. ''' post_recs = MPost.query_random(limit=1000) outrecs = [] errrecs = [] idx = 0 for postinfo in post_recs: if idx > 16: break cat = MPost2Catalog.get_first_catego...
List the posts to be modified.
def draw_variable(loc, scale, shape, skewness, nsims): """ Draws random variables from this distribution Parameters ---------- loc : float location parameter for the distribution scale : float scale parameter for the distribution shape : float ...
Draws random variables from this distribution Parameters ---------- loc : float location parameter for the distribution scale : float scale parameter for the distribution shape : float tail thickness parameter for the distribution s...
def object_patch_rm_link(self, root, link, **kwargs): """Creates a new merkledag object based on an existing one. The new object will lack a link to the specified object. .. code-block:: python >>> c.object_patch_rm_link( ... 'QmNtXbF3AjAk59gQKRgEdVabHcSsiPUnJwHnZK...
Creates a new merkledag object based on an existing one. The new object will lack a link to the specified object. .. code-block:: python >>> c.object_patch_rm_link( ... 'QmNtXbF3AjAk59gQKRgEdVabHcSsiPUnJwHnZKyj2x8Z3k', ... 'Johnny' ... ) ...
def twilight(self, direction=SUN_RISING, date=None, local=True, use_elevation=True): """Returns the start and end times of Twilight in the UTC timezone when the sun is traversing in the specified direction. This method defines twilight as being between the time when the sun is at -6 deg...
Returns the start and end times of Twilight in the UTC timezone when the sun is traversing in the specified direction. This method defines twilight as being between the time when the sun is at -6 degrees and sunrise/sunset. :param direction: Determines whether the time is for the sun ...
def hash_sha256(self): """Calculate sha256 fingerprint.""" fp_plain = hashlib.sha256(self._decoded_key).digest() return (b"SHA256:" + base64.b64encode(fp_plain).replace(b"=", b"")).decode("utf-8")
Calculate sha256 fingerprint.
def dumps(*args, **kwargs): """ Wrapper for json.dumps that uses the JSONArgonautsEncoder. """ import json from django.conf import settings from argonauts.serializers import JSONArgonautsEncoder kwargs.setdefault('cls', JSONArgonautsEncoder) # pretty print in DEBUG mode. if setting...
Wrapper for json.dumps that uses the JSONArgonautsEncoder.
def _highlightBracket(self, bracket, qpart, block, columnIndex): """Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's """ try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _Time...
Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's
def exclude_from(l, containing = [], equal_to = []): """Exclude elements in list l containing any elements from list ex. Example: >>> l = ['bob', 'r', 'rob\r', '\r\nrobert'] >>> containing = ['\n', '\r'] >>> equal_to = ['r'] >>> exclude_from(l, containing, equal_to) ['bob...
Exclude elements in list l containing any elements from list ex. Example: >>> l = ['bob', 'r', 'rob\r', '\r\nrobert'] >>> containing = ['\n', '\r'] >>> equal_to = ['r'] >>> exclude_from(l, containing, equal_to) ['bob']
def do_gate(self, gate: Gate): """ Perform a gate. :return: ``self`` to support method chaining. """ gate_matrix, qubit_inds = _get_gate_tensor_and_qubits(gate=gate) # Note to developers: you can use either einsum- or tensordot- based functions. # tensordot seems...
Perform a gate. :return: ``self`` to support method chaining.
def parent_org_sdo_ids(self): '''The SDO IDs of the compositions this RTC belongs to.''' return [sdo.get_owner()._narrow(SDOPackage.SDO).get_sdo_id() \ for sdo in self._obj.get_organizations() if sdo]
The SDO IDs of the compositions this RTC belongs to.
def star(self): """ Stars the project .. deprecated:: 0.8.5 Update Taiga and use like instead """ warnings.warn( "Deprecated! Update Taiga and use .like() instead", DeprecationWarning ) self.requester.post( '/{endp...
Stars the project .. deprecated:: 0.8.5 Update Taiga and use like instead
def _post_read_flds(flds, header): """Process flds to handle sphericity.""" if flds.shape[0] >= 3 and header['rcmb'] > 0: # spherical vector header['p_mesh'] = np.roll( np.arctan2(header['y_mesh'], header['x_mesh']), -1, 1) for ibk in range(header['ntb']): flds[.....
Process flds to handle sphericity.
def shutdown(self): """ Shuts down this HazelcastClient. """ if self.lifecycle.is_live: self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTTING_DOWN) self.near_cache_manager.destroy_all_near_caches() self.statistics.shutdown() self.par...
Shuts down this HazelcastClient.
def wrap_args_with_process_isolation(self, args): ''' Wrap existing command line with bwrap to restrict access to: - self.process_isolation_path (generally, /tmp) (except for own /tmp files) ''' cwd = os.path.realpath(self.cwd) pi_temp_dir = self.build_process_isolation_...
Wrap existing command line with bwrap to restrict access to: - self.process_isolation_path (generally, /tmp) (except for own /tmp files)
def generate(self, src=None, identifier=None): """Generate static files for one source image.""" self.src = src self.identifier = identifier # Get image details and calculate tiles im = self.manipulator_klass() im.srcfile = self.src im.set_max_image_pixels(self.ma...
Generate static files for one source image.
def add_tokens_for_group(self, with_pass=False): """Add the tokens for the group signature""" kls = self.groups.super_kls name = self.groups.kls_name # Reset indentation to beginning and add signature self.reset_indentation('') self.result.extend(self.tokens.make_describ...
Add the tokens for the group signature
async def get_entity(self): """ Returns `entity` but will make an API call if necessary. """ if not self.entity and await self.get_input_entity(): try: self._entity =\ await self._client.get_entity(self._input_entity) except Val...
Returns `entity` but will make an API call if necessary.
def save(self, *args, **kwargs): """Save animation into a movie file. [NOTE] If 'writer' is not specified, default writer defined in this module will be used to generate the movie file. [TODO] Implement docstring inheritance. """ writer = None if 'write...
Save animation into a movie file. [NOTE] If 'writer' is not specified, default writer defined in this module will be used to generate the movie file. [TODO] Implement docstring inheritance.
def Draw(self, *args, **kwargs): """ Loop over subfiles, draw each, and sum the output into a single histogram. """ self.reset() output = None while self._rollover(): if output is None: # Make our own copy of the drawn histogram ...
Loop over subfiles, draw each, and sum the output into a single histogram.
def _map_tril_1d_on_2d(indices, dims): """Map 1d indices on lower triangular matrix in 2d. """ N = (dims * dims - dims) / 2 m = np.ceil(np.sqrt(2 * N)) c = m - np.round(np.sqrt(2 * (N - indices))) - 1 r = np.mod(indices + (c + 1) * (c + 2) / 2 - 1, m) + 1 return np.array([r, c], dtype=np.int6...
Map 1d indices on lower triangular matrix in 2d.
def _set_ghost_ios(self, vm): """ Manages Ghost IOS support. :param vm: VM instance """ if not vm.mmap: raise DynamipsError("mmap support is required to enable ghost IOS support") if vm.platform == "c7200" and vm.npe == "npe-g2": log.warning("Gh...
Manages Ghost IOS support. :param vm: VM instance
def request_verification(self, user, identity): """ Sends the user a verification email with a link to verify ownership of the email address. :param user: User id or object :param identity: Identity id or object :return: requests Response object """ return UserId...
Sends the user a verification email with a link to verify ownership of the email address. :param user: User id or object :param identity: Identity id or object :return: requests Response object
def get_item(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None): """GetItem. Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a ...
GetItem. Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download. :param str path: Version control path...
def _update_geography(self, countries, regions, cities, city_country_mapping): """ Update database with new countries, regions and cities """ existing = { 'cities': list(City.objects.values_list('id', flat=True)), 'regions': list(Region.objects.values('name', 'country__code')), ...
Update database with new countries, regions and cities
def thorium(opts, functions, runners): ''' Load the thorium runtime modules ''' pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = r...
Load the thorium runtime modules
def accept(self): # type: () -> str """The content-type for the response to the client. Returns: (str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT environment variable. """ accept = self.headers.get('Accept...
The content-type for the response to the client. Returns: (str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT environment variable.
def sample_indexes(segyfile, t0=0.0, dt_override=None): """ Creates a list of values representing the samples in a trace at depth or time. The list starts at *t0* and is incremented with am*dt* for the number of samples. If a *dt_override* is not provided it will try to find a *dt* in the file. Pa...
Creates a list of values representing the samples in a trace at depth or time. The list starts at *t0* and is incremented with am*dt* for the number of samples. If a *dt_override* is not provided it will try to find a *dt* in the file. Parameters ---------- segyfile : segyio.SegyFile t0 : flo...
def distributive(self): """ Return a term where the leading AND or OR terms are switched. This is done by applying the distributive laws: A & (B|C) = (A&B) | (A&C) A | (B&C) = (A|B) & (A|C) """ dual = self.dual args = list(self.args) for i...
Return a term where the leading AND or OR terms are switched. This is done by applying the distributive laws: A & (B|C) = (A&B) | (A&C) A | (B&C) = (A|B) & (A|C)
def get_location(self, location_id: int, timeout: int=None): """Get a location information Parameters ---------- location_id: int A location ID See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable locatio...
Get a location information Parameters ---------- location_id: int A location ID See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json for a list of acceptable location IDs timeout: Optional[int] = None Custom timeout t...
def exec_command( client, container, command, interactive=True, stdout=None, stderr=None, stdin=None): """ Run provided command via exec API in provided container. This is just a wrapper for PseudoTerminal(client, container).exec_command() """ exec_id = exec_create(client, container, comman...
Run provided command via exec API in provided container. This is just a wrapper for PseudoTerminal(client, container).exec_command()
def inis2dict(ini_paths: Union[str, Sequence[str]]) -> dict: """ Take one or more ini files and return a dict with configuration from all, interpolating bash-style variables ${VAR} or ${VAR:-DEFAULT}. :param ini_paths: path or paths to .ini files """ var_dflt = r'\${(.*?):-(.*?)}' def _int...
Take one or more ini files and return a dict with configuration from all, interpolating bash-style variables ${VAR} or ${VAR:-DEFAULT}. :param ini_paths: path or paths to .ini files
def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, ...
Finds the width of the terminal, or returns a suitable default value.
def authenticate(self, email=None, password=None): """ Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns -...
Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns ------- boolean True if the user authenticated or ra...
def input_from_history(a, n, bias=False): """ This is function for creation of input matrix. **Args:** * `a` : series (1 dimensional array) * `n` : size of input matrix row (int). It means how many samples \ of previous history you want to use \ as the filter input. It also repres...
This is function for creation of input matrix. **Args:** * `a` : series (1 dimensional array) * `n` : size of input matrix row (int). It means how many samples \ of previous history you want to use \ as the filter input. It also represents the filter length. **Kwargs:** * `bias`...
def template_scheduler_yaml(cl_args, masters): ''' Template scheduler.yaml ''' single_master = masters[0] scheduler_config_actual = "%s/standalone/scheduler.yaml" % cl_args["config_path"] scheduler_config_template = "%s/standalone/templates/scheduler.template.yaml" \ % cl_args...
Template scheduler.yaml
def _addConfig(instance, config, parent_section): """ Writes a section for a plugin. Args: instance (object): Class instance for plugin config (object): Object (ConfigParser) which the current config parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports' """ try: section...
Writes a section for a plugin. Args: instance (object): Class instance for plugin config (object): Object (ConfigParser) which the current config parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'
def process_line(self, idx, line): """处理每行""" if '///' in line: # 注释 py_line = '#' + line[3:] # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==> # /// <summary> # /// 投资者范围类型 # /// </summary>""" if py_line.find('是一个') >...
处理每行
def _cast_field(self, cast_to, value): """ Convert field type from raw bytes to native python type :param cast_to: native python type to cast to :type cast_to: a type object (one of bytes, int, unicode (str for py3k)) :param value: raw value from the database :type value...
Convert field type from raw bytes to native python type :param cast_to: native python type to cast to :type cast_to: a type object (one of bytes, int, unicode (str for py3k)) :param value: raw value from the database :type value: bytes :return: converted value :rtype: v...
def _periodically_flush_profile_events(self): """Drivers run this as a thread to flush profile data in the background.""" # Note(rkn): This is run on a background thread in the driver. It uses # the raylet client. This should be ok because it doesn't read # from the raylet client...
Drivers run this as a thread to flush profile data in the background.
def _add_months(p_sourcedate, p_months): """ Adds a number of months to the source date. Takes into account shorter months and leap years and such. https://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python """ month = p_sourcedate.month - 1 + p_months year = p_s...
Adds a number of months to the source date. Takes into account shorter months and leap years and such. https://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python