code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def sasets(self) -> 'SASets': """ This methods creates a SASets object which you can use to run various analytics. See the sasets.py module. :return: sasets object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True ...
This methods creates a SASets object which you can use to run various analytics. See the sasets.py module. :return: sasets object
def configure_config(graph): """ Configure the health endpoint. :returns: the current service configuration """ ns = Namespace( subject=Config, ) convention = ConfigDiscoveryConvention( graph, ) convention.configure(ns, retrieve=tuple()) return convention.config...
Configure the health endpoint. :returns: the current service configuration
def check(text): """Suggest the preferred forms.""" err = "strunk_white.composition" msg = "Try '{}' instead of '{}'." bad_forms = [ # Put statements in positive form ["dishonest", ["not honest"]], ["trifling", ["not important"]], ["forgot", ...
Suggest the preferred forms.
def get(self, fields=[]): '''taobao.shopcats.list.get 获取前台展示的店铺类目 此API获取淘宝面向买家的浏览导航类目 跟后台卖家商品管理的类目有差异''' request = TOPRequest('taobao.shopcats.list.get') if not fields: shopCat = ShopCat() fields = shopCat.fields request['fields'] = fields ...
taobao.shopcats.list.get 获取前台展示的店铺类目 此API获取淘宝面向买家的浏览导航类目 跟后台卖家商品管理的类目有差异
def releases(self): """The releases for this app.""" return self._h._get_resources( resource=('apps', self.name, 'releases'), obj=Release, app=self )
The releases for this app.
def colors_no_palette(colors=None, **kwds): """Return a Palette but don't take into account Pallete Names.""" if isinstance(colors, str): colors = _split_colors(colors) else: colors = to_triplets(colors or ()) colors = (color(c) for c in colors or ()) return palette.Palette(colors, ...
Return a Palette but don't take into account Pallete Names.
def remove(self, ref, cb=None): """Check in a bundle to the remote""" if self.is_api: return self._remove_api(ref, cb) else: return self._remove_fs(ref, cb)
Check in a bundle to the remote
def threshold(self, value): """Threshold used to determine if your content qualifies as spam. On a scale from 1 to 10, with 10 being most strict, or most likely to be considered as spam. :param value: Threshold used to determine if your content qualifies as spam. ...
Threshold used to determine if your content qualifies as spam. On a scale from 1 to 10, with 10 being most strict, or most likely to be considered as spam. :param value: Threshold used to determine if your content qualifies as spam. On a scale from 1 ...
def eval_adiabatic_limit(YABFGN, Ytilde, P0): """Compute the limiting SLH model for the adiabatic approximation Args: YABFGN: The tuple (Y, A, B, F, G, N) as returned by prepare_adiabatic_limit. Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0. P0: The projector o...
Compute the limiting SLH model for the adiabatic approximation Args: YABFGN: The tuple (Y, A, B, F, G, N) as returned by prepare_adiabatic_limit. Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0. P0: The projector onto the null-space of Y. Returns: SLH: L...
def _setup_advanced_theme(self, theme_name, output_dir, advanced_name): """ Setup all the files required to enable an advanced theme. Copies all the files over and creates the required directories if they do not exist. :param theme_name: theme to copy the files over from ...
Setup all the files required to enable an advanced theme. Copies all the files over and creates the required directories if they do not exist. :param theme_name: theme to copy the files over from :param output_dir: output directory to place the files in
def read(self, size=sys.maxsize): """Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). """ blob_size = int(self.blob_properties.get('content-length')) if self._pointer < blob_size: chunk = self._download_chunk_with_retries(...
Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
def field_from_django_field(cls, field_name, django_field, readonly): """ Returns a Resource Field instance for the given Django model field. """ FieldWidget = cls.widget_from_django_field(django_field) widget_kwargs = cls.widget_kwargs_for_field(field_name) field = cls....
Returns a Resource Field instance for the given Django model field.
def close_session(self): """Close current session.""" if not self._session.closed: if self._session._connector_owner: self._session._connector.close() self._session._connector = None
Close current session.
def patch(self, id_or_uri, operation, path, value, timeout=-1, custom_headers=None): """ Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. operation: P...
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. operation: Patch operation path: Path value: Value timeout: Timeout in seconds. W...
def _update_partition_srvc_node_ip(self, tenant_name, srvc_ip, vrf_prof=None, part_name=None): """Function to update srvc_node address of partition. """ self.dcnm_obj.update_project(tenant_name, part_name, service_node_ip=srvc_i...
Function to update srvc_node address of partition.
def is_not_inf(self): """Asserts that val is real number and not Inf (infinity).""" self._validate_number() self._validate_real() if math.isinf(self.val): self._err('Expected not <Inf>, but was.') return self
Asserts that val is real number and not Inf (infinity).
def _run_cromwell(args): """Run CWL with Cromwell. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cromwell_work")) final_dir = utils.safe_makedir(os.path.join(work_dir, "final")) if args.no_container: _...
Run CWL with Cromwell.
def indent(text, n=4): """Indent each line of text by n spaces""" _indent = ' ' * n return '\n'.join(_indent + line for line in text.split('\n'))
Indent each line of text by n spaces
def add(self, event, subscriber, append=True): """ Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend th...
Add a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be added (and called when the event is published). :param append: Whether to append or prepend the subscriber to an existing subscriber list ...
def make_doc(self): """ Generate the doc for the current context in the form {'key': 'label'} """ res = {} for column in self.columns: if isinstance(column['__col__'], ColumnProperty): key = column['name'] label = column['__col_...
Generate the doc for the current context in the form {'key': 'label'}
def add_text(self, text, cursor=None, justification=None): """ Input text, short or long. Writes in order, within the defined page boundaries. Sequential add_text commands will print without additional whitespace. """ if cursor is None: cursor = self.page.cursor te...
Input text, short or long. Writes in order, within the defined page boundaries. Sequential add_text commands will print without additional whitespace.
def _get_config(): ''' Get user docker configuration Return: dict ''' cfg = os.path.expanduser('~/.dockercfg') try: fic = open(cfg) try: config = json.loads(fic.read()) finally: fic.close() except Exception: config = {'rootPath': '/dev...
Get user docker configuration Return: dict
def main_generate(table_names, stream): """This will print out valid prom python code for given tables that already exist in a database. This is really handy when you want to bootstrap an existing database to work with prom and don't want to manually create Orm objects for the tables you want to us...
This will print out valid prom python code for given tables that already exist in a database. This is really handy when you want to bootstrap an existing database to work with prom and don't want to manually create Orm objects for the tables you want to use, let `generate` do it for you
def getpath(self, section, option): """Return option as an expanded path.""" return os.path.expanduser(os.path.expandvars(self.get(section, option)))
Return option as an expanded path.
def _prepare_output(partitions, verbose): """Returns dict with 'raw' and 'message' keys filled.""" out = {} partitions_count = len(partitions) out['raw'] = { 'offline_count': partitions_count, } if partitions_count == 0: out['message'] = 'No offline partitions.' else: ...
Returns dict with 'raw' and 'message' keys filled.
def remove_description(self, id, **kwargs): # noqa: E501 """Remove description from a specific source # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_d...
Remove description from a specific source # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_description(id, async_req=True) >>> result = thread.get() ...
def up(self, migration_id=None, fake=False): """Executes migrations.""" if not self.check_directory(): return for migration in self.get_migrations_to_up(migration_id): logger.info('Executing migration: %s' % migration.filename) migration_module = self.load_m...
Executes migrations.
def increase_fcp_usage(self, fcp, assigner_id=None): """Incrase fcp usage of given fcp Returns True if it's a new fcp, otherwise return False """ # TODO: check assigner_id to make sure on the correct fcp record connections = self.db.get_connections_from_assigner(assigner_id) ...
Incrase fcp usage of given fcp Returns True if it's a new fcp, otherwise return False
def fingers_needed(fingering): """Return the number of fingers needed to play the given fingering.""" split = False # True if an open string must be played, thereby making any # subsequent strings impossible to bar with the index finger indexfinger = False # True if the index finger was al...
Return the number of fingers needed to play the given fingering.
def load_additional_data(self, valid_data, many, original_data): """Include unknown fields after load. Unknown fields are added with no processing at all. Args: valid_data (dict or list): validated data returned by ``load()``. many (bool): if True, data and original_dat...
Include unknown fields after load. Unknown fields are added with no processing at all. Args: valid_data (dict or list): validated data returned by ``load()``. many (bool): if True, data and original_data are a list. original_data (dict or list): data passed to ``loa...
def _salt_send_domain_event(opaque, conn, domain, event, event_data): ''' Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection ...
Helper function send a salt event for a libvirt domain. :param opaque: the opaque data that is passed to the callback. This is a dict with 'prefix', 'object' and 'event' keys. :param conn: libvirt connection :param domain: name of the domain related to the event :param event: name of...
def wait(self): ''' wait for the done event to be set - no timeout''' self._done_event.wait(MAXINT) return self._status, self._exception
wait for the done event to be set - no timeout
def controlled(self, control_qubit): """ Add the CONTROLLED modifier to the gate with the given control qubit. """ control_qubit = unpack_qubit(control_qubit) self.modifiers.insert(0, "CONTROLLED") self.qubits.insert(0, control_qubit) return self
Add the CONTROLLED modifier to the gate with the given control qubit.
def OnOpen(self, event): """File open event handler""" # If changes have taken place save of old grid if undo.stack().haschanged(): save_choice = self.interfaces.get_save_request_from_user() if save_choice is None: # Cancelled close operation ...
File open event handler
def parse(self): """ parse the data """ # convert the xlsx file to csv first delimiter = "|" csv_file = self.xlsx_to_csv(self.getInputFile(), delimiter=delimiter) reader = csv.DictReader(csv_file, delimiter=delimiter) for n, row in enumerate(reader): ...
parse the data
def fromvars(cls, dataset, batch_size, train=None, **kwargs): """Create a Batch directly from a number of Variables.""" batch = cls() batch.batch_size = batch_size batch.dataset = dataset batch.fields = dataset.fields.keys() for k, v in kwargs.items(): setattr...
Create a Batch directly from a number of Variables.
def flash_spi_attach(self, hspi_arg): """Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command. """ # last 3 bytes in ESP_SPI_ATTACH argument are reserved values arg = struct.pack('<I', hsp...
Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command.
def key_value_contents(use_dict=None, as_class=dict, key_values=()): """Return the contents of an object as a dict.""" if _debug: key_value_contents._debug("key_value_contents use_dict=%r as_class=%r key_values=%r", use_dict, as_class, key_values) # make/extend the dictionary of content if use_dict is ...
Return the contents of an object as a dict.
def set_device_id(self, dev, id): """Set device ID to new value. :param str dev: Serial device address/path :param id: Device ID to set """ if id < 0 or id > 255: raise ValueError("ID must be an unsigned byte!") com, code, ok = io.send_packet( CMD...
Set device ID to new value. :param str dev: Serial device address/path :param id: Device ID to set
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value """ try: return self._kvs.has(self._key(block, name)) except KeyError: return False
Return whether or not the field named `name` has a non-default value
def __decode_dictionary(self, message_type, dictionary): """Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries...
Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries.
def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear proxy data self.driver_args['service_args'] = self.default_service_args # Clear headers self.dcap = dict(webdriver...
Kills old session and creates a new one with no proxies or headers
def make_2d(array, verbose=True): """ tiny tool to expand 1D arrays the way i want Parameters ---------- array : array-like verbose : bool, default: True whether to print warnings Returns ------- np.array of with ndim = 2 """ array = np.asarray(array) if array....
tiny tool to expand 1D arrays the way i want Parameters ---------- array : array-like verbose : bool, default: True whether to print warnings Returns ------- np.array of with ndim = 2
def propmerge(into, data_from): """ Merge JSON schema requirements into a dictionary """ newprops = copy.deepcopy(into) for prop, propval in six.iteritems(data_from): if prop not in newprops: newprops[prop] = propval continue new_sp = newprops[prop] for subp...
Merge JSON schema requirements into a dictionary
def _read_from_cwlinput(in_file, work_dir, runtime, parallel, input_order, output_cwl_keys): """Read data records from a JSON dump of inputs. Avoids command line flattening of records. """ with open(in_file) as in_handle: inputs = json.load(in_handle) items_by_key = {} input_files = [] p...
Read data records from a JSON dump of inputs. Avoids command line flattening of records.
def searchForMessageIDs(self, query, offset=0, limit=5, thread_id=None): """ Find and get message IDs by query :param query: Text to search for :param offset: Number of messages to skip :param limit: Max. number of messages to retrieve :param thread_id: User/Group ID to ...
Find and get message IDs by query :param query: Text to search for :param offset: Number of messages to skip :param limit: Max. number of messages to retrieve :param thread_id: User/Group ID to search in. See :ref:`intro_threads` :type offset: int :type limit: int ...
def reset_selective(self, regex=None): """Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching ...
Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching variable names in the users namespaces.
def blacklist_token(): """ Blacklists an existing JWT by registering its jti claim in the blacklist. .. example:: $ curl http://localhost:5000/blacklist_token -X POST \ -d '{"token":"<your_token>"}' """ req = flask.request.get_json(force=True) data = guard.extract_jwt_token(req[...
Blacklists an existing JWT by registering its jti claim in the blacklist. .. example:: $ curl http://localhost:5000/blacklist_token -X POST \ -d '{"token":"<your_token>"}'
def predict(self, a, b): """ Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic """ a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) return (m...
Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, subheader=None, track=False, header=None): """Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_...
Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unserialize methods convert the nested message dict into this format...
def solve_potts_approx(y, w, gamma=None, min_size=1, **kw): """ Fit penalized stepwise constant function (Potts model) to data approximatively, in linear time. Do this by running the exact solver using a small maximum interval size, and then combining consecutive intervals together if it decrea...
Fit penalized stepwise constant function (Potts model) to data approximatively, in linear time. Do this by running the exact solver using a small maximum interval size, and then combining consecutive intervals together if it decreases the cost function.
def inside_polygon(x, y, coordinates): """ Implementing the ray casting point in polygon test algorithm cf. https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm :param x: :param y: :param coordinates: a polygon represented by a list containing two lists (x and y coordinates): ...
Implementing the ray casting point in polygon test algorithm cf. https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm :param x: :param y: :param coordinates: a polygon represented by a list containing two lists (x and y coordinates): [ [x1,x2,x3...], [y1,y2,y3...]] those ...
def set_custom_serializer(self, _type, serializer): """ Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function """ validate_type(_type) validate_serializer(...
Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function
def get_time(self) -> float: """ Get the current time in seconds Returns: The current time in seconds """ if self.pause_time is not None: curr_time = self.pause_time - self.offset - self.start_time return curr_time curr_time = time.ti...
Get the current time in seconds Returns: The current time in seconds
def memory_zones(self): """Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLi...
Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLink): the ``JLink`` instance ...
def get_messages(self): """ Retrieves the error or status messages associated with the specified profile. Returns: dict: Server Profile Health. """ uri = '{}/messages'.format(self.data["uri"]) return self._helper.do_get(uri)
Retrieves the error or status messages associated with the specified profile. Returns: dict: Server Profile Health.
def set_children(self, value, defined): """Set the children of the object.""" self.children = value self.children_defined = defined return self
Set the children of the object.
def get_bibliography(lsst_bib_names=None, bibtex=None): """Make a pybtex BibliographyData instance from standard lsst-texmf bibliography files and user-supplied bibtex content. Parameters ---------- lsst_bib_names : sequence of `str`, optional Names of lsst-texmf BibTeX files to include. Fo...
Make a pybtex BibliographyData instance from standard lsst-texmf bibliography files and user-supplied bibtex content. Parameters ---------- lsst_bib_names : sequence of `str`, optional Names of lsst-texmf BibTeX files to include. For example: .. code-block:: python ['lsst',...
def splay(vec): """ Determine two lengths to split stride the input vector by """ N2 = 2 ** int(numpy.log2( len(vec) ) / 2) N1 = len(vec) / N2 return N1, N2
Determine two lengths to split stride the input vector by
def extract_notification_payload(process_output): """ Processes the raw output from Gatttool stripping the first line and the 'Notification handle = 0x000e value: ' from each line @param: process_output - the raw output from a listen commad of GattTool which may look like thi...
Processes the raw output from Gatttool stripping the first line and the 'Notification handle = 0x000e value: ' from each line @param: process_output - the raw output from a listen commad of GattTool which may look like this: Characteristic value was written successfully ...
def fill_subparser(subparser): """Sets up a subparser to download the binarized MNIST dataset files. The binarized MNIST dataset files (`binarized_mnist_{train,valid,test}.amat`) are downloaded from Hugo Larochelle's website [HUGO]. .. [HUGO] http://www.cs.toronto.edu/~larocheh/public/datasets/ ...
Sets up a subparser to download the binarized MNIST dataset files. The binarized MNIST dataset files (`binarized_mnist_{train,valid,test}.amat`) are downloaded from Hugo Larochelle's website [HUGO]. .. [HUGO] http://www.cs.toronto.edu/~larocheh/public/datasets/ binarized_mnist/binarized_mnist_{...
def _CheckPacketSize(cursor): """Checks that MySQL packet size is big enough for expected query size.""" cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor)) if cur_packet_size < MAX_PACKET_SIZE: raise Error( "MySQL max_allowed_packet of {0} is required, got {1}. " "Please set ma...
Checks that MySQL packet size is big enough for expected query size.
def get_media_list_by_selector( self, media_selector, media_attribute="src" ): """Return a list of media.""" page_url = urlparse.urlparse(self.uri) return [ mediafile.get_instance( urlparse.urljoin( "%s://%s" % ( ...
Return a list of media.
def _expected_condition_find_first_element(self, elements): """Try to find sequentially the elements of the list and return the first element found :param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found sequentially ...
Try to find sequentially the elements of the list and return the first element found :param elements: list of PageElements or element locators as a tuple (locator_type, locator_value) to be found sequentially :returns: first element found or None :rtype: toolium.pageele...
def decrypt(private, ciphertext, output): """Decrypt ciphertext with private key. Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key. """ privatekeydata = json.load(private) assert 'pub' in privatekeydata pub = load_public_key(privatekeydata['pub']) ...
Decrypt ciphertext with private key. Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key.
async def fetch_message(self, id): """|coro| Retrieves a single :class:`.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- :exc...
|coro| Retrieves a single :class:`.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- :exc:`.NotFound` The specified message...
def _is_gitted(self): """Returns true if the current repodir has been initialized in git *and* had a remote origin added *and* has a 'testing' branch. """ from os import waitpid from subprocess import Popen, PIPE premote = Popen("cd {}; git remote -v".format(self.rep...
Returns true if the current repodir has been initialized in git *and* had a remote origin added *and* has a 'testing' branch.
def select(self, selections): '''Make a selection in this representation. BallAndStickRenderer support selections of atoms and bonds. To select the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selec...
Make a selection in this representation. BallAndStickRenderer support selections of atoms and bonds. To select the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection representation.s...
def _deserialize_class(cls, input_cls_name, trusted, strict): """Returns the HasProperties class to use for deserialization""" if not input_cls_name or input_cls_name == cls.__name__: return cls if trusted and input_cls_name in cls._REGISTRY: return cls._REGISTRY[input_cl...
Returns the HasProperties class to use for deserialization
def get_version(dunder_file): """Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDist...
Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDistCommand classes for cmdclass in s...
def int_to_varbyte(self, value): """Convert an integer into a variable length byte. How it works: the bytes are stored in big-endian (significant bit first), the highest bit of the byte (mask 0x80) is set when there are more bytes following. The remaining 7 bits (mask 0x7F) are used ...
Convert an integer into a variable length byte. How it works: the bytes are stored in big-endian (significant bit first), the highest bit of the byte (mask 0x80) is set when there are more bytes following. The remaining 7 bits (mask 0x7F) are used to store the value.
def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None): """ Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state. """ with LiveExecution.lock: self.good_cb = good_cb ...
Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state.
def ctype_class(self): """Summary Returns: TYPE: Description """ def struct_factory(field_types): """Summary Args: field_types (TYPE): Description Returns: TYPE: Description """ cla...
Summary Returns: TYPE: Description
def get_raw(config, backend_section, arthur): """Execute the raw phase for a given backend section, optionally using Arthur :param config: a Mordred config object :param backend_section: the backend section where the raw phase is executed :param arthur: if true, it enables Arthur to collect the raw dat...
Execute the raw phase for a given backend section, optionally using Arthur :param config: a Mordred config object :param backend_section: the backend section where the raw phase is executed :param arthur: if true, it enables Arthur to collect the raw data
def scale_in(self, blocks=None, block_ids=[]): """Scale in the number of active blocks by specified amount. The scale in method here is very rude. It doesn't give the workers the opportunity to finish current tasks or cleanup. This is tracked in issue #530 Parameters --...
Scale in the number of active blocks by specified amount. The scale in method here is very rude. It doesn't give the workers the opportunity to finish current tasks or cleanup. This is tracked in issue #530 Parameters ---------- blocks : int Number of bloc...
def get_threads(session, query): """ Get one or more threads """ # GET /api/messages/0.1/threads response = make_get_request(session, 'threads', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise ThreadsNo...
Get one or more threads
def new_fills_report(self, start_date, end_date, account_id=None, product_id='BTC-USD', format=None, email=None): """`<https://docs.exchange.coinbase.com/#create-a-new-report>`_"...
`<https://docs.exchange.coinbase.com/#create-a-new-report>`_
def check_array(array, accept_sparse=None, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, ensure_min_features=1): """Input validation on an array, list, sparse matrix or similar. By default, the input is conv...
Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. ...
def stdev(requestContext, seriesList, points, windowTolerance=0.1): """ Takes one metric or a wildcard seriesList followed by an integer N. Draw the Standard Deviation of all metrics passed for the past N datapoints. If the ratio of null points in the window is greater than windowTolerance, skip the...
Takes one metric or a wildcard seriesList followed by an integer N. Draw the Standard Deviation of all metrics passed for the past N datapoints. If the ratio of null points in the window is greater than windowTolerance, skip the calculation. The default for windowTolerance is 0.1 (up to 10% of points in...
def compileSass(sassPath): ''' Compile a sass file (and dependencies) into a single css file. ''' cssPath = os.path.splitext(sassPath)[0] + ".css" # subprocess.call(["sass", sassPath, cssPath]) print("Compiling Sass") process = subprocess.Popen(["sass", sassPath, cssPath]) process.wait...
Compile a sass file (and dependencies) into a single css file.
def get_overlapping_ranges(self, collection_link, partition_key_ranges): ''' Given a partition key range and a collection, returns the list of overlapping partition key ranges :param str collection_link: The name of the collection. :param list partition_key_...
Given a partition key range and a collection, returns the list of overlapping partition key ranges :param str collection_link: The name of the collection. :param list partition_key_range: List of partition key range. :return: List o...
def _friendlyAuthError(fn): ''' Decorator to print a friendly you-are-not-authorised message. Use **outside** the _handleAuth decorator to only print the message after the user has been given a chance to login. ''' @functools.wraps(fn) def wrapped(*args, **kwargs): try: r...
Decorator to print a friendly you-are-not-authorised message. Use **outside** the _handleAuth decorator to only print the message after the user has been given a chance to login.
def extract_kwargs(names:Collection[str], kwargs:KWArgs): "Extract the keys in `names` from the `kwargs`." new_kwargs = {} for arg_name in names: if arg_name in kwargs: arg_val = kwargs.pop(arg_name) new_kwargs[arg_name] = arg_val return new_kwargs, kwargs
Extract the keys in `names` from the `kwargs`.
def unregister_counter_nonzero(network): """ Unregister nonzero counter hooks :param network: The network previously registered via `register_nonzero_counter` """ if not hasattr(network, "__counter_nonzero_handles__"): raise ValueError("register_counter_nonzero was not called for this network") for h i...
Unregister nonzero counter hooks :param network: The network previously registered via `register_nonzero_counter`
def cli(ctx, feature_id, organism="", sequence=""): """[CURRENTLY BROKEN] Get the sequence of a feature Output: A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.get_feature_sequence(feature_id, organism=organism, sequence=sequence)
[CURRENTLY BROKEN] Get the sequence of a feature Output: A standard apollo feature dictionary ({"features": [{...}]})
def ParseOptions(self, options): """Parses the options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid. """ # The extraction options are dependent on the data location. helpers_manager.ArgumentHelperManager.ParseOptio...
Parses the options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def get_documents_in_database(self, with_id=True): """Gets all documents in database :param with_id: True iff each document should also come with its id :return: List of documents in collection in database """ documents = [] for coll in self.get_collection_names(): ...
Gets all documents in database :param with_id: True iff each document should also come with its id :return: List of documents in collection in database
def default_if_empty(self, default): '''If the source sequence is empty return a single element sequence containing the supplied default value, otherwise return the source sequence unchanged. Note: This method uses deferred execution. Args: default: The element to b...
If the source sequence is empty return a single element sequence containing the supplied default value, otherwise return the source sequence unchanged. Note: This method uses deferred execution. Args: default: The element to be returned if the source sequence is empty. ...
def from_poppy_creature(cls, poppy, motors, passiv, tip, reversed_motors=[]): """ Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain ...
Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x...
def get_field_from_args_or_session(config, args, field_name): """ We try to get field_name from diffent sources: The order of priorioty is following: - command line argument (--<field_name>) - current session configuration (default_<filed_name>) """ rez = getattr(args, field_name, None) ...
We try to get field_name from diffent sources: The order of priorioty is following: - command line argument (--<field_name>) - current session configuration (default_<filed_name>)
def validate(self, expectations_config=None, evaluation_parameters=None, catch_exceptions=True, result_format=None, only_return_failures=False): """Generates a JSON-formatted report describing the outcome of all expectations. Use the default expectations_config=None to validate the expectations con...
Generates a JSON-formatted report describing the outcome of all expectations. Use the default expectations_config=None to validate the expectations config associated with the DataAsset. Args: expectations_config (json or None): \ If None, uses the expectatio...
def parse_dash(string, width): "parse dash pattern specified with string" # DashConvert from {tk-sources}/generic/tkCanvUtil.c w = max(1, int(width + 0.5)) n = len(string) result = [] for i, c in enumerate(string): if c == " " and len(result): result[-1] += w + 1 elif c == "_": result.append(8*w) ...
parse dash pattern specified with string
def put(self, item): ''' store item in sqlite database ''' if isinstance(item, self._item_class): self._put_one(item) elif isinstance(item, (list, tuple)): self._put_many(item) else: raise RuntimeError('Unknown item(s) type, %s' % type(item))
store item in sqlite database
def get_run_as_identifiers_stack(self): """ :returns: an IdentifierCollection """ session = self.get_session(False) try: return session.get_internal_attribute(self.run_as_identifiers_session_key) except AttributeError: return None
:returns: an IdentifierCollection
def colored(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, ...
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Example: color...
def DEBUG_ON_RESPONSE(self, statusCode, responseHeader, data): ''' Update current frame with response Current frame index will be attached to responseHeader ''' if self.DEBUG_FLAG: # pragma no branch (Flag always set in tests) self._frameBuffer[self._frameCount][1:4]...
Update current frame with response Current frame index will be attached to responseHeader
def __to_plain_containers(self, container: Union[CommentedSeq, CommentedMap] ) -> Union[OrderedDict, list]: """Converts any sequence or mapping to list or OrderedDict Stops at anything that isn't a sequence or a mapping. One day, we'l...
Converts any sequence or mapping to list or OrderedDict Stops at anything that isn't a sequence or a mapping. One day, we'll extract the comments and formatting and store \ them out-of-band. Args: mapping: The mapping of constructed subobjects to edit
def p_expr_div_expr(p): """ expr : expr BAND expr | expr BOR expr | expr BXOR expr | expr PLUS expr | expr MINUS expr | expr MUL expr | expr DIV expr | expr MOD expr | expr POW expr | expr LSHIFT exp...
expr : expr BAND expr | expr BOR expr | expr BXOR expr | expr PLUS expr | expr MINUS expr | expr MUL expr | expr DIV expr | expr MOD expr | expr POW expr | expr LSHIFT expr | expr RSHIFT exp...
def channel_in_frame(channel, framefile): """Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str` name of channel to find framefile : `str` path of GWF file to test Returns ------- infram...
Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str` name of channel to find framefile : `str` path of GWF file to test Returns ------- inframe : `bool` whether this channel is includ...
def run_cell_magic(self, magic_name, line, cell): """Execute the given cell magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the first input line as a single string. ...
Execute the given cell magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the first input line as a single string. cell : str The body of the cell as a (possibly mul...