code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def tree_multiresolution(G, Nlevel, reduction_method='resistance_distance', compute_full_eigen=False, root=None): r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the...
r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default = 1) reduction_method : str The graph reduction method (de...
def _convert_or_shorten_month(cls, data): """ Convert a given month into our unified format. :param data: The month to convert or shorten. :type data: str :return: The unified month name. :rtype: str """ # We map the different month and their possible r...
Convert a given month into our unified format. :param data: The month to convert or shorten. :type data: str :return: The unified month name. :rtype: str
def rect(self): """rect(self) -> PyObject *""" CheckParent(self) val = _fitz.Link_rect(self) val = Rect(val) return val
rect(self) -> PyObject *
def gausspars(fwhm, nsigma=1.5, ratio=1, theta=0.): """ height - the amplitude of the gaussian x0, y0, - center of the gaussian fwhm - full width at half maximum of the observation nsigma - cut the gaussian at nsigma ratio = ratio of xsigma/ysigma theta - angle of pos...
height - the amplitude of the gaussian x0, y0, - center of the gaussian fwhm - full width at half maximum of the observation nsigma - cut the gaussian at nsigma ratio = ratio of xsigma/ysigma theta - angle of position angle of the major axis measured counter-clockwise fro...
def add_to_emails(self, *emails): """ :calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_ :param email: string :rtype: None """ assert all(isinstance(element, (str, unicode)) for element in emails), emails post_parameters = emails he...
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_ :param email: string :rtype: None
def list_datasets(self, get_global_public): """ Lists datasets in resources. Setting 'get_global_public' to 'True' will retrieve all public datasets in cloud. 'False' will get user's public datasets. Arguments: get_global_public (bool): True if user wants all public ...
Lists datasets in resources. Setting 'get_global_public' to 'True' will retrieve all public datasets in cloud. 'False' will get user's public datasets. Arguments: get_global_public (bool): True if user wants all public datasets in cloud. False i...
def run(cl_args, compo_type): """ run command """ cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ'] topology = cl_args['topology-name'] spouts_only, bolts_only = cl_args['spout'], cl_args['bolt'] try: components = tracker_access.get_logical_plan(cluster, env, topology, role) ...
run command
def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None, calendar_view=None, page_size=None, max_items=None, offset=0): """ Private method to call the FindItem service :param q: a Q instance containing any restrictions :param sh...
Private method to call the FindItem service :param q: a Q instance containing any restrictions :param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is non-null, we always return Item objects. :param depth: controls the whether to r...
def _to_operator(rep, data, input_dim, output_dim): """Transform a QuantumChannel to the Operator representation.""" if rep == 'Operator': return data if rep == 'Stinespring': return _stinespring_to_operator(data, input_dim, output_dim) # Convert via Kraus representation if rep != 'K...
Transform a QuantumChannel to the Operator representation.
def get_redirect_url(self, **kwargs): """ Return the authorization/authentication URL signed with the request token. """ params = { 'oauth_token': self.get_request_token().key, } return '%s?%s' % (self.auth_url, urllib.urlencode(params))
Return the authorization/authentication URL signed with the request token.
def get_ref_free_exc_info(): "Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory" type, val, tb = sys.exc_info() traceback.clear_frames(tb) return (type, val, tb)
Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory
def read(filename,**kwargs): """ Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array """ base,ext = os.path.splitext(fi...
Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array
def update_editor ( self ): """ Updates the editor when the object trait changes externally to the editor. """ object = self.value # Graph the new object... canvas = self.factory.canvas if canvas is not None: for nodes_name in canvas.node_children:...
Updates the editor when the object trait changes externally to the editor.
def __solve_overlaps(self, start_time, end_time): """finds facts that happen in given interval and shifts them to make room for new fact """ if end_time is None or start_time is None: return # possible combinations and the OR clauses that catch them # (the si...
finds facts that happen in given interval and shifts them to make room for new fact
def _involuted_reverse(self): """ This method reverses the StridedInterval object for real. Do expect loss of precision for most cases! :return: A new reversed StridedInterval instance """ def inv_is_top(si): return (si.stride == 1 and self._lower_bou...
This method reverses the StridedInterval object for real. Do expect loss of precision for most cases! :return: A new reversed StridedInterval instance
def get_link_page_text(link_page): """ Construct the dialog box to display a list of links to the user. """ text = '' for i, link in enumerate(link_page): capped_link_text = (link['text'] if len(link['text']) <= 20 else link['text'][:19...
Construct the dialog box to display a list of links to the user.
def delete(self): """ Deletes the object. Returns without doing anything if the object is new. """ if not self.id: return if not self._loaded: self.reload() return self.http_delete(self.id, etag=self.etag)
Deletes the object. Returns without doing anything if the object is new.
def pretty_format(message): """ Convert a message dictionary into a human-readable string. @param message: Message to parse, as dictionary. @return: Unicode string. """ skip = { TIMESTAMP_FIELD, TASK_UUID_FIELD, TASK_LEVEL_FIELD, MESSAGE_TYPE_FIELD, ACTION_TYPE_FIELD, ACTION_ST...
Convert a message dictionary into a human-readable string. @param message: Message to parse, as dictionary. @return: Unicode string.
def delitem_via_sibseqs(ol,*sibseqs): ''' from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] delitem_via_sibseqs(y,1,1) y ''' pathlist = list(sibseqs) this = ol for i in range(0,pathlist.__len__()-1): key = pathlist[i] this = this.__g...
from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] delitem_via_sibseqs(y,1,1) y
def set_task_object(self, task_id, task_progress_object): """ Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing...
Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing. :param task_progress_object: TaskProgress object holding the progress bar information.
def flush(self): """ Sends buffered data to the target """ # Flush buffer content = self._buffer.getvalue() self._buffer = StringIO() if content: # Send message self._client.send_message(self._target, content, mtype="chat")
Sends buffered data to the target
def TEST(): """ Modules for testing happiness of 'persons' in 'worlds' based on simplistic preferences. Just a toy - dont take seriously ----- WORLD SUMMARY for : Mars ----- population = 0 tax_rate = 0.0 tradition = 0.9 equity = 0.0 Preferences for Rov...
Modules for testing happiness of 'persons' in 'worlds' based on simplistic preferences. Just a toy - dont take seriously ----- WORLD SUMMARY for : Mars ----- population = 0 tax_rate = 0.0 tradition = 0.9 equity = 0.0 Preferences for Rover tax_min = 0....
def base26(x, _alphabet=string.ascii_uppercase): """Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 2...
Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0 'SPAM' >>> base26(256) 'IV'
def get_consensus_hashes(block_heights, hostport=None, proxy=None): """ Get consensus hashes for a list of blocks NOTE: returns {block_height (int): consensus_hash (str)} (coerces the key to an int) Returns {'error': ...} on error """ assert proxy or hostport, 'Need proxy or hostport' if...
Get consensus hashes for a list of blocks NOTE: returns {block_height (int): consensus_hash (str)} (coerces the key to an int) Returns {'error': ...} on error
def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort...
Add `dist` if we ``can_add()`` it and it has not already been added
def _CollectTypeChecks(function, parent_type_check_dict, stack_location, self_name): """Collect all type checks for this function.""" type_check_dict = dict(parent_type_check_dict) type_check_dict.update(_ParseDocstring(function)) # Convert any potential string based checks into python in...
Collect all type checks for this function.
def add_unique_template_variables(self, options): """Update map template variables specific to graduated circle visual""" options.update(dict( colorProperty=self.color_property, colorStops=self.color_stops, colorType=self.color_function_type, radiusType=se...
Update map template variables specific to graduated circle visual
def answers(self, other): """DEV: true if self is an answer from other""" if other.__class__ == self.__class__: return (other.service + 0x40) == self.service or \ (self.service == 0x7f and self.request_service_id == other.service) return False
DEV: true if self is an answer from other
def init_module(self, run_object): """Initializes profiler with a module.""" self.profile = self.profile_module self._run_object, _, self._run_args = run_object.partition(' ') self._object_name = '%s (module)' % self._run_object self._globs = { '__file__': self._run_o...
Initializes profiler with a module.
def convert_types(cls, value): """ Takes a value from MSSQL, and converts it to a value that's safe for JSON/Google Cloud Storage/BigQuery. """ if isinstance(value, decimal.Decimal): return float(value) else: return value
Takes a value from MSSQL, and converts it to a value that's safe for JSON/Google Cloud Storage/BigQuery.
def query(querystr, connection=None, **connectkwargs): """Execute a query of the given SQL database """ if connection is None: connection = connect(**connectkwargs) cursor = connection.cursor() cursor.execute(querystr) return cursor.fetchall()
Execute a query of the given SQL database
def _preprocess_values(self, Y): """ Check if the values of the observations correspond to the values assumed by the likelihood function. ..Note:: Binary classification algorithm works better with classes {-1, 1} """ Y_prep = Y.copy() Y1 = Y[Y.flatten()==1].size ...
Check if the values of the observations correspond to the values assumed by the likelihood function. ..Note:: Binary classification algorithm works better with classes {-1, 1}
def segments(self): """List of :class:`ChatMessageSegment` in message (:class:`list`).""" seg_list = self._event.chat_message.message_content.segment return [ChatMessageSegment.deserialize(seg) for seg in seg_list]
List of :class:`ChatMessageSegment` in message (:class:`list`).
def get_safe_return_to(request, return_to): """ Ensure the user-originating redirection url is safe, i.e. within same scheme://domain:port """ if return_to and is_safe_url(url=return_to, host=request.get_host()) and return_to != request.build_absolute_uri(): return return_to
Ensure the user-originating redirection url is safe, i.e. within same scheme://domain:port
def reduce(fname, reduction_factor): """ Produce a submodel from `fname` by sampling the nodes randomly. Supports source models, site models and exposure models. As a special case, it is also able to reduce .csv files by sampling the lines. This is a debugging utility to reduce large computations to...
Produce a submodel from `fname` by sampling the nodes randomly. Supports source models, site models and exposure models. As a special case, it is also able to reduce .csv files by sampling the lines. This is a debugging utility to reduce large computations to small ones.
def encode_sequence(content, error=None, version=None, mode=None, mask=None, encoding=None, eci=False, boost_error=True, symbol_count=None): """\ EXPERIMENTAL: Creates a sequence of QR Codes in Structured Append mode. :return: Iterable of named tuples, see :py:func:`...
\ EXPERIMENTAL: Creates a sequence of QR Codes in Structured Append mode. :return: Iterable of named tuples, see :py:func:`encode` for details.
def _do_api_call(self, method, data): """ Convenience method to carry out a standard API call against the Petfinder API. :param basestring method: The API method name to call. :param dict data: Key/value parameters to send to the API method. This varies based on the ...
Convenience method to carry out a standard API call against the Petfinder API. :param basestring method: The API method name to call. :param dict data: Key/value parameters to send to the API method. This varies based on the method. :raises: A number of :py:exc:`petfinder.ex...
def patch(module, external=(), internal=()): """ Temporarily monkey-patch dependencies which can be external to, or internal to the supplied module. :param module: Module object :param external: External dependencies to patch (full paths as strings) :param internal: Internal dependencies to pat...
Temporarily monkey-patch dependencies which can be external to, or internal to the supplied module. :param module: Module object :param external: External dependencies to patch (full paths as strings) :param internal: Internal dependencies to patch (short names as strings) :return:
def activate_left(self, token): """Make a copy of the received token and call `_activate_left`.""" watchers.MATCHER.debug( "Node <%s> activated left with token %r", self, token) return self._activate_left(token.copy())
Make a copy of the received token and call `_activate_left`.
def str_rfind(x, sub, start=0, end=None): """Returns the highest indices in each string in a column, where the provided substring is fully contained between within a sample. If the substring is not found, -1 is returned. :param str sub: A substring to be found in the samples :param int start: :para...
Returns the highest indices in each string in a column, where the provided substring is fully contained between within a sample. If the substring is not found, -1 is returned. :param str sub: A substring to be found in the samples :param int start: :param int end: :returns: an expression containing...
def _generate_splits(self, m, r): """ When a rectangle is placed inside a maximal rectangle, it stops being one and up to 4 new maximal rectangles may appear depending on the placement. _generate_splits calculates them. Arguments: m (Rectangle): max_rect rectangle ...
When a rectangle is placed inside a maximal rectangle, it stops being one and up to 4 new maximal rectangles may appear depending on the placement. _generate_splits calculates them. Arguments: m (Rectangle): max_rect rectangle r (Rectangle): rectangle placed Ret...
def get_page_labels(self, page_id, prefix=None, start=None, limit=None): """ Returns the list of labels on a piece of Content. :param page_id: A string containing the id of the labels content container. :param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}. ...
Returns the list of labels on a piece of Content. :param page_id: A string containing the id of the labels content container. :param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}. Default: None. :param start: OPTIONAL: The start poin...
def extractHolidayWeekendSchedules(self): """ extract holiday and weekend :class:`~ekmmeters.Schedule` from meter object buffer. Returns: tuple: Holiday and weekend :class:`~ekmmeters.Schedule` values, as strings. ======= ====================================== Holid...
extract holiday and weekend :class:`~ekmmeters.Schedule` from meter object buffer. Returns: tuple: Holiday and weekend :class:`~ekmmeters.Schedule` values, as strings. ======= ====================================== Holiday :class:`~ekmmeters.Schedule` as string ...
def expose_ancestors_or_children(self, member, collection, lang=None): """ Build an ancestor or descendant dict view based on selected information :param member: Current Member to build for :param collection: Collection from which we retrieved it :param lang: Language to express data in...
Build an ancestor or descendant dict view based on selected information :param member: Current Member to build for :param collection: Collection from which we retrieved it :param lang: Language to express data in :return:
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): """ Create a service from an endpoint if it does not already exists. """ from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: # check if endpoint is...
Create a service from an endpoint if it does not already exists.
def getKeyword(filename, keyword, default=None, handle=None): """ General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string. """ # Insure that there is at least 1 extension specified... if filename.find('[') < 0: ...
General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string.
def generate_join_docs_list(self, left_collection_list, right_collection_list): """ Helper function for merge_join_docs :param left_collection_list: Left Collection to be joined :type left_collection_list: MongoCollection :param right_collection_list: Right Coll...
Helper function for merge_join_docs :param left_collection_list: Left Collection to be joined :type left_collection_list: MongoCollection :param right_collection_list: Right Collection to be joined :type right_collection_list: MongoCollection :return joine...
def _nextSequence(cls, name=None): """Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full se...
Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _nextSe...
def get_project(self) -> str: """ Get the ihc project and make sure controller is ready before""" with IHCController._mutex: if self._project is None: if self.client.get_state() != IHCSTATE_READY: ready = self.client.wait_for_state_change(IHCSTATE_READY, ...
Get the ihc project and make sure controller is ready before
def new(cls, nsptagname, val): """ Return a new ``CT_String`` element with tagname *nsptagname* and ``val`` attribute set to *val*. """ elm = OxmlElement(nsptagname) elm.val = val return elm
Return a new ``CT_String`` element with tagname *nsptagname* and ``val`` attribute set to *val*.
def send(self, smtp=None, **kw): """ Sends message. :param smtp: When set, parameters from this dictionary overwrite options from config. See `emails.Message.send` for more information. :param kwargs: Parameters for `emails.Message.send` :return: Response ...
Sends message. :param smtp: When set, parameters from this dictionary overwrite options from config. See `emails.Message.send` for more information. :param kwargs: Parameters for `emails.Message.send` :return: Response objects from emails backend. For def...
def switch_delete_record_for_userid(self, userid): """Remove userid switch record from switch table.""" with get_network_conn() as conn: conn.execute("DELETE FROM switch WHERE userid=?", (userid,)) LOG.debug("Switch record for user %s is removed from " ...
Remove userid switch record from switch table.
def repack(self, to_width, *, msb_first, start=0, start_bit=0, length=None): """Extracts a part of a BinArray's data and converts it to a BinArray of a different width. For the purposes of this conversion, words in this BinArray are joined side-by-side, starting from a gi...
Extracts a part of a BinArray's data and converts it to a BinArray of a different width. For the purposes of this conversion, words in this BinArray are joined side-by-side, starting from a given start index (defaulting to 0), skipping ``start_bit`` first bits of the first word, then th...
def _escape(self, msg): """ Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string. """ escaped = '' for c in msg: escaped += c if c ...
Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string.
def timezone(self, tz): """ Set timezone on the audit records. Timezone can be in formats: 'US/Eastern', 'PST', 'Europe/Helsinki' See SMC Log Viewer settings for more examples. :param str tz: timezone, i.e. CST """ self.data['resolving'].update( ...
Set timezone on the audit records. Timezone can be in formats: 'US/Eastern', 'PST', 'Europe/Helsinki' See SMC Log Viewer settings for more examples. :param str tz: timezone, i.e. CST
def send(self, to, from_, body, dm=False): """ Send BODY as an @message from FROM to TO If we don't have the access tokens for FROM, raise AccountNotFoundError. If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars raise TweetTooLongError. If we want to...
Send BODY as an @message from FROM to TO If we don't have the access tokens for FROM, raise AccountNotFoundError. If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars raise TweetTooLongError. If we want to send this message as a DM, do so. Arguments: ...
def domain_block(self, domain=None): """ Add a block for all statuses originating from the specified domain for the logged-in user. """ params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/domain_blocks', params)
Add a block for all statuses originating from the specified domain for the logged-in user.
def validate_text(value): """Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError""" possible_transform = ['axes', 'fig', 'data'] validate_transform = ValidateInStrings('transform', possible_transform, ...
Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError
def interpolate_gridded_scalar(self, x, y, c, order=1, pad=1, offset=0): """Interpolate gridded scalar C to points x,y. Parameters ---------- x, y : array-like Points at which to interpolate c : array-like The scalar, assumed to be defined on the ...
Interpolate gridded scalar C to points x,y. Parameters ---------- x, y : array-like Points at which to interpolate c : array-like The scalar, assumed to be defined on the grid. order : int Order of interpolation pad : int ...
def add_auth_attribute(attr, value, actor=False): """ Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute i...
Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute is an actor (user or client app accessing own data) ...
def compliance_report(self, validation_file=None, validation_source=None): """ Return a compliance report. Verify that the device complies with the given validation file and writes a compliance report file. See https://napalm.readthedocs.io/en/latest/validate/index.html. :param...
Return a compliance report. Verify that the device complies with the given validation file and writes a compliance report file. See https://napalm.readthedocs.io/en/latest/validate/index.html. :param validation_file: Path to the file containing compliance definition. Default is None. :...
def mouseMoveEvent(self, e): """ Extends mouseMoveEvent to display a pointing hand cursor when the mouse cursor is over a file location """ super(PyInteractiveConsole, self).mouseMoveEvent(e) cursor = self.cursorForPosition(e.pos()) assert isinstance(cursor, QtGui...
Extends mouseMoveEvent to display a pointing hand cursor when the mouse cursor is over a file location
def apply(self, coordinates): """Generate, apply and return a random manipulation""" transform = self.get_transformation(coordinates) result = MolecularDistortion(self.affected_atoms, transform) result.apply(coordinates) return result
Generate, apply and return a random manipulation
def set_monitor(module): """ Defines the monitor method on the module. """ def monitor(name, tensor, track_data=True, track_grad=True): """ Register the tensor under the name given (now a string) and track it based on the track_data and track_grad argument...
Defines the monitor method on the module.
def cmsearch_from_file(cm_file_path, seqs, moltype, cutoff=0.0, params=None): """Uses cmbuild to build a CM file, then cmsearch to find homologs. - cm_file_path: path to the file created by cmbuild, containing aligned sequences. This will be used to search sequences in seqs. - seqs: Seq...
Uses cmbuild to build a CM file, then cmsearch to find homologs. - cm_file_path: path to the file created by cmbuild, containing aligned sequences. This will be used to search sequences in seqs. - seqs: SequenceCollection object or something that can be used to construct one, co...
def wipe_container(self): """ Completely wipes out the contents of the container. """ if self.test_run: print("Wipe would delete {0} objects.".format(len(self.container.object_count))) else: if not self.quiet or self.verbosity > 1: print("D...
Completely wipes out the contents of the container.
def updateMktDepthL2(self, id, position, marketMaker, operation, side, price, size): """updateMktDepthL2(EWrapper self, TickerId id, int position, IBString marketMaker, int operation, int side, double price, int size)""" return _swigibpy.EWrapper_updateMktDepthL2(self, id, position, marketMaker, operati...
updateMktDepthL2(EWrapper self, TickerId id, int position, IBString marketMaker, int operation, int side, double price, int size)
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." User = orm[user_orm_label] try: user = User.objects.all()[0] for article in orm.Article.objects.all(): ...
Write your forwards methods here.
def set_limit(self, param): """ Models "Limit Command" functionality of device. Sets the target temperate to be reached. :param param: Target temperature in C, multiplied by 10, as a string. Can be negative. :return: Empty string. """ # TODO: Is not having leadi...
Models "Limit Command" functionality of device. Sets the target temperate to be reached. :param param: Target temperature in C, multiplied by 10, as a string. Can be negative. :return: Empty string.
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): """Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetim...
Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetime.datetime end: The datetime which the stepdown window is to close. :param bool enabled: ...
def add_store(name, store, saltenv='base'): ''' Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local...
Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local path is specified
def add_format(self, mimetype, format, requires_context=False): """ Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware gr...
Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw): """ Get a connection from the pool and perform...
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such ...
def create_permissions_from_tuples(model, codename_tpls): """Creates custom permissions on model "model". """ if codename_tpls: model_cls = django_apps.get_model(model) content_type = ContentType.objects.get_for_model(model_cls) for codename_tpl in codename_tpls: app_labe...
Creates custom permissions on model "model".
def auth(self): """Send authorization secret to nsqd.""" self.send(nsq.auth(self.auth_secret)) frame, data = self.read_response() if frame == nsq.FRAME_TYPE_ERROR: raise data try: response = json.loads(data.decode('utf-8')) except ValueError: ...
Send authorization secret to nsqd.
def __replace_adjective(sentence, counts): """Lets find and replace all instances of #ADJECTIVE :param _sentence: :param counts: """ if sentence is not None: while sentence.find('#ADJECTIVE') != -1: sentence = sentence.replace('#ADJECTIVE', ...
Lets find and replace all instances of #ADJECTIVE :param _sentence: :param counts:
def _maybe_trim_strings(self, array, **keys): """ if requested, trim trailing white space from all string fields in the input array """ trim_strings = keys.get('trim_strings', False) if self.trim_strings or trim_strings: _trim_strings(array)
if requested, trim trailing white space from all string fields in the input array
def update_next_block(self): """ If the last instruction of this block is a JP, JR or RET (with no conditions) then the next and goes_to sets just contains a single block """ last = self.mem[-1] if last.inst not in ('ret', 'jp', 'jr') or last.condition_flag is not None: ...
If the last instruction of this block is a JP, JR or RET (with no conditions) then the next and goes_to sets just contains a single block
async def fetchmany(self, size: int = None) -> Iterable[sqlite3.Row]: """Fetch up to `cursor.arraysize` number of rows.""" args = () # type: Tuple[int, ...] if size is not None: args = (size,) return await self._execute(self._cursor.fetchmany, *args)
Fetch up to `cursor.arraysize` number of rows.
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo...
Load sentiment dataset.
def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_t...
Returns the "natural" mask of an IPv4 address
def _record(self): # type: () -> bytes ''' An internal method to generate a string representing this El Torito Validation Entry. Parameters: None. Returns: String representing this El Torito Validation Entry. ''' return struct.pack(self....
An internal method to generate a string representing this El Torito Validation Entry. Parameters: None. Returns: String representing this El Torito Validation Entry.
def compare_tags(self, tags): ''' given a list of tags that the user has specified, return two lists: matched_tags: tags were found within the current play and match those given by the user unmatched_tags: tags that were found within the current play but do not match ...
given a list of tags that the user has specified, return two lists: matched_tags: tags were found within the current play and match those given by the user unmatched_tags: tags that were found within the current play but do not match any provided by the ...
def get_inline_instances(self, request, *args, **kwargs): """ Create the inlines for the admin, including the placeholder and contentitem inlines. """ inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] ...
Create the inlines for the admin, including the placeholder and contentitem inlines.
def _plot_colorbar(mappable, fig, subplot_spec, max_cbar_height=4): """ Plots a vertical color bar based on mappable. The height of the colorbar is min(figure-height, max_cmap_height) Parameters ---------- mappable : The image to which the colorbar applies. fig ; The figure object subpl...
Plots a vertical color bar based on mappable. The height of the colorbar is min(figure-height, max_cmap_height) Parameters ---------- mappable : The image to which the colorbar applies. fig ; The figure object subplot_spec : the gridspec subplot. Eg. axs[1,2] max_cbar_height : `float` ...
def add_transaction_clause(self, clause): """ Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: TransactionClause """ if not isinstance(clause, TransactionClause): raise StatementException('onl...
Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: TransactionClause
def create_parser() -> FileAwareParser: """ Create a command line parser :return: parser """ parser = FileAwareParser(description="Clear data from FHIR observation fact table", prog="removefacts", use_defaults=False) parser.add_argument("-ss", "--sourcesystem", metav...
Create a command line parser :return: parser
def write_extra_data(self, stream: WriteStream) -> None: """Writes the param container and string pointer arrays. Unlike other write_extra_data functions, this can be called before write().""" if self.params: stream.align(8) if self._params_offset_writer: ...
Writes the param container and string pointer arrays. Unlike other write_extra_data functions, this can be called before write().
def resolve_imports(self, imports, import_depth, parser=None): """Import required ontologies. """ if imports and import_depth: for i in list(self.imports): try: if os.path.exists(i) or i.startswith(('http', 'ftp')): self.me...
Import required ontologies.
def MGMT_ED_SCAN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod, xScanDuration): """send MGMT_ED_SCAN message to a given destinaition. Args: sAddr: IPv6 destination address for this message xCommissionerSessionId: commissioner session id listCh...
send MGMT_ED_SCAN message to a given destinaition. Args: sAddr: IPv6 destination address for this message xCommissionerSessionId: commissioner session id listChannelMask: a channel array to indicate which channels to be scaned xCount: number of IEEE 802.15.4 ED S...
def create_job(db, datadir): """ Create job for the given user, return it. :param db: a :class:`openquake.server.dbapi.Db` instance :param datadir: Data directory of the user who owns/started this job. :returns: the job ID """ calc_id = get_calc_id(db, datadir) + 1 ...
Create job for the given user, return it. :param db: a :class:`openquake.server.dbapi.Db` instance :param datadir: Data directory of the user who owns/started this job. :returns: the job ID
def devices(self): """Wait for new DS4 devices to appear.""" context = Context() existing_devices = context.list_devices(subsystem="hidraw") future_devices = self._get_future_devices(context) for hidraw_device in itertools.chain(existing_devices, future_devices): hi...
Wait for new DS4 devices to appear.
def cut_mechanisms(self): """The mechanisms of this system that are currently cut. Note that although ``cut_indices`` returns micro indices, this returns macro mechanisms. Yields: tuple[int] """ for mechanism in utils.powerset(self.node_indices, nonempty=Tru...
The mechanisms of this system that are currently cut. Note that although ``cut_indices`` returns micro indices, this returns macro mechanisms. Yields: tuple[int]
def resource_filename(package_or_requirement, resource_name): """ Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources it also looks in a predefined list of paths in order to find the resource :param package_or_requirement: the module in which the resource resid...
Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources it also looks in a predefined list of paths in order to find the resource :param package_or_requirement: the module in which the resource resides :param resource_name: the name of the resource :return: the pat...
def build_model(self): '''Find out the type of model configured and dispatch the request to the appropriate method''' if self.model_config['model-type']: return self.build_red() elif self.model_config['model-type']: return self.buidl_hred() else: raise...
Find out the type of model configured and dispatch the request to the appropriate method
def check_config(conf): '''Type and boundary check''' if 'fmode' in conf and not isinstance(conf['fmode'], string_types): raise TypeError(TAG + ": `fmode` must be a string") if 'dmode' in conf and not isinstance(conf['dmode'], string_types): raise TypeError(TAG + ": `dmode` must be a string...
Type and boundary check
def Authenticate(self, app_id, challenge, registered_keys): """Authenticates app_id with the security key. Executes the U2F authentication/signature flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key...
Authenticates app_id with the security key. Executes the U2F authentication/signature flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key as a bytes object. registered_keys: List of keys already reg...
def exists(self, uri): """Method returns true is the entity exists in the Repository, false, otherwise Args: uri(str): Entity URI Returns: bool """ ##entity_uri = "/".join([self.base_url, entity_id]) try: urllib.request.urlope...
Method returns true is the entity exists in the Repository, false, otherwise Args: uri(str): Entity URI Returns: bool
def get_parent_families(self, family_id): """Gets the parent families of the given ``id``. arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to query return: (osid.relationship.FamilyList) - the parent families of the ``id`` raise: NotFound - ...
Gets the parent families of the given ``id``. arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to query return: (osid.relationship.FamilyList) - the parent families of the ``id`` raise: NotFound - a ``Family`` identified by ``Id is`` not ...
def is_valid(edtf_candidate): """isValid takes a candidate date and returns if it is valid or not""" if ( isLevel0(edtf_candidate) or isLevel1(edtf_candidate) or isLevel2(edtf_candidate) ): if '/' in edtf_candidate: return is_valid_interval(edtf_candidate) ...
isValid takes a candidate date and returns if it is valid or not