positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def is_previous_task_processing(self, *args, **kwargs): """ Return True if exist task that is equal to current and is uncompleted """ app = self._get_app() inspect = app.control.inspect() active = inspect.active() or {} scheduled = inspect.scheduled() or {} reserved = ins...
Return True if exist task that is equal to current and is uncompleted
def get_hg_revision(repopath): """Return Mercurial revision for the repository located at repopath Result is a tuple (global, local, branch), with None values on error For example: >>> get_hg_revision(".") ('eba7273c69df+', '2015+', 'default') """ try: ass...
Return Mercurial revision for the repository located at repopath Result is a tuple (global, local, branch), with None values on error For example: >>> get_hg_revision(".") ('eba7273c69df+', '2015+', 'default')
def modify_ssh_template(auth, url, ssh_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a ssh template. :param auth: :param url: :param ssh_template: Human readable label which is the name ...
Function takes input of a dictionry containing the required key/value pair for the modification of a ssh template. :param auth: :param url: :param ssh_template: Human readable label which is the name of the specific ssh template :param template_id Internal IMC number which designates the specific s...
def run(config_file): """load the config, create a population, evolve and show the result""" # Load configuration. config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file) # Create the population, which is the top-level object for...
load the config, create a population, evolve and show the result
def calculte_tensor_to_label_output_shapes(operator): ''' Allowed input/output patterns are 1. [N, C] ---> [N, 1] Note that N must be 1 currently because TensorToProbability doesn't support batch size larger than 1. ''' check_input_and_output_numbers(operator, input_count_range=1, output_co...
Allowed input/output patterns are 1. [N, C] ---> [N, 1] Note that N must be 1 currently because TensorToProbability doesn't support batch size larger than 1.
def set_position(self, x, y): """Sets the shape position. Args: x (int): the x coordinate y (int): the y coordinate """ self.attributes['x'] = str(x) self.attributes['y'] = str(y)
Sets the shape position. Args: x (int): the x coordinate y (int): the y coordinate
def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. :rtype: dict. """ kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } #noinspection PyUnresolvedReferences if self.re...
Returns the keyword arguments for instantiating the form. :rtype: dict.
def download(self, start, stop, freq='D', user=None, password=None, **kwargs): """Download data for given Instrument object from start to stop. Parameters ---------- start : pandas.datetime start date to download data stop : pandas.datetime ...
Download data for given Instrument object from start to stop. Parameters ---------- start : pandas.datetime start date to download data stop : pandas.datetime stop date to download data freq : string Stepsize between dates for season, ...
def __get_response_element_data(self, key1, key2): """ For each origin an elements object is created in the ouput. For each destination, an object is created inside elements object. For example, if there are 2 origins and 1 destination, 2 element objects with 1 object each are created. I...
For each origin an elements object is created in the ouput. For each destination, an object is created inside elements object. For example, if there are 2 origins and 1 destination, 2 element objects with 1 object each are created. If there are 2 origins and 2 destinations, 2 element objects wit...
def evaluate_rule(self, rule, value, target): """Calculate the value.""" def evaluate(expr): if expr in LOGICAL_OPERATORS.values(): return expr rvalue = self.get_value_for_expr(expr, target) if rvalue is None: return False # ignore thi...
Calculate the value.
def find_files(args): ''' Return list of spec files. `args` may be filenames which are passed right through, or directories in which case they are searched recursively for *._spec.py ''' files_or_dirs = args or ['.'] filenames = [] for f in files_or_dirs: if path.isdir(f): ...
Return list of spec files. `args` may be filenames which are passed right through, or directories in which case they are searched recursively for *._spec.py
def send(self, from_client, message, to_clients=None, transient=False, push_data=None): """ 在指定会话中发送消息。 :param from_client: 发送者 id :param message: 消息内容 :param to_clients: 接受者 id,只在系统会话中生效 :param transient: 是否以暂态形式发送消息 :param push_data: 推送消息内容,参考:https://url.leana...
在指定会话中发送消息。 :param from_client: 发送者 id :param message: 消息内容 :param to_clients: 接受者 id,只在系统会话中生效 :param transient: 是否以暂态形式发送消息 :param push_data: 推送消息内容,参考:https://url.leanapp.cn/pushData
def generate(self, api): """Generates a file that lists each namespace.""" with self.output_to_relative_path('ex1.out'): for namespace in api.namespaces.values(): self.emit(namespace.name)
Generates a file that lists each namespace.
def verify_ticket(self, ticket): """Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. """ params = [('ticket', ticket), ('service', self.service_url)] url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' + urllib_pa...
Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure.
def get(self): """ Get a JSON-ready representation of this Section. :returns: This Section, ready for use in a request body. :rtype: dict """ section = {} if self.key is not None and self.value is not None: section[self.key] = self.value retur...
Get a JSON-ready representation of this Section. :returns: This Section, ready for use in a request body. :rtype: dict
def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None): """Component-wise operation with no broadcasting. Args: tf_fn: a component-wise function taking n tf.Tensor inputs and producing a tf.Tensor output xs: n Tensors output_dtype: an optional dtype grad_function: an optional ...
Component-wise operation with no broadcasting. Args: tf_fn: a component-wise function taking n tf.Tensor inputs and producing a tf.Tensor output xs: n Tensors output_dtype: an optional dtype grad_function: an optional python function name: an optional string Returns: a Tensor
def wait_for_redfish_firmware_update_to_complete(self, redfish_object): """Continuously polls for iLO firmware update to complete. :param redfish_object: redfish instance """ p_state = ['Idle'] c_state = ['Idle'] def has_firmware_flash_completed(): """Checks...
Continuously polls for iLO firmware update to complete. :param redfish_object: redfish instance
def incr(self, item, value): """Increment a key by the given amount.""" if item in self: old = UserDict.__getitem__(self, item) else: old = 0.0 self[item] = old + value
Increment a key by the given amount.
def check_field(self, field, required_channels='all'): """ Check whether a single field is valid in its basic form. Does not check compatibility with other fields. Parameters ---------- field : str The field name required_channels : list, optional ...
Check whether a single field is valid in its basic form. Does not check compatibility with other fields. Parameters ---------- field : str The field name required_channels : list, optional Used for signal specification fields. All channels are ...
def _create_os_nwk(self, tenant_id, tenant_name, direc, is_fw_virt=False): """Function to create Openstack network. This function does the following: 1. Allocate an IP address with the net_id/subnet_id not filled in the DB. 2. Fill network parameters w/o vlan, segmentation_id...
Function to create Openstack network. This function does the following: 1. Allocate an IP address with the net_id/subnet_id not filled in the DB. 2. Fill network parameters w/o vlan, segmentation_id, because we don't have net_id to store in DB. 3. Create a Openstac...
def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual_...
List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number]
def update_or_create(cls, with_status=False, **kwargs): """ Update or create static netlink. DNS entry differences are not resolved, instead any entries provided will be the final state for this netlink. If the intent is to add/remove DNS entries you can use the :meth:`~domain_se...
Update or create static netlink. DNS entry differences are not resolved, instead any entries provided will be the final state for this netlink. If the intent is to add/remove DNS entries you can use the :meth:`~domain_server_address` method to add or remove. :raises Crea...
def user_path(self, team, user): """ Returns the path to directory with the user's package repositories. """ return os.path.join(self.team_path(team), user)
Returns the path to directory with the user's package repositories.
def auto_message(self, args): """Try guess the message by the args passed args: a set of args passed on the wrapper __call__ in the definition above. if the object already have some message (defined in __init__), we don't change that. If the first arg is a function, so is...
Try guess the message by the args passed args: a set of args passed on the wrapper __call__ in the definition above. if the object already have some message (defined in __init__), we don't change that. If the first arg is a function, so is decorated without argument, use ...
def add_context(self, isc_name, isc_policy_id, isc_traffic_tag): """ Create the VSS Context within the VSSContainer :param str isc_name: ISC name, possibly append policy name?? :param str isc_policy_id: Policy ID in SMC (the 'key' attribute) :param str isc_traffic_tag: NSX group...
Create the VSS Context within the VSSContainer :param str isc_name: ISC name, possibly append policy name?? :param str isc_policy_id: Policy ID in SMC (the 'key' attribute) :param str isc_traffic_tag: NSX groupId (serviceprofile-145) :raises CreateElementFailed: failed to create ...
def dcc_accept(self, mask, filepath, port, pos): """accept a DCC RESUME for an axisting DCC SEND. filepath is the filename to sent. port is the port opened on the server. pos is the expected offset""" return self.dcc.resume(mask, filepath, port, pos)
accept a DCC RESUME for an axisting DCC SEND. filepath is the filename to sent. port is the port opened on the server. pos is the expected offset
def get_correction(self, entry): """ Gets the Freysoldt correction for a defect entry Args: entry (DefectEntry): defect entry to compute Freysoldt correction on. Requires following parameters in the DefectEntry to exist: axis_grid (3 x NGX where N...
Gets the Freysoldt correction for a defect entry Args: entry (DefectEntry): defect entry to compute Freysoldt correction on. Requires following parameters in the DefectEntry to exist: axis_grid (3 x NGX where NGX is the length of the NGX grid ...
def write_outro (self): """Write end of check message.""" self.writeln(u"<br/>") self.write(_("That's it.")+" ") if self.stats.number >= 0: self.write(_n("%d link checked.", "%d links checked.", self.stats.number) % self.stats.number) self.w...
Write end of check message.
def ReadPathInfos(self, client_id, path_type, components_list, cursor=None): """Retrieves path info records for given paths.""" if not components_list: return {} path_ids = list(map(rdf_objects.PathID.FromComponents, components_list)) path_infos = {components: None for components in components_...
Retrieves path info records for given paths.
def get_init_container(self, init_command, init_args, env_vars, context_mounts, persistence_outputs, persistence_data): """Pod init container for sett...
Pod init container for setting outputs path.
def __could_edit(self, slug): ''' Test if the user could edit the page. ''' page_rec = MWiki.get_by_uid(slug) if not page_rec: return False if self.check_post_role()['EDIT']: return True elif page_rec.user_name == self.userinfo.user_name: ...
Test if the user could edit the page.
def check_key(self, key, raise_error=True, *args, **kwargs): """ Checks whether the key is a valid formatoption Parameters ---------- %(check_key.parameters.no_possible_keys|name)s Returns ------- %(check_key.returns)s Raises ------ ...
Checks whether the key is a valid formatoption Parameters ---------- %(check_key.parameters.no_possible_keys|name)s Returns ------- %(check_key.returns)s Raises ------ %(check_key.raises)s
def enable(): """ Enable all benchmarking. """ Benchmark.enable = True ComparisonBenchmark.enable = True BenchmarkedFunction.enable = True BenchmarkedClass.enable = True
Enable all benchmarking.
def bin(self): """The bin index of this mark. :returns: An integer bin index or None if the mark is inactive. """ bin = self._query(('MBIN?', Integer, Integer), self.idx) return None if bin == -1 else bin
The bin index of this mark. :returns: An integer bin index or None if the mark is inactive.
def get_route(self, route_id): """ Gets specified route. Will be detail-level if owned by authenticated user; otherwise summary-level. https://strava.github.io/api/v3/routes/#retreive :param route_id: The ID of route to fetch. :type route_id: int :rtype: :clas...
Gets specified route. Will be detail-level if owned by authenticated user; otherwise summary-level. https://strava.github.io/api/v3/routes/#retreive :param route_id: The ID of route to fetch. :type route_id: int :rtype: :class:`stravalib.model.Route`
def malloc(func): """ Decorator Execute tracemalloc """ def _f(*args, **kwargs): print("\n<<<---") tracemalloc.start() res = func(*args, **kwargs) snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') print("[ Top 10 ]") ...
Decorator Execute tracemalloc
def write(self, data, assets=None, show_progress=False, invalid_data_behavior='warn'): """ Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should b...
Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should be a tuple of sid and the data for that asset. assets : set[int], optional The assets that should be in ``data``. If this is provide...
def fetch_all(self, credentials, regions = [], partition_name = 'aws', targets = None): """ Generic fetching function that iterates through all of the service's targets :param credentials: F :param service: Name of the service :param regions: ...
Generic fetching function that iterates through all of the service's targets :param credentials: F :param service: Name of the service :param regions: Name of regions to fetch data from :param partition_name: AWS partition to connect ...
def similar_artists(self, artist_id: str) -> List[NameExternalIDPair]: """ Returns zero or more similar artists (in the form of artist name - external ID pairs) to the one corresponding to the given artist ID. Arguments: artist_id ([str]): The Spotify ID of the artist for wh...
Returns zero or more similar artists (in the form of artist name - external ID pairs) to the one corresponding to the given artist ID. Arguments: artist_id ([str]): The Spotify ID of the artist for whom similar artists are requested. Returns: Zero or more artist name - ...
def upsert_multi(db, collection, object, match_params=None): """ Wrapper for pymongo.insert_many() and update_many() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the do...
Wrapper for pymongo.insert_many() and update_many() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the documents to update :return: ids of inserted/updated document
def set_home_position_encode(self, target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z): ''' The position the system will return to and land on. The position is set automatically by the system during the takeoff in ...
The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitely set by the operator before or after. The global and local positions encode the position in the respective ...
def MERGE(*args): """ Wipe repeated dependencies from a list of (Analysis, id, filename) tuples, supplied as argument. Replace id with the correct filename. """ # Get the longest common path common_prefix = os.path.dirname(os.path.commonprefix([os.path.abspath(a.scripts[-1][1]) for a, _, _ in a...
Wipe repeated dependencies from a list of (Analysis, id, filename) tuples, supplied as argument. Replace id with the correct filename.
def assert_is_not_none(expr, msg_fmt="{msg}"): """Fail if the expression is None. >>> assert_is_not_none(0) >>> assert_is_not_none(None) Traceback (most recent call last): ... AssertionError: expression is None The following msg_fmt arguments are supported: * msg - the default erro...
Fail if the expression is None. >>> assert_is_not_none(0) >>> assert_is_not_none(None) Traceback (most recent call last): ... AssertionError: expression is None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
def removedirs_p(self): """ Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist. """ with contextlib.suppress(FileExistsError, DirectoryNotEmpty): with DirectoryNotEmpty.translate(): self.removedirs() return...
Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist.
def index_queryset(self, using=None): """ Used when the entire index for model is updated. """ return self.get_model().objects.filter(date_creation__lte=datetime.datetime.now())
Used when the entire index for model is updated.
def _prep_inputs(vrn_info, cnv_info, somatic_info, work_dir, config): """Prepare inputs for running PhyloWGS from variant and CNV calls. """ exe = os.path.join(os.path.dirname(sys.executable), "create_phylowgs_inputs.py") assert os.path.exists(exe), "Could not find input prep script for PhyloWGS runs." ...
Prepare inputs for running PhyloWGS from variant and CNV calls.
def get_paths(self): """Get all paths from the root to the leaves. For example, given a chain like `{'a':{'b':{'c':None}}}`, this method would return `[['a', 'b', 'c']]`. Returns: A list of lists of paths. """ paths = [] for key, child in six.iterite...
Get all paths from the root to the leaves. For example, given a chain like `{'a':{'b':{'c':None}}}`, this method would return `[['a', 'b', 'c']]`. Returns: A list of lists of paths.
def add_format_info(matrix, version, error, mask_pattern): """\ Adds the format information into the provided matrix. ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55) ISO/IEC 18004:2015(E) -- 7.9.1 QR Code symbols ISO/IEC 18004:2015(E) -- 7.9.2 Micro QR Code symbols :param matrix: The...
\ Adds the format information into the provided matrix. ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55) ISO/IEC 18004:2015(E) -- 7.9.1 QR Code symbols ISO/IEC 18004:2015(E) -- 7.9.2 Micro QR Code symbols :param matrix: The matrix. :param int version: Version constant :param int e...
def get_lldp_neighbor_detail_output_has_more(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(get_lldp_neighbor_detail, "out...
Auto Generated Code
def sendGame(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bots/api#sendgame """ p = _strip(locals()) return self._api_request('sendGame', _rectify(p))
See: https://core.telegram.org/bots/api#sendgame
def state_pop(self): """ Pop the state of all generators """ super(Composite,self).state_pop() for gen in self.generators: gen.state_pop()
Pop the state of all generators
def execute(self, conn, block_name="", transaction = False): """ block: /a/b/c#d """ if not conn: msg='Oracle/BlockParent/List. No DB connection found' dbsExceptionHandler('dbsException-failed-connect2host', msg, self.logger.exception) sql = self.sql ...
block: /a/b/c#d
def fft_spectrum(frames, fft_points=512): """This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT). Please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.f...
This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT). Please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html for further details. Args: ...
def get_domain_class_terminal_attribute_iterator(ent): """ Returns an iterator over all terminal attributes in the given registered resource. """ for attr in itervalues_(ent.__everest_attributes__): if attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL: yield attr
Returns an iterator over all terminal attributes in the given registered resource.
def checklat(lat, name='lat'): """Makes sure the latitude is inside [-90, 90], clipping close values (tolerance 1e-4). Parameters ========== lat : array_like latitude name : str, optional parameter name to use in the exception message Returns ======= lat : ndarray o...
Makes sure the latitude is inside [-90, 90], clipping close values (tolerance 1e-4). Parameters ========== lat : array_like latitude name : str, optional parameter name to use in the exception message Returns ======= lat : ndarray or float Same as input where va...
def rooms_upload(self, rid, file, **kwargs): """Post a message with attached file to a dedicated room.""" files = { 'file': (os.path.basename(file), open(file, 'rb'), mimetypes.guess_type(file)[0]), } return self.__call_api_post('rooms.upload/' + rid, kwargs=kwargs, use_json=...
Post a message with attached file to a dedicated room.
def stream(self, date_created_from=values.unset, date_created_to=values.unset, limit=None, page_size=None): """ Streams ExecutionInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. ...
Streams ExecutionInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param datetime date_created_from: Only show E...
def find_kw(ar_or_sample, kw): """ This function is used to find keywords that are not on the analysis but keywords that are on the interim fields. This function and is is_keyword function should probably be in resultsimport.py or somewhere central where it can be used by other inst...
This function is used to find keywords that are not on the analysis but keywords that are on the interim fields. This function and is is_keyword function should probably be in resultsimport.py or somewhere central where it can be used by other instrument interfaces.
def tokenize_math(text): r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position >>> b = Buffer(r'$\min_x$ \command') >>> tokenize_math(b) '$' >>> b = Buffer(r'$$\min_x$$ \command') >>> tokenize_math(b) '$$' """ if text.startswith('...
r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position >>> b = Buffer(r'$\min_x$ \command') >>> tokenize_math(b) '$' >>> b = Buffer(r'$$\min_x$$ \command') >>> tokenize_math(b) '$$'
def _await_descriptor_upload(tor_protocol, onion, progress, await_all_uploads): """ Internal helper. :param tor_protocol: ITorControlProtocol instance :param onion: IOnionService instance :param progress: a progess callback, or None :returns: a Deferred that fires once we've detected at leas...
Internal helper. :param tor_protocol: ITorControlProtocol instance :param onion: IOnionService instance :param progress: a progess callback, or None :returns: a Deferred that fires once we've detected at least one descriptor upload for the service (as detected by listening for HS_DES...
def setShowTerritory(self, state): """ Sets the display mode for this widget to the inputed mode. :param state | <bool> """ if state == self._showTerritory: return self._showTerritory = state self.setDirty()
Sets the display mode for this widget to the inputed mode. :param state | <bool>
def createArchiveExample(fileName): """ Creates Combine Archive containing the given file. :param fileName: file to include in the archive :return: None """ print('*' * 80) print('Create archive') print('*' * 80) archive = CombineArchive() archive.addFile( fileName, # file...
Creates Combine Archive containing the given file. :param fileName: file to include in the archive :return: None
def clean_s_name(self, s_name, root): """ Helper function to take a long file name and strip it back to a clean sample name. Somewhat arbitrary. :param s_name: The sample name to clean :param root: The directory path that this file is within :config.prepend_dirs: boolean, whether...
Helper function to take a long file name and strip it back to a clean sample name. Somewhat arbitrary. :param s_name: The sample name to clean :param root: The directory path that this file is within :config.prepend_dirs: boolean, whether to prepend dir name to s_name :return: Th...
def insert_io( args ): """ Inserts a method's i/o into the datastore :param dict args: A dictionary of the hash, stack, packet_num, methodname, args, and returnval :rtype None: """ global CACHE_ load_cache() hash = args['hash'] record_used('cache', hash) packet_num = args['pack...
Inserts a method's i/o into the datastore :param dict args: A dictionary of the hash, stack, packet_num, methodname, args, and returnval :rtype None:
def get_random_path(graph) -> List[BaseEntity]: """Get a random path from the graph as a list of nodes. :param pybel.BELGraph graph: A BEL graph """ wg = graph.to_undirected() nodes = wg.nodes() def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]: """Get a pair of random nodes."""...
Get a random path from the graph as a list of nodes. :param pybel.BELGraph graph: A BEL graph
def remove_adapter(widget_class, flavour=None): """Removes the given widget class information from the default set of adapters. If widget_class had been previously added by using add_adapter, the added adapter will be removed, restoring possibly previusly existing adapter(s). Notice that this funct...
Removes the given widget class information from the default set of adapters. If widget_class had been previously added by using add_adapter, the added adapter will be removed, restoring possibly previusly existing adapter(s). Notice that this function will remove only *one* adapter about given wige...
def create_assignment( # pylint: disable=too-many-arguments self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs ): """Create a new assignment. Create a new assignment. By...
Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE ASSIGNMENT`` short_name (str): short name of assignment, on...
def get_new_edges(self, level): """Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph. """ if level == 0: edges0 = [(0, 1), (0, 2)] e...
Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph.
def list_services(zone=None, permanent=True): ''' List services added for zone as a space separated list. If zone is omitted, default zone will be used. CLI Example: .. code-block:: bash salt '*' firewalld.list_services List a specific zone .. code-block:: bash salt '*'...
List services added for zone as a space separated list. If zone is omitted, default zone will be used. CLI Example: .. code-block:: bash salt '*' firewalld.list_services List a specific zone .. code-block:: bash salt '*' firewalld.list_services my_zone
def children(self): """ returns a list of dicts of items in the current context """ items = [] catalog = self.context.portal_catalog current_path = '/'.join(self.context.getPhysicalPath()) sidebar_search = self.request.get('sidebar-search', None) if sidebar_searc...
returns a list of dicts of items in the current context
def get_extents(self, element, ranges, range_type='combined', xdim=None, ydim=None, zdim=None): """ Gets the extents for the axes from the current Element. The globally computed ranges can optionally override the extents. The extents are computed by combining the data ranges, extents ...
Gets the extents for the axes from the current Element. The globally computed ranges can optionally override the extents. The extents are computed by combining the data ranges, extents and dimension ranges. Each of these can be obtained individually by setting the range_type to one of: ...
def twoline2rv(longstr1, longstr2, whichconst, afspc_mode=False): """Return a Satellite imported from two lines of TLE data. Provide the two TLE lines as strings `longstr1` and `longstr2`, and select which standard set of gravitational constants you want by providing `gravity_constants`: `sgp4.ear...
Return a Satellite imported from two lines of TLE data. Provide the two TLE lines as strings `longstr1` and `longstr2`, and select which standard set of gravitational constants you want by providing `gravity_constants`: `sgp4.earth_gravity.wgs72` - Standard WGS 72 model `sgp4.earth_gravity.wgs84` ...
def _parse_tile_url(tile_url): """ Extracts tile name, data and AWS index from tile URL :param tile_url: Location of tile at AWS :type: tile_url: str :return: Tuple in a form (tile_name, date, aws_index) :rtype: (str, str, int) """ props = tile_url.rsplit('/', 7)...
Extracts tile name, data and AWS index from tile URL :param tile_url: Location of tile at AWS :type: tile_url: str :return: Tuple in a form (tile_name, date, aws_index) :rtype: (str, str, int)
def endpoint(value: Any) -> Any: """ Convert a endpoint string to the corresponding Endpoint instance type :param value: Endpoint string or subclass :return: """ if issubclass(type(value), Endpoint): return value elif isinstance(value, str): for api, cls in MANAGED_API.items...
Convert a endpoint string to the corresponding Endpoint instance type :param value: Endpoint string or subclass :return:
def clean(): """Deletes dev files""" rm("$testfn*") rm("*.bak") rm("*.core") rm("*.egg-info") rm("*.orig") rm("*.pyc") rm("*.pyd") rm("*.pyo") rm("*.rej") rm("*.so") rm("*.~") rm("*__pycache__") rm(".coverage") rm(".tox") rm(".coverage") rm("build") ...
Deletes dev files
def load_modules(self, filepaths): """ Loads the modules from their `filepaths`. A filepath may be a directory filepath if there is an `__init__.py` file in the directory. If a filepath errors, the exception will be caught and logged in the logger. Returns a lis...
Loads the modules from their `filepaths`. A filepath may be a directory filepath if there is an `__init__.py` file in the directory. If a filepath errors, the exception will be caught and logged in the logger. Returns a list of modules.
def attached_to_model(self): """Tells if the current field is the one attached to the model, not instance""" try: if not bool(self._model): return False except AttributeError: return False else: try: return not bool(self...
Tells if the current field is the one attached to the model, not instance
def create_record(self, dns_type, name, content, **kwargs): """ Create a dns record :param dns_type: :param name: :param content: :param kwargs: :return: """ data = { 'type': dns_type, 'name': name, 'content': co...
Create a dns record :param dns_type: :param name: :param content: :param kwargs: :return:
def fasta_format_check(fasta_path, logger): """ Check that a file is valid FASTA format. - First non-blank line needs to begin with a '>' header character. - Sequence can only contain valid IUPAC nucleotide characters Args: fasta_str (str): FASTA file contents string Raises: ...
Check that a file is valid FASTA format. - First non-blank line needs to begin with a '>' header character. - Sequence can only contain valid IUPAC nucleotide characters Args: fasta_str (str): FASTA file contents string Raises: Exception: If invalid FASTA format
def user_warning(self, message, caption='Warning!'): """ Shows a dialog that warns the user about some action Parameters ---------- message : message to display to user caption : title for dialog (default: "Warning!") Returns ------- continue_boo...
Shows a dialog that warns the user about some action Parameters ---------- message : message to display to user caption : title for dialog (default: "Warning!") Returns ------- continue_bool : True or False
def iterslice(iterable, start=0, stop=None, step=1): # type: (Iterable[T], int, int, int) -> Iterable[T] """ Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice ...
Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice after the first time stop(item) == True.
def find_eq_stress(strains, stresses, tol=1e-10): """ Finds stress corresponding to zero strain state in stress-strain list Args: strains (Nx3x3 array-like): array corresponding to strains stresses (Nx3x3 array-like): array corresponding to stresses tol (float): tolerance to find ze...
Finds stress corresponding to zero strain state in stress-strain list Args: strains (Nx3x3 array-like): array corresponding to strains stresses (Nx3x3 array-like): array corresponding to stresses tol (float): tolerance to find zero strain state
def calc_attribute_statistic(self, attribute, statistic, time): """ Calculate statistics based on the values of an attribute. The following statistics are supported: mean, max, min, std, ptp (range), median, skew (mean - median), and percentile_(percentile value). Args: attr...
Calculate statistics based on the values of an attribute. The following statistics are supported: mean, max, min, std, ptp (range), median, skew (mean - median), and percentile_(percentile value). Args: attribute: Attribute extracted from model grid statistic: Name of statistic ...
def base_http_parser(): """Creates a parser with arguments specific to sending an HTTP request to the REST API. Returns: {ArgumentParser}: Base parser with default HTTP args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( '--url', type=str, ...
Creates a parser with arguments specific to sending an HTTP request to the REST API. Returns: {ArgumentParser}: Base parser with default HTTP args
def build_markov(cursor, cmdchar, ctrlchan, speaker=None, initial_run=False, debug=False): """Builds a markov dictionary.""" if initial_run: cursor.query(Babble_last).delete() lastrow = cursor.query(Babble_last).first() if not lastrow: lastrow = Babble_last(last=0) cursor.add(las...
Builds a markov dictionary.
def pairwise(function, x, y=None, **kwargs): """ pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list o...
pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list of random vectors. The columns of each vector correspond ...
def fromISO(cls, iso_string): ''' a method for constructing a labDT object from a timezone aware ISO string :param iso_string: string with date and time info in ISO format :return: labDT object ''' # validate input title = 'ISO time input for labDT.fromISO...
a method for constructing a labDT object from a timezone aware ISO string :param iso_string: string with date and time info in ISO format :return: labDT object
def layer_description_extractor(layer, node_to_id): '''get layer description. ''' layer_input = layer.input layer_output = layer.output if layer_input is not None: if isinstance(layer_input, Iterable): layer_input = list(map(lambda x: node_to_id[x], layer_input)) else: ...
get layer description.
def get_authorization(self, **kwargs): """Gets the authorization object for the view.""" if self.authorization is not None: return self.authorization auth_class = self.get_authorization_class() auth_user = self.get_authorization_user() auth_kwargs = { 'to...
Gets the authorization object for the view.
def _handle_response(self, response): """Logs dropped chunks and updates dynamic settings""" if isinstance(response, Exception): logging.error("dropped chunk %s" % response) elif response.json().get("limits"): parsed = response.json() self._api.dynamic_setting...
Logs dropped chunks and updates dynamic settings
def done(self, msg_handle): """acknowledge completion of message""" self.sqs_client.delete_message( QueueUrl=self.queue_url, ReceiptHandle=msg_handle.handle, )
acknowledge completion of message
def _update_avr(self): """ Get the latest status information from device. Method queries device via HTTP and updates instance attributes. Returns "True" on success and "False" on fail. This method is for pre 2016 AVR(-X) devices """ # Set all tags to be evaluated...
Get the latest status information from device. Method queries device via HTTP and updates instance attributes. Returns "True" on success and "False" on fail. This method is for pre 2016 AVR(-X) devices
def insert(self, context): """ Create connection pool. :param resort.engine.execution.Context context: Current execution context. """ status_code, msg = self.__endpoint.post( "/resources/jdbc-connection-pool", data={ "id": self.__name, "resType": self.__res_type, "datasourceClas...
Create connection pool. :param resort.engine.execution.Context context: Current execution context.
def extract_links_from_peer_assignment(self, element_id): """ Return a dictionary with links to supplement files (pdf, csv, zip, ipynb, html and so on) extracted from peer assignment. @param element_id: Element ID to extract files from. @type element_id: str @return: @s...
Return a dictionary with links to supplement files (pdf, csv, zip, ipynb, html and so on) extracted from peer assignment. @param element_id: Element ID to extract files from. @type element_id: str @return: @see CourseraOnDemand._extract_links_from_text
def _worst_case_generation(self, worst_case_scale_factors, modes): """ Define worst case generation time series for fluctuating and dispatchable generators. Parameters ---------- worst_case_scale_factors : dict Scale factors defined in config file 'config_tim...
Define worst case generation time series for fluctuating and dispatchable generators. Parameters ---------- worst_case_scale_factors : dict Scale factors defined in config file 'config_timeseries.cfg'. Scale factors describe actual power to nominal power ratio of...
def _query_(self, path, method, params={}): """Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: ...
Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the ...
def duplicates(inlist): """ Returns duplicate items in the FIRST dimension of the passed list. Usage: duplicates (inlist) """ dups = [] for i in range(len(inlist)): if inlist[i] in inlist[i+1:]: dups.append(inlist[i]) return dups
Returns duplicate items in the FIRST dimension of the passed list. Usage: duplicates (inlist)
def _handle_for(self, node, scope, ctxt, stream): """Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling for") if node.init is not None: # perform the init self._hand...
Handle For nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
def add_rup_params(self, rupture): """ Add .REQUIRES_RUPTURE_PARAMETERS to the rupture """ for param in self.REQUIRES_RUPTURE_PARAMETERS: if param == 'mag': value = rupture.mag elif param == 'strike': value = rupture.surface.get_str...
Add .REQUIRES_RUPTURE_PARAMETERS to the rupture
def _set_link_error_disable(self, v, load=False): """ Setter method for link_error_disable, mapped from YANG variable /interface/ethernet/link_error_disable (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_error_disable is considered as a private meth...
Setter method for link_error_disable, mapped from YANG variable /interface/ethernet/link_error_disable (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_error_disable is considered as a private method. Backends looking to populate this variable should do s...