code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None): """ Adapts a single persistent instance to a REST model; at present this is a common method for all persistent backends. Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as fo...
Adapts a single persistent instance to a REST model; at present this is a common method for all persistent backends. Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as for discussion on this feature
def lag_avgs(self): ''' same data as expo_avgs, but with keys as the average age of the data -- assuming evenly spaced data points -- rather than decay rates ''' if not self.interval: return interval = self.interval.mean return dict([(...
same data as expo_avgs, but with keys as the average age of the data -- assuming evenly spaced data points -- rather than decay rates
def temp45(msg): """Static air temperature. Args: msg (String): 28 bytes hexadecimal message string Returns: float: tmeperature in Celsius degree """ d = hex2bin(data(msg)) sign = int(d[16]) value = bin2int(d[17:26]) if sign: value = value - 512 temp = v...
Static air temperature. Args: msg (String): 28 bytes hexadecimal message string Returns: float: tmeperature in Celsius degree
def update(self): """Update RAM memory stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Grab MEM using the psutil virtual_memory method vm_s...
Update RAM memory stats using the input method.
def find(self, pattern): """ Searches for a pattern in the current memory segment """ pos = self.current_segment.data.find(pattern) if pos == -1: return -1 return pos + self.current_position
Searches for a pattern in the current memory segment
def getPassage(self, urn, inventory=None, context=None): """ Retrieve a passage :param urn: URN identifying the text's passage (Minimum depth : 1) :type urn: text :param inventory: Name of the inventory :type inventory: text :param context: Number of citation units at th...
Retrieve a passage :param urn: URN identifying the text's passage (Minimum depth : 1) :type urn: text :param inventory: Name of the inventory :type inventory: text :param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediat...
def create_diamond_db(self): '''Create a diamond database from the unaligned sequences in this package. Returns ------- path to the created diamond db e.g. 'my_sequences.dmnd' ''' base = self.unaligned_sequence_database_path() cmd = "diamond makedb --in '%s' -d '...
Create a diamond database from the unaligned sequences in this package. Returns ------- path to the created diamond db e.g. 'my_sequences.dmnd'
def _scrollTree( self, value ): """ Updates the tree view scrolling to the inputed value. :param value | <int> """ if self._scrolling: return tree_bar = self.uiGanttTREE.verticalScrollBar() self._scrolling = True ...
Updates the tree view scrolling to the inputed value. :param value | <int>
def search(keyword, type=1, offset=0, limit=30): """搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if keyword is None: raise ParamsError() r =...
搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
def listFormats(self, vendorSpecific=None): """See Also: listFormatsResponse() Args: vendorSpecific: Returns: """ response = self.listFormatsResponse(vendorSpecific) return self._read_dataone_type_response(response, 'ObjectFormatList')
See Also: listFormatsResponse() Args: vendorSpecific: Returns:
def new_qt_console(self, evt=None): """start a new qtconsole connected to our kernel""" return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile)
start a new qtconsole connected to our kernel
def ensure_dtraj_list(dtrajs): r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) """ if isinstance(dtrajs, list): # elements are ints? then wrap into a list if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i...
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
def from_ofxparse(data, institution): """Instantiate :py:class:`ofxclient.Account` subclass from ofxparse module :param data: an ofxparse account :type data: An :py:class:`ofxparse.Account` object :param institution: The parent institution of the account :type institutio...
Instantiate :py:class:`ofxclient.Account` subclass from ofxparse module :param data: an ofxparse account :type data: An :py:class:`ofxparse.Account` object :param institution: The parent institution of the account :type institution: :py:class:`ofxclient.Institution` object
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'birdland.mit.edu', 'namespace': 'currency format', 'identifier': name, ...
Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type
def to_concat_skip_model(self, start_id, end_id): """Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-...
Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection.
def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' atjob_file = '/var/spool/cron/atjobs/{job}'.format( job=jobid ...
Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid>
def calculate_size(name, service_name): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(service_name) return data_size
Calculates the request payload size
def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card typ...
Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card type. :type card_type: str Can be one of these: ...
def execute_side_effect(side_effect=UNDEFINED, args=UNDEFINED, kwargs=UNDEFINED): """ Executes a side effect if one is defined. :param side_effect: The side effect to execute :type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters. :param tuple a...
Executes a side effect if one is defined. :param side_effect: The side effect to execute :type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters. :param tuple args: The arguments passed to the stubbed out method :param dict kwargs: The kwargs passed ...
def alter(self, operation, timeout=None, metadata=None, credentials=None): """Runs a modification via this client.""" new_metadata = self.add_login_metadata(metadata) try: return self.any_client().alter(operation, timeout=timeout, metadata=...
Runs a modification via this client.
def set_min_lease(self, min_lease): """ Set the minimum lease period in months. :param min_lease: int """ self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease)
Set the minimum lease period in months. :param min_lease: int
def run(self): """ function called when thread is started """ global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.idx, self.min_file_size, self.max...
function called when thread is started
def get_time_to_merge_request_response(self, item): """Get the first date at which a review was made on the PR by someone other than the user who created the PR """ review_dates = [str_to_datetime(review['created_at']) for review in item['review_comments_data'] if...
Get the first date at which a review was made on the PR by someone other than the user who created the PR
def getRnaQuantMetadata(self): """ input is tab file with no header. Columns are: Id, annotations, description, name, readGroupId where annotation is a comma separated list """ rnaQuantId = self.getLocalId() with self._db as dataSource: rnaQuantReturn...
input is tab file with no header. Columns are: Id, annotations, description, name, readGroupId where annotation is a comma separated list
def initialTrendSmoothingFactors(self, timeSeries): """ Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0 """ result...
Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0
def _pretty_size(size): ''' Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1])
Print sizes in a similar fashion as eclean
def ensure_dirs(filename): """Make sure the directories exist for `filename`.""" dirname, _ = os.path.split(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname)
Make sure the directories exist for `filename`.
def train_rdp_classifier( training_seqs_file, taxonomy_file, model_output_dir, max_memory=None, tmp_dir=tempfile.gettempdir()): """ Train RDP Classifier, saving to model_output_dir training_seqs_file, taxonomy_file: file-like objects used to train the RDP Classifier (see RdpTrai...
Train RDP Classifier, saving to model_output_dir training_seqs_file, taxonomy_file: file-like objects used to train the RDP Classifier (see RdpTrainer documentation for format of training data) model_output_dir: directory in which to save the files necessary to clas...
def read_json(self): """Calls the overridden method. :returns: The read metadata. :rtype: dict """ with reading_ancillary_files(self): metadata = super(GenericLayerMetadata, self).read_json() return metadata
Calls the overridden method. :returns: The read metadata. :rtype: dict
def _parse_siblings(s, **kw): """ http://stackoverflow.com/a/26809037 """ bracket_level = 0 current = [] # trick to remove special-case of trailing chars for c in (s + ","): if c == "," and bracket_level == 0: yield parse_node("".join(current), **kw) current ...
http://stackoverflow.com/a/26809037
def get_obj_cols(df): """ Returns names of 'object' columns in the DataFrame. """ obj_cols = [] for idx, dt in enumerate(df.dtypes): if dt == 'object' or is_category(dt): obj_cols.append(df.columns.values[idx]) return obj_cols
Returns names of 'object' columns in the DataFrame.
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None): """ Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matche...
Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matches *label*, and `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* fi...
def dump(self, config, instance, file_object, prefer=None, **kwargs): """ An abstract method that dumps to a given file object. :param class config: The config class of the instance :param object instance: The instance to dump :param file file_object: The file object to dump to ...
An abstract method that dumps to a given file object. :param class config: The config class of the instance :param object instance: The instance to dump :param file file_object: The file object to dump to :param str prefer: The preferred serialization module name
def build_collision_table(aliases, levels=COLLISION_CHECK_LEVEL_DEPTH): """ Build the collision table according to the alias configuration file against the entire command table. self.collided_alias is structured as: { 'collided_alias': [the command level at which collision h...
Build the collision table according to the alias configuration file against the entire command table. self.collided_alias is structured as: { 'collided_alias': [the command level at which collision happens] } For example: { 'account': [1, 2] } ...
def get_all_route_tables(self, route_table_ids=None, filters=None): """ Retrieve information about your routing tables. You can filter results to return information only about those route tables that match your search parameters. Otherwise, all route tables associated with your a...
Retrieve information about your routing tables. You can filter results to return information only about those route tables that match your search parameters. Otherwise, all route tables associated with your account are returned. :type route_table_ids: list :param route_table_ids...
def trigger_callback(self, sid, namespace, id, data): """Invoke an application callback.""" callback = None try: callback = self.callbacks[sid][namespace][id] except KeyError: # if we get an unknown callback we just ignore it self._get_logger().warning...
Invoke an application callback.
def create_token(user, client, scope, id_token_dic=None): """ Create and populate a Token object. Return a Token object. """ token = Token() token.user = user token.client = client token.access_token = uuid.uuid4().hex if id_token_dic is not None: token.id_token = id_token_d...
Create and populate a Token object. Return a Token object.
def delete_messages(self, ids): """ Delete selected messages for the current user :param ids: list of ids """ str_ids = self._return_comma_list(ids) return self.request('MsgAction', {'action': {'op': 'delete', 'id': str_ids}})
Delete selected messages for the current user :param ids: list of ids
def set_servo_angle(self, goalangle, goaltime, led): """ Sets the servo angle (in degrees) Enable torque using torque_on function before calling this Args: goalangle (int): The desired angle in degrees, range -150 to 150 goaltime (int): the time taken to move from prese...
Sets the servo angle (in degrees) Enable torque using torque_on function before calling this Args: goalangle (int): The desired angle in degrees, range -150 to 150 goaltime (int): the time taken to move from present position to goalposition led (int): t...
def validateObjectPath(p): """ Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path """ if not p.startswith('/'): raise MarshallingError('Object paths must begin with...
Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path
def fire(self, *args, **kwargs): """ Emit the signal, calling all coroutines in-line with the given arguments and in the order they were registered. This is obviously a coroutine. Instead of calling :meth:`fire` explicitly, the ad-hoc signal object itself can be called,...
Emit the signal, calling all coroutines in-line with the given arguments and in the order they were registered. This is obviously a coroutine. Instead of calling :meth:`fire` explicitly, the ad-hoc signal object itself can be called, too.
def results(self, request): "Match results to given term and return the serialized HttpResponse." results = {} form = self.form(request.GET) if form.is_valid(): options = form.cleaned_data term = options.get('term', '') raw_data = self.get_query(reques...
Match results to given term and return the serialized HttpResponse.
def method_selector_fn(self): """Gets the method selector from the config. """ if callable(self.json_rpc_method): return self.json_rpc_method elif isinstance(self.json_rpc_method, (str,)): return lambda *_: self.json_rpc_method raise ValueError("``json_rpc...
Gets the method selector from the config.
def _locatedownload(self, remote_path, **kwargs): """百度云管家获得方式 :param remote_path: 需要下载的文件路径 :type remote_path: str """ params = { 'path': remote_path } url = 'https://{0}/rest/2.0/pcs/file'.format(BAIDUPCS_SERVER) return self._request('file', ...
百度云管家获得方式 :param remote_path: 需要下载的文件路径 :type remote_path: str
def from_descriptions(cls, text, lexicon=None, source='CSV', dlm=',', points=False, abbreviations=False, complete=False, order='depth', ...
Convert a CSV string into a striplog. Expects 2 or 3 fields: top, description OR top, base, description Args: text (str): The input text, given by ``well.other``. lexicon (Lexicon): A lexicon, required to extract components. source (str): ...
def check_hotkey_unique(self, modifiers, hotKey, newFilterPattern, targetItem): """ Checks that the given hotkey is not already in use. Also checks the special hotkeys configured from the advanced settings dialog. @param modifiers: modifiers for the hotkey @param hotKey...
Checks that the given hotkey is not already in use. Also checks the special hotkeys configured from the advanced settings dialog. @param modifiers: modifiers for the hotkey @param hotKey: the hotkey to check @param newFilterPattern: @param targetItem: the phrase for whi...
def insert(self): """persist the field values of this orm""" ret = True schema = self.schema fields = self.depopulate(False) q = self.query q.set_fields(fields) pk = q.insert() if pk: fields = q.fields fields[schema.pk.name] = pk ...
persist the field values of this orm
def get_parser(self, prog_name): """Override to add command options.""" parser = argparse.ArgumentParser(description=self.get_description(), prog=prog_name, add_help=False) return parser
Override to add command options.
def get_parent_repository_ids(self, repository_id): """Gets the parent ``Ids`` of the given repository. arg: repository_id (osid.id.Id): a repository ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the repository raise: NotFound - ``repository_id`` is not found raise...
Gets the parent ``Ids`` of the given repository. arg: repository_id (osid.id.Id): a repository ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the repository raise: NotFound - ``repository_id`` is not found raise: NullArgument - ``repository_id`` is ``null`` raise: ...
def update(self, id, **kwargs): """ Updates an existing post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param id: The ID of the existing post :param kwargs: The properties of the post to change ...
Updates an existing post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param id: The ID of the existing post :param kwargs: The properties of the post to change :return: The updated `Post` object
def connect(self, callback, *args, **kwargs): """ Connects the event with the given callback. When the signal is emitted, the callback is invoked. .. note:: The signal handler is stored with a hard reference, so you need to make sure to call :class:`disconnect()...
Connects the event with the given callback. When the signal is emitted, the callback is invoked. .. note:: The signal handler is stored with a hard reference, so you need to make sure to call :class:`disconnect()` if you want the handler to be garbage co...
def parse_plotPCA(self): """Find plotPCA output""" self.deeptools_plotPCAData = dict() for f in self.find_log_files('deeptools/plotPCAData', filehandles=False): parsed_data = self.parsePlotPCAData(f) for k, v in parsed_data.items(): if k in self.deeptools_...
Find plotPCA output
def entry_to_matrix(prodigy_entry): """ Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating t...
Take in a line from the labeled json and return a vector of labels and a matrix of features for training. Two ways to get 0s: - marked as false by user - generated automatically from other entries when guess is correct Rather than iterating through entities, just get the number of the corr...
def get_assessment_part_form_for_update(self, assessment_part_id): """Gets the assessment part form for updating an existing assessment part. A new assessment part form should be requested for each update transaction. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ...
Gets the assessment part form for updating an existing assessment part. A new assessment part form should be requested for each update transaction. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` return: (osid.assessment.authoring.Assessmen...
def _athlete_endpoint(self, athlete): """Construct athlete endpoint from host and athlete name Keyword arguments: athlete -- Full athlete name """ return '{host}{athlete}'.format( host=self.host, athlete=quote_plus(athlete) )
Construct athlete endpoint from host and athlete name Keyword arguments: athlete -- Full athlete name
def doesNotMatch(self, value, caseSensitive=True): """ Sets the operator type to Query.Op.DoesNotMatch and sets the \ value to the inputted value. :param value <variant> :return self (useful for chaining) :usage |>>> from ...
Sets the operator type to Query.Op.DoesNotMatch and sets the \ value to the inputted value. :param value <variant> :return self (useful for chaining) :usage |>>> from orb import Query as Q |>>> query = Q('comments').do...
def reset(cls): """ Reset to default settings """ cls.debug = False cls.disabled = False cls.overwrite = False cls.playback_only = False cls.recv_timeout = 5 cls.recv_endmarkers = [] cls.recv_size = None
Reset to default settings
def InitializeDebuggeeLabels(self, flags): """Initialize debuggee labels from environment variables and flags. The caller passes all the flags that the the debuglet got. This function will only use the flags used to label the debuggee. Flags take precedence over environment variables. Debuggee des...
Initialize debuggee labels from environment variables and flags. The caller passes all the flags that the the debuglet got. This function will only use the flags used to label the debuggee. Flags take precedence over environment variables. Debuggee description is formatted from available flags. A...
def network_deconvolution(mat, **kwargs): """Python implementation/translation of network deconvolution by MIT-KELLIS LAB. .. note:: code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution) LICENSE: MIT-KELLIS LAB AUTHORS: Algorithm was programmed by...
Python implementation/translation of network deconvolution by MIT-KELLIS LAB. .. note:: code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution) LICENSE: MIT-KELLIS LAB AUTHORS: Algorithm was programmed by Soheil Feizi. Paper authors are S. Feizi,...
def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ domain_settings = DomainSettings.get() with root(): if os.path.exists(self.SMBCONF_FILE): os.remove(self.SMBCONF_FILE) ...
Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain
def metablock(parsed): """ Remove HTML tags, entities and superfluous characters from meta blocks. """ parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",") return escape(strip_tags(decode_entities(parsed)))
Remove HTML tags, entities and superfluous characters from meta blocks.
def scrollright(self, window_name, object_name): """ Scroll right @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's ...
Scroll right @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string ...
def compile_expression(source): """ THIS FUNCTION IS ON ITS OWN FOR MINIMAL GLOBAL NAMESPACE :param source: PYTHON SOURCE CODE :return: PYTHON FUNCTION """ # FORCE MODULES TO BE IN NAMESPACE _ = coalesce _ = listwrap _ = Date _ = convert _ = Log _ = Data _ = EMPTY...
THIS FUNCTION IS ON ITS OWN FOR MINIMAL GLOBAL NAMESPACE :param source: PYTHON SOURCE CODE :return: PYTHON FUNCTION
def eval(self, key, default=None, loc=None, correct_key=True): """Evaluates and sets the specified option value in environment `loc`. Many options need ``N`` to be defined in `loc`, some need `popsize`. Details ------- Keys that contain 'filename' are not evaluated. ...
Evaluates and sets the specified option value in environment `loc`. Many options need ``N`` to be defined in `loc`, some need `popsize`. Details ------- Keys that contain 'filename' are not evaluated. For `loc` is None, the self-dict is used as environment :See:...
def _scale(self, image, width, height): """ Does the resizing of the image """ image['options']['scale'] = '%sx%s!' % (width, height) image['size'] = (width, height) # update image size return image
Does the resizing of the image
def _get_destination_paths(self): # type: (Uploader) -> # Tuple[blobxfer.operations.azure.StorageAccount, str, str, str] """Get destination paths :param Uploader self: this :rtype: tuple :return: (storage account, container, name, dpath) """ for dst...
Get destination paths :param Uploader self: this :rtype: tuple :return: (storage account, container, name, dpath)
def ranges(self, start=None, stop=None): """Generate MappedRanges for all mapped ranges. Yields: MappedRange """ _check_start_stop(start, stop) start_loc = self._bisect_right(start) if stop is None: stop_loc = len(self._keys) else: stop_loc = self._bisect_left(stop) start_val = self._values[st...
Generate MappedRanges for all mapped ranges. Yields: MappedRange
def frombools(cls, bools=()): """Create a set from an iterable of boolean evaluable items.""" return cls.fromint(sum(compress(cls._atoms, bools)))
Create a set from an iterable of boolean evaluable items.
def execute_input_middleware_stream(self, request, controller): """ Request comes from the controller. Returned is a request. controller arg is the name of the controller. """ start_request = request # either 'http' or 'cmd' or 'irc' controller_name = "".join(cont...
Request comes from the controller. Returned is a request. controller arg is the name of the controller.
def tokenProgressFunc(state="update", action=None, text=None, tick=0): """ state: string, "update", "reading sources", "wrapping up" action: string, "stop", "start" text: string, value, additional parameter. For instance ufoname. tick: a float between 0 and 1 indicating progress. """ print("tokenProgres...
state: string, "update", "reading sources", "wrapping up" action: string, "stop", "start" text: string, value, additional parameter. For instance ufoname. tick: a float between 0 and 1 indicating progress.
def set_settings(self, releases=None, default_release=None): """set path to storage""" super(ShardedClusters, self).set_settings(releases, default_release) ReplicaSets().set_settings(releases, default_release)
set path to storage
def generation_fluctuating(self): """ Get generation time series of fluctuating renewables (only active power) Returns ------- :pandas:`pandas.DataFrame<dataframe>` See class definition for details. """ try: return self._generatio...
Get generation time series of fluctuating renewables (only active power) Returns ------- :pandas:`pandas.DataFrame<dataframe>` See class definition for details.
def create_image_summary(name, val): """ Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary: """ assert isinstance(name, six.string_types), type(name) n, h, w, c ...
Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary:
def _base_repr(self, and_also=None): """Common repr logic for subclasses to hook """ items = [ "=".join((key, repr(getattr(self, key)))) for key in sorted(self._fields.keys())] if items: output = ", ".join(items) else: output = Non...
Common repr logic for subclasses to hook
def build_arg_parser(): """ Build an argument parser using argparse. Use it when python version is 2.7 or later. """ parser = argparse.ArgumentParser(description="Smatch table calculator -- arguments") parser.add_argument("--fl", type=argparse.FileType('r'), help='AMR ID list file') parser.add_...
Build an argument parser using argparse. Use it when python version is 2.7 or later.
def calculate_trip_shape_breakpoints(conn): """Pre-compute the shape points corresponding to each trip's stop. Depends: shapes""" from gtfspy import shapes cur = conn.cursor() breakpoints_cache = {} # Counters for problems - don't print every problem. count_bad_shape_ordering = 0 coun...
Pre-compute the shape points corresponding to each trip's stop. Depends: shapes
def _decompose(net, wv_map, mems, block_out): """ Add the wires and logicnets to block_out and wv_map to decompose net """ def arg(x, i): # return the mapped wire vector for argument x, wire number i return wv_map[(net.args[x], i)] def destlen(): # return iterator over length of th...
Add the wires and logicnets to block_out and wv_map to decompose net
def split_flanks(self, _, result): """Return `result` without flanking whitespace. """ if not result.strip(): self.left, self.right = "", "" return result match = self.flank_re.match(result) assert match, "This regexp should always match" self.lef...
Return `result` without flanking whitespace.
def update_config(cls, config_file, config): """ Update configuration if needed. """ need_save = False # delete old env key if 'api' in config and 'env' in config['api']: del config['api']['env'] need_save = True # convert old ssh_key configuration entry ...
Update configuration if needed.
def _coerceSingleRepetition(self, dataSet): """ Make a new liveform with our parameters, and get it to coerce our data for us. """ # make a liveform because there is some logic in _coerced form = LiveForm(lambda **k: None, self.parameters, self.name) return form.f...
Make a new liveform with our parameters, and get it to coerce our data for us.
def os_details(): """ Returns a dictionary containing details about the operating system """ # Compute architecture and linkage bits, linkage = platform.architecture() results = { # Machine details "platform.arch.bits": bits, "platform....
Returns a dictionary containing details about the operating system
def _find_min_start(text, max_width, unicode_aware=True, at_end=False): """ Find the starting point in the string that will reduce it to be less than or equal to the specified width when displayed on screen. :param text: The text to analyze. :param max_width: The required maximum width :param a...
Find the starting point in the string that will reduce it to be less than or equal to the specified width when displayed on screen. :param text: The text to analyze. :param max_width: The required maximum width :param at_end: At the end of the editable line, so allow spaced for cursor. :return: Th...
def build_command(self, command_name, **kwargs): """build command from command_name and keyword values Returns ------- command_bitvector : list List of bitarrays. Usage ----- Receives: command name as defined inside xml file, key-value-pair...
build command from command_name and keyword values Returns ------- command_bitvector : list List of bitarrays. Usage ----- Receives: command name as defined inside xml file, key-value-pairs as defined inside bit stream filed for each command
def run_ffitch(distfile, outtreefile, intreefile=None, **kwargs): """ Infer tree branch lengths using ffitch in EMBOSS PHYLIP """ cl = FfitchCommandline(datafile=distfile, outtreefile=outtreefile, \ intreefile=intreefile, **kwargs) r, e = cl.run() if e: print("***ffitch coul...
Infer tree branch lengths using ffitch in EMBOSS PHYLIP
def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray, moderngl.Texture3D, moderngl.TextureCube]: """ Get a texture by label Args: label (str): The label for the texture to fetch Returns: ...
Get a texture by label Args: label (str): The label for the texture to fetch Returns: Texture instance
def receive(organization=None, user=None, team=None, credential_type=None, credential=None, notification_template=None, inventory_script=None, inventory=None, project=None, job_template=None, workflow=None, all=None): """Export assets from Tower. 'tower receive' exports one or more asse...
Export assets from Tower. 'tower receive' exports one or more assets from a Tower instance For all of the possible assets types the TEXT can either be the assets name (or username for the case of a user) or the keyword all. Specifying all will export all of the assets of that type.
def calculate_integral_over_T(self, T1, T2, method): r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Uses SciPy's `quad` function to perform the integral, with no options. This method can be overwritten ...
r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Uses SciPy's `quad` function to perform the integral, with no options. This method can be overwritten by subclasses who may perfer to add analytical method...
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True): """Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version ...
Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version to use. If set to 0, the library picks the smallest version that the data fits in. level...
def _all_get_or_create_table(self, where, tablename, description, expectedrows=None): """Creates a new table, or if the table already exists, returns it.""" where_node = self._hdf5file.get_node(where) if not tablename in where_node: if not expectedrows is None: table...
Creates a new table, or if the table already exists, returns it.
def create(provider, names, opts=None, **kwargs): ''' Create an instance using Salt Cloud CLI Example: .. code-block:: bash salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True ''' c...
Create an instance using Salt Cloud CLI Example: .. code-block:: bash salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
def _tilequeue_rawr_setup(cfg): """command to read from rawr queue and generate rawr tiles""" rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' rawr_postgresql_yaml = rawr_yaml.get('postgresql') assert rawr_postgresql_yaml, 'Missing rawr postgresql c...
command to read from rawr queue and generate rawr tiles
def find_string_ids(self, substring, suffix_tree_id, limit=None): """Returns a set of IDs for strings that contain the given substring. """ # Find an edge for the substring. edge, ln = self.find_substring_edge(substring=substring, suffix_tree_id=suffix_tree_id) # If there isn't...
Returns a set of IDs for strings that contain the given substring.
def correct(tokens, term_freq): """ Correct a list of tokens, according to the term_freq """ log = [] output = [] for token in tokens: corrected = _correct(token, term_freq) if corrected != token: log.append((token, corrected)) output.append(corrected) ret...
Correct a list of tokens, according to the term_freq
def position_after_whitespace(body, start_position): # type: (str, int) -> int """Reads from body starting at start_position until it finds a non-whitespace or commented character, then returns the position of that character for lexing.""" body_length = len(body) position = start_position wh...
Reads from body starting at start_position until it finds a non-whitespace or commented character, then returns the position of that character for lexing.
def b_spline_basis(x, edge_knots, n_splines=20, spline_order=3, sparse=True, periodic=True, verbose=True): """ tool to generate b-spline basis using vectorized De Boor recursion the basis functions extrapolate linearly past the end-knots. Parameters ---------- x : array-like,...
tool to generate b-spline basis using vectorized De Boor recursion the basis functions extrapolate linearly past the end-knots. Parameters ---------- x : array-like, with ndims == 1. edge_knots : array-like contaning locations of the 2 edge knots. n_splines : int. number of splines to generate....
def _ensure_channel_connected(self, destination_id): """ Ensure we opened a channel to destination_id. """ if destination_id not in self._open_channels: self._open_channels.append(destination_id) self.send_message( destination_id, NS_CONNECTION, {...
Ensure we opened a channel to destination_id.
def _read(self, ti, try_number, metadata=None): """ Endpoint for streaming log. :param ti: task instance object :param try_number: try_number of the task instance :param metadata: log metadata, can be used for steaming log reading and auto-tailing. ...
Endpoint for streaming log. :param ti: task instance object :param try_number: try_number of the task instance :param metadata: log metadata, can be used for steaming log reading and auto-tailing. :return: a list of log documents and metadata.
def remove(args): """Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys...
Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used.
def parse_quantity(string): """ Parse quantity allows to convert the value in the resources spec like: resources: requests: cpu: "100m" memory": "200Mi" limits: memory: "300Mi" :param string: str :return: float """ ...
Parse quantity allows to convert the value in the resources spec like: resources: requests: cpu: "100m" memory": "200Mi" limits: memory: "300Mi" :param string: str :return: float
def print_loop(self, sf, sftag, f=sys.stdout, file_format="nmrstar", tw=3): """Print loop into a file or stdout. :param str sf: Saveframe name. :param str sftag: Saveframe tag, i.e. field name. :param io.StringIO f: writable file-like stream. :param str file_format: Format to us...
Print loop into a file or stdout. :param str sf: Saveframe name. :param str sftag: Saveframe tag, i.e. field name. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `nmrstar` or `json`. :param int tw: Tab width. :return: None ...