code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_assessment_taken(self, assessment_taken_id): """Helper method for getting an AssessmentTaken objects given an Id.""" if assessment_taken_id not in self._assessments_taken: mgr = self._get_provider_manager('ASSESSMENT') lookup_session = mgr.get_assessment_taken_lookup_ses...
Helper method for getting an AssessmentTaken objects given an Id.
def get_next_first(intersection, intersections, to_end=True): """Gets the next node along the current (first) edge. .. note:: This is a helper used only by :func:`get_next`, which in turn is only used by :func:`basic_interior_combine`, which itself is only used by :func:`combine_intersect...
Gets the next node along the current (first) edge. .. note:: This is a helper used only by :func:`get_next`, which in turn is only used by :func:`basic_interior_combine`, which itself is only used by :func:`combine_intersections`. Along with :func:`get_next_second`, this function does th...
def psd(self): """ A pyCBC FrequencySeries holding the appropriate PSD. Return the PSD used in the metric calculation. """ if not self._psd: errMsg = "The PSD has not been set in the metricParameters " errMsg += "instance." raise ValueError(err...
A pyCBC FrequencySeries holding the appropriate PSD. Return the PSD used in the metric calculation.
def save_ds9(output, filename): """Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name. """ ds9_file = open(filename, 'wt') ds9_file.writ...
Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name.
def to_dict(self): """ Transform an attribute to a dict """ data = {} # mandatory characteristics data["name"] = self.name data["description"] = self.description if self.description and len(self.description) else None data["type"] = self.type if self.type and len...
Transform an attribute to a dict
def process_blast( blast_dir, org_lengths, fraglengths=None, mode="ANIb", identity=0.3, coverage=0.7, logger=None, ): """Returns a tuple of ANIb results for .blast_tab files in the output dir. - blast_dir - path to the directory containing .blast_tab files - org_lengths - the ba...
Returns a tuple of ANIb results for .blast_tab files in the output dir. - blast_dir - path to the directory containing .blast_tab files - org_lengths - the base count for each input sequence - fraglengths - dictionary of query sequence fragment lengths, only needed for BLASTALL output - mode - pars...
def get_users(self, fetch=True): """Return this Applications's users object, populating it if fetch is True.""" return Users(self.resource.users, self.client, populate=fetch)
Return this Applications's users object, populating it if fetch is True.
def _reset_cache(self, key=None): """ Reset cached properties. If ``key`` is passed, only clears that key. """ if getattr(self, '_cache', None) is None: return if key is None: self._cache.clear() else: self._cache.pop(key, None)
Reset cached properties. If ``key`` is passed, only clears that key.
def read(self, ncfile, timegrid_data) -> None: """Read the data from the given NetCDF file. The argument `timegrid_data` defines the data period of the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples. """ array = ...
Read the data from the given NetCDF file. The argument `timegrid_data` defines the data period of the given NetCDF file. See the general documentation on class |NetCDFVariableFlat| for some examples.
def resolve_links(self): """Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed. ...
Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed.
def QA_indicator_WR(DataFrame, N, N1): '威廉指标' HIGH = DataFrame['high'] LOW = DataFrame['low'] CLOSE = DataFrame['close'] WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) DICT = {'WR1': WR1, 'WR2': WR2} ...
威廉指标
def _import_all_modules(): """dynamically imports all modules in the package""" import traceback import os global results globals_, locals_ = globals(), locals() def load_module(modulename, package_module): try: names = [] module = __import__(package_module, glob...
dynamically imports all modules in the package
def add_console_logger(logger, level='info'): """ 增加console作为日志输入. """ logger.setLevel(getattr(logging, level.upper())) if not logger.handlers: # Set up color if we are in a tty and curses is installed color = False if curses and sys.stderr.isatty(): try: ...
增加console作为日志输入.
def remove(self): """ Remove the directory. """ lib.gp_camera_folder_remove_dir( self._cam._cam, self.parent.path.encode(), self.name.encode(), self._cam._ctx)
Remove the directory.
def transform(self, fn, dtype=None, *args, **kwargs): """Equivalent to map, compatibility purpose only. Column parameter ignored. """ rdd = self._rdd.map(fn) if dtype is None: return self.__class__(rdd, noblock=True, **self.get_params()) if dtype is np.ndarra...
Equivalent to map, compatibility purpose only. Column parameter ignored.
def get_all_sources(self): """ Returns: OrderedDict: all source file names in the hierarchy, paired with the names of their subpages. """ if self.__all_sources is None: self.__all_sources = OrderedDict() self.walk(self.__add_one) ...
Returns: OrderedDict: all source file names in the hierarchy, paired with the names of their subpages.
def parse_baxter(reading): """ Parse a Baxter string and render it with all its contents, namely initial, medial, final, and tone. """ initial = '' medial = '' final = '' tone = '' # determine environments inienv = True medienv = False finenv = False tonenv = Fa...
Parse a Baxter string and render it with all its contents, namely initial, medial, final, and tone.
def _app_cache_deepcopy(obj): """ An helper that correctly deepcopy model cache state """ if isinstance(obj, defaultdict): return deepcopy(obj) elif isinstance(obj, dict): return type(obj)((_app_cache_deepcopy(key), _app_cache_deepcopy(val)) for key, val in obj.items()) elif isin...
An helper that correctly deepcopy model cache state
def fence_point_encode(self, target_system, target_component, idx, count, lat, lng): ''' A fence point. Used to set a point when from GCS -> MAV. Also used to return a point from MAV -> GCS target_system : System ID (uint8_t) t...
A fence point. Used to set a point when from GCS -> MAV. Also used to return a point from MAV -> GCS target_system : System ID (uint8_t) target_component : Component ID (uint8_t) idx : point index (first point is...
def Var(self, mu=None): """Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance """ if mu is None: mu = self.Mean() var = 0.0...
Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance
def model(self, value): """The model property. Args: value (string). the property value. """ if value == self._defaults['ai.device.model'] and 'ai.device.model' in self._values: del self._values['ai.device.model'] else: self._values['a...
The model property. Args: value (string). the property value.
def migrate(connection, dsn): """ Collects all migrations and applies missed. Args: connection (sqlalchemy connection): """ all_migrations = _get_all_migrations() logger.debug('Collected migrations: {}'.format(all_migrations)) for version, modname in all_migrations: if _is_mis...
Collects all migrations and applies missed. Args: connection (sqlalchemy connection):
def _calculate_status(self, target_freshness, freshness): """Calculate the status of a run. :param dict target_freshness: The target freshness dictionary. It must match the freshness spec. :param timedelta freshness: The actual freshness of the data, as calculated from t...
Calculate the status of a run. :param dict target_freshness: The target freshness dictionary. It must match the freshness spec. :param timedelta freshness: The actual freshness of the data, as calculated from the database's timestamps
def from_content(cls, content): """Creates an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 25 entries per page, so in order to obtain the full highscores, all 12 pages must be parsed and merged into one. Parame...
Creates an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 25 entries per page, so in order to obtain the full highscores, all 12 pages must be parsed and merged into one. Parameters ---------- content: :c...
def carrysave_adder(a, b, c, final_adder=ripple_add): """ Adds three wirevectors up in an efficient manner :param WireVector a, b, c : the three wires to add up :param function final_adder : The adder to use to do the final addition :return: a wirevector with length 2 longer than the largest input ...
Adds three wirevectors up in an efficient manner :param WireVector a, b, c : the three wires to add up :param function final_adder : The adder to use to do the final addition :return: a wirevector with length 2 longer than the largest input
def __cache(self, file, content, document): """ Caches given file. :param file: File to cache. :type file: unicode :param content: File content. :type content: list :param document: File document. :type document: QTextDocument """ self.__...
Caches given file. :param file: File to cache. :type file: unicode :param content: File content. :type content: list :param document: File document. :type document: QTextDocument
def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()""" if self.multi: #multi parameters can be passed as parameterid=choice...
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()
def setup(level='debug', output=None): ''' Hivy formated logger ''' output = output or settings.LOG['file'] level = level.upper() handlers = [ logbook.NullHandler() ] if output == 'stdout': handlers.append( logbook.StreamHandler(sys.stdout, ...
Hivy formated logger
def gen_token(cls): """ 生成 access_token """ token = os.urandom(16) token_time = int(time.time()) return {'token': token, 'token_time': token_time}
生成 access_token
def format_result(result): """Serialise Result""" instance = None error = None if result["instance"] is not None: instance = format_instance(result["instance"]) if result["error"] is not None: error = format_error(result["error"]) result = { "success": result["success"...
Serialise Result
def __audioread_load(path, offset, duration, dtype): '''Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results. ''' y = [] with audioread.audio_open(path) as input_file: sr_native = input_file.samplerate n_channels = input_file.chann...
Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results.
def find(cls, key=None, **kwargs): """ Find an asset by key E.g. shopify.Asset.find('layout/theme.liquid', theme_id=99) """ if not key: return super(Asset, cls).find(**kwargs) params = {"asset[key]": key} params.update(kwargs) them...
Find an asset by key E.g. shopify.Asset.find('layout/theme.liquid', theme_id=99)
def ip(): """Show ip address.""" ok, err = _hack_ip() if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) click.secho(click.style(err, fg='green'))
Show ip address.
def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')): """Get a mapping of standard streams to given paths.""" # FIXME add device number too standard_inos = {} for stream in streams: try: stream_stat = os.fstat(getattr(sys, stream).fileno()) key = s...
Get a mapping of standard streams to given paths.
def sys_version(version_tuple): """ Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple """ old_version = sys.version_info sys.version_info = version_tuple yield sys.version_info = old_version
Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple
def get_content_commit_date(extensions, acceptance_callback=None, root_dir='.'): """Get the datetime for the most recent commit to a project that affected certain types of content. Parameters ---------- extensions : sequence of 'str' Extensions of files to consid...
Get the datetime for the most recent commit to a project that affected certain types of content. Parameters ---------- extensions : sequence of 'str' Extensions of files to consider in getting the most recent commit date. For example, ``('rst', 'svg', 'png')`` are content extensions ...
def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' compound = bool(re.search(r'(-| |=)', word)) syllabify = _syllabify_compound if compound else _syllabify_simplex syllabifications = list(syllabify(word)) for word, rules in rank(syllabifications): # post-proces...
Syllabify the given word, whether simplex or complex.
def list_vnets(access_token, subscription_id): '''List the VNETs in a subscription . Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VNets list with properties. ''' endpoint = '...
List the VNETs in a subscription . Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VNets list with properties.
def get_hex_color(layer_type): """ Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block. """ COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B'...
Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block.
def _get_fuzzy_tc_matches(text, full_text, options): ''' Get the options that match the full text, then from each option return only the individual words which have not yet been matched which also match the text being tab-completed. ''' print("text: {}, full: {}, options: {}".format(text, full_t...
Get the options that match the full text, then from each option return only the individual words which have not yet been matched which also match the text being tab-completed.
def remove(self): """ remove the environment """ try: self.phase = PHASE.REMOVE self.logger.info("Removing environment %s..." % self.namespace) self.instantiate_features() self._specialize() for feature in self.features.run_order: ...
remove the environment
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai ...
Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5)
def read_composite_array(fname, sep=','): r""" Convert a CSV file with header into an ArrayWrapper object. >>> from openquake.baselib.general import gettemp >>> fname = gettemp('PGA:3,PGV:2,avg:1\n' ... '.1 .2 .3,.4 .5,.6\n') >>> print(read_composite_array(fname).array) # arra...
r""" Convert a CSV file with header into an ArrayWrapper object. >>> from openquake.baselib.general import gettemp >>> fname = gettemp('PGA:3,PGV:2,avg:1\n' ... '.1 .2 .3,.4 .5,.6\n') >>> print(read_composite_array(fname).array) # array of shape (1,) [([0.1, 0.2, 0.3], [0.4, 0...
def add_btn_ok(self,label_ok): """ Adds an OK button to allow the user to exit the dialog. This widget can be triggered by setting the label ``label_ok`` to a string. This widget will be mostly centered on the screen, but below the main label by the double of it...
Adds an OK button to allow the user to exit the dialog. This widget can be triggered by setting the label ``label_ok`` to a string. This widget will be mostly centered on the screen, but below the main label by the double of its height.
def convert_csv_with_dialog_paths(csv_file): """ Converts CSV file with comma separated paths to filesystem paths. :param csv_file: :return: """ def convert_line_to_path(line): file, dir = map(lambda x: x.strip(), line.split(",")) return os.path.join(dir, file) return map(co...
Converts CSV file with comma separated paths to filesystem paths. :param csv_file: :return:
def _parse_scram_response(response): """Split a scram response into key, value pairs.""" return dict(item.split(b"=", 1) for item in response.split(b","))
Split a scram response into key, value pairs.
def _format_msg(text, width, indent=0, prefix=""): r""" Format exception message. Replace newline characters \n with ``\n``, ` with \` and then wrap text as needed """ text = repr(text).replace("`", "\\`").replace("\\n", " ``\\n`` ") sindent = " " * indent if not prefix else prefix wrap...
r""" Format exception message. Replace newline characters \n with ``\n``, ` with \` and then wrap text as needed
def insert(self, fields, typecast=False): """ Inserts a record >>> record = {'Name': 'John'} >>> airtable.insert(record) Args: fields(``dict``): Fields to insert. Must be dictionary with Column names as Key. typecast(``boolean``...
Inserts a record >>> record = {'Name': 'John'} >>> airtable.insert(record) Args: fields(``dict``): Fields to insert. Must be dictionary with Column names as Key. typecast(``boolean``): Automatic data conversion from string values. Retu...
def from_args(cls, args, project_profile_name=None): """Given the raw profiles as read from disk and the name of the desired profile if specified, return the profile component of the runtime config. :param args argparse.Namespace: The arguments as parsed from the cli. :param pro...
Given the raw profiles as read from disk and the name of the desired profile if specified, return the profile component of the runtime config. :param args argparse.Namespace: The arguments as parsed from the cli. :param project_profile_name Optional[str]: The profile name, if ...
def start(self): """Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` metho...
Start the component's event loop (thread-safe). After the event loop is started the Qt thread calls the component's :py:meth:`~Component.start_event` method, then calls its :py:meth:`~Component.new_frame_event` and :py:meth:`~Component.new_config_event` methods as required until ...
def format_command( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """ Format command information for logging. """ text = 'Command arguments: {}\n'.format(command_args) if not command_output: text += 'Command output: None' elif logger.g...
Format command information for logging.
def subset(args): """ %prog subset blastfile qbedfile sbedfile Extract blast hits between given query and subject chrs. If --qchrs or --schrs is not given, then all chrs from q/s genome will be included. However one of --qchrs and --schrs must be specified. Otherwise the script will do nothing...
%prog subset blastfile qbedfile sbedfile Extract blast hits between given query and subject chrs. If --qchrs or --schrs is not given, then all chrs from q/s genome will be included. However one of --qchrs and --schrs must be specified. Otherwise the script will do nothing.
def write(self, chunk, offset): """ Write chunk to file at specified position Return 0 if OK, else -1 """ return lib.zfile_write(self._as_parameter_, chunk, offset)
Write chunk to file at specified position Return 0 if OK, else -1
def pywt_wavelet(wavelet): """Convert ``wavelet`` to a `pywt.Wavelet` instance.""" if isinstance(wavelet, pywt.Wavelet): return wavelet else: return pywt.Wavelet(wavelet)
Convert ``wavelet`` to a `pywt.Wavelet` instance.
def get_stream_url(self, session_id, stream_id=None): """ this method returns the url to get streams information """ url = self.api_url + '/v2/project/' + self.api_key + '/session/' + session_id + '/stream' if stream_id: url = url + '/' + stream_id return url
this method returns the url to get streams information
def insert(self, index, p_object): """ Insert an element to a list """ validated_value = self.get_validated_object(p_object) if validated_value is not None: self.__modified_data__.insert(index, validated_value)
Insert an element to a list
def _clone(self, cid): """ Create a temporary image snapshot from a given cid. Temporary image snapshots are marked with a sentinel label so that they can be cleaned on unmount. """ try: iid = self.client.commit( container=cid, ...
Create a temporary image snapshot from a given cid. Temporary image snapshots are marked with a sentinel label so that they can be cleaned on unmount.
def wrap_rtx(packet, payload_type, sequence_number, ssrc): """ Create a retransmission packet from a lost packet. """ rtx = RtpPacket( payload_type=payload_type, marker=packet.marker, sequence_number=sequence_number, timestamp=packet.timestamp, ssrc=ssrc, ...
Create a retransmission packet from a lost packet.
def change_type(self, bucket, key, storage_type): """修改文件的存储类型 修改文件的存储类型为普通存储或者是低频存储,参考文档: https://developer.qiniu.com/kodo/api/3710/modify-the-file-type Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 storage_type: 待操作资源存储类型,0为普通存储,1为低频存储...
修改文件的存储类型 修改文件的存储类型为普通存储或者是低频存储,参考文档: https://developer.qiniu.com/kodo/api/3710/modify-the-file-type Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 storage_type: 待操作资源存储类型,0为普通存储,1为低频存储
def receive_external(self, http_verb, host, url, http_headers): """ Retrieve a streaming request for a file. :param http_verb: str GET is only supported right now :param host: str host we are requesting the file from :param url: str url to ask the host for :param http_hea...
Retrieve a streaming request for a file. :param http_verb: str GET is only supported right now :param host: str host we are requesting the file from :param url: str url to ask the host for :param http_headers: object headers to send with the request :return: requests.Response con...
def cheat(num): """View the answer to a problem.""" # Define solution before echoing in case solution does not exist solution = click.style(Problem(num).solution, bold=True) click.confirm("View answer to problem %i?" % num, abort=True) click.echo("The answer to problem {} is {}.".format(num, solutio...
View the answer to a problem.
def write_tsv(self, path): """Write the database to a tab-delimited text file. Parameters ---------- path: str The path name of the file. Returns ------- None """ with open(path, 'wb') as ofh: writer = csv.writer( ...
Write the database to a tab-delimited text file. Parameters ---------- path: str The path name of the file. Returns ------- None
def external_commands(self): """Get the external commands from the daemon Use a lock for this function to protect :return: serialized external command list :rtype: str """ res = [] with self.app.external_commands_lock: for cmd in self.app.get_externa...
Get the external commands from the daemon Use a lock for this function to protect :return: serialized external command list :rtype: str
def linspace2(a, b, n, dtype=None): """similar to numpy.linspace but excluding the boundaries this is the normal numpy.linspace: >>> print linspace(0,1,5) [ 0. 0.25 0.5 0.75 1. ] and this gives excludes the boundaries: >>> print linspace2(0,1,5) [ 0.1 0.3 0.5 0.7 0.9] """...
similar to numpy.linspace but excluding the boundaries this is the normal numpy.linspace: >>> print linspace(0,1,5) [ 0. 0.25 0.5 0.75 1. ] and this gives excludes the boundaries: >>> print linspace2(0,1,5) [ 0.1 0.3 0.5 0.7 0.9]
def serialize( self, value, # type: Any state # type: _ProcessorState ): # type: (...) -> ET.Element """Serialize the value into a new Element object and return it.""" if self._nested is None: state.raise_error(InvalidRootProcessor, ...
Serialize the value into a new Element object and return it.
def clean_axis(axis): """Remove ticks, tick labels, and frame from axis""" axis.get_xaxis().set_ticks([]) axis.get_yaxis().set_ticks([]) for spine in list(axis.spines.values()): spine.set_visible(False)
Remove ticks, tick labels, and frame from axis
def load_from_stream(self, stream, container, **opts): """ :param stream: XML file or file-like object :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters """ ...
:param stream: XML file or file-like object :param container: callble to make a container object :param opts: optional keyword parameters to be sanitized :return: Dict-like object holding config parameters
def square_distance(a: Square, b: Square) -> int: """ Gets the distance (i.e., the number of king steps) from square *a* to *b*. """ return max(abs(square_file(a) - square_file(b)), abs(square_rank(a) - square_rank(b)))
Gets the distance (i.e., the number of king steps) from square *a* to *b*.
def script_current_send(self, seq, force_mavlink1=False): ''' This message informs about the currently active SCRIPT. seq : Active Sequence (uint16_t) ''' return self.send(self.script_current_encode(seq), force_mavli...
This message informs about the currently active SCRIPT. seq : Active Sequence (uint16_t)
def chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default format...
chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default formatting rules. (e.g: "Hello world") `timestamp`: Timestamp of the me...
def _as_rdf_xml(self, ns): """ Return identity details for the element as XML nodes """ self.rdf_identity = self._get_identity(ns) elements = [] elements.append(ET.Element(NS('sbol', 'persistentIdentity'), attrib={NS('rdf', 'resource'): ...
Return identity details for the element as XML nodes
def dump(self): """Serialize a test case to a string.""" result = list(self.output_lines()) if self.locked: result.append('# locked') if self.choices: for choice in self.choices: result.append('# choice: ' + choice) if self.expl...
Serialize a test case to a string.
def password_hash(password): """Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str """ try: return bcrypt_sha256.encrypt(password) except TypeError: return bcrypt_sha256.encrypt...
Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password hash :rtype: str
def sill(self): """ get the sill of the GeoStruct Return ------ sill : float the sill of the (nested) GeoStruct, including nugget and contribution from each variogram """ sill = self.nugget for v in self.variograms: sill += v.c...
get the sill of the GeoStruct Return ------ sill : float the sill of the (nested) GeoStruct, including nugget and contribution from each variogram
def getByTime(self, startTime=None, endTime=None): """ :desc: Get all the notes in the given time window :param int startTime: The begining of the window :param int endTime: The end of the window :returns: A list of IDs :ravl: list """ ...
:desc: Get all the notes in the given time window :param int startTime: The begining of the window :param int endTime: The end of the window :returns: A list of IDs :ravl: list
def firsttime(self): """ sets it as already done""" self.config.set('DEFAULT', 'firsttime', 'no') if self.cli_config.getboolean('core', 'collect_telemetry', fallback=False): print(PRIVACY_STATEMENT) else: self.cli_config.set_value('core', 'collect_telemetry', ask_...
sets it as already done
def GetRemainder(self): """Method to get the remainder of the buffered XML. this method stops the parser, set its state to End Of File and return the input stream with what is left that the parser did not use. The implementation is not good, the parser certainly procgres...
Method to get the remainder of the buffered XML. this method stops the parser, set its state to End Of File and return the input stream with what is left that the parser did not use. The implementation is not good, the parser certainly procgressed past what's left in reader->inp...
def get_ticker(self, symbol=None): """Get symbol tick https://docs.kucoin.com/#get-ticker :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python all_ticks = client.get_ticker() ticker = client.get_ticker('ETH-BTC')...
Get symbol tick https://docs.kucoin.com/#get-ticker :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python all_ticks = client.get_ticker() ticker = client.get_ticker('ETH-BTC') :returns: ApiResponse .. co...
def _disconnect(self, mqttc, userdata, rc): """ The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anyt...
The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: The private userdata for the mqtt client. Not used in Polyglot :param rc: Result code of connection, 0 = Graceful, anything else is unclean
def get_requests(self): """Get all the new requests that were found in the response. Returns: list(:class:`nyawc.http.Request`): A list of new requests that were found. """ requests = self.derived_get_requests() for request in requests: request.url = U...
Get all the new requests that were found in the response. Returns: list(:class:`nyawc.http.Request`): A list of new requests that were found.
def build_request(self, input_data=None, *args, **kwargs): """ Builds request :param input_data: :param args: :param kwargs: :return: """ if input_data is not None: self.input_data = input_data if self.input_data is None: r...
Builds request :param input_data: :param args: :param kwargs: :return:
def chunks(iterable, size): """ Splits a very large list into evenly sized chunks. Returns an iterator of lists that are no more than the size passed in. """ it = iter(iterable) item = list(islice(it, size)) while item: yield item item = list(islice(it, size))
Splits a very large list into evenly sized chunks. Returns an iterator of lists that are no more than the size passed in.
def spectrum(self, function='geoid', lmax=None, unit='per_l', base=10.): """ Return the spectrum as a function of spherical harmonic degree. Usage ----- spectrum, [error_spectrum] = x.spectrum([function, lmax, unit, base]) Returns ------- spectrum : ndar...
Return the spectrum as a function of spherical harmonic degree. Usage ----- spectrum, [error_spectrum] = x.spectrum([function, lmax, unit, base]) Returns ------- spectrum : ndarray, shape (lmax+1) 1-D numpy ndarray of the spectrum, where lmax is the maximum ...
def _clean_up_columns( self): """clean up columns .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check subli...
clean up columns .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text ...
def lpc(blk, order=None): """ Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object, the analysis whitening filter. This implementation uses the autocorrelation method, using the Levinson-Durbin algorithm or Numpy pseudo-inverse for linear system solving, when needed. Parameters ------...
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object, the analysis whitening filter. This implementation uses the autocorrelation method, using the Levinson-Durbin algorithm or Numpy pseudo-inverse for linear system solving, when needed. Parameters ---------- blk : An iterable with ...
def upgradeShare1to2(oldShare): "Upgrader from Share version 1 to version 2." sharedInterfaces = [] attrs = set(oldShare.sharedAttributeNames.split(u',')) for iface in implementedBy(oldShare.sharedItem.__class__): if set(iface) == attrs or attrs == set('*'): sharedInterfaces.append(i...
Upgrader from Share version 1 to version 2.
def setObsoletedBy(self, pid, obsoletedByPid, serialVersion, vendorSpecific=None): """See Also: setObsoletedByResponse() Args: pid: obsoletedByPid: serialVersion: vendorSpecific: Returns: """ response = self.setObsoletedByResponse( ...
See Also: setObsoletedByResponse() Args: pid: obsoletedByPid: serialVersion: vendorSpecific: Returns:
def set_roots(self, uproot_with=None): ''' Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable ''' # Check for TREE_DIR self.treedir = os.envir...
Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable
def write(self, args): # pylint: disable=no-self-use """ writes the progres """ ShellProgressView.done = False message = args.get('message', '') percent = args.get('percent', None) if percent: ShellProgressView.progress_bar = _format_value(message, percent) ...
writes the progres
def like_shared_file(self, sharekey=None): """ 'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str): Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exceptio...
'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str): Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exception on error.
def complete_info(self, text, line, begidx, endidx): """completion for info command""" opts = self.INFO_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(text) ...
completion for info command
def dlabfs(handle): """ Begin a forward segment search in a DLA file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dlabfs_c.html :param handle: Handle of open DLA file. :type handle: int :return: Descriptor of next segment in DLA file :rtype: spiceypy.utils.support_type...
Begin a forward segment search in a DLA file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dlabfs_c.html :param handle: Handle of open DLA file. :type handle: int :return: Descriptor of next segment in DLA file :rtype: spiceypy.utils.support_types.SpiceDLADescr
def extended_analog(self, pin, data): """ This method will send an extended-data analog write command to the selected pin.. :param pin: 0 - 127 :param data: 0 - 0-0x4000 (14 bits) :returns: No return value """ task = asyncio.ensure_future(self.core.exte...
This method will send an extended-data analog write command to the selected pin.. :param pin: 0 - 127 :param data: 0 - 0-0x4000 (14 bits) :returns: No return value
def serialize_formula(formula): r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- ...
r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula strin...
def optional(validator): """ A validator that makes an attribute optional. An optional attribute is one which can be set to ``None`` in addition to satisfying the requirements of the sub-validator. :param validator: A validator (or a list of validators) that is used for non-``None`` values...
A validator that makes an attribute optional. An optional attribute is one which can be set to ``None`` in addition to satisfying the requirements of the sub-validator. :param validator: A validator (or a list of validators) that is used for non-``None`` values. :type validator: callable or :c...
def equivalent(kls, first, second): """ Tests that two skeletons are the same in form not merely that their array contents are exactly the same. This test can be made more sophisticated. """ if first.empty() and second.empty(): return True elif first.vertices.shape[0] != second.vertic...
Tests that two skeletons are the same in form not merely that their array contents are exactly the same. This test can be made more sophisticated.
def check_var_units(self, ds): ''' Checks each applicable variable for the units attribute :param netCDF4.Dataset ds: An open netCDF dataset ''' results = [] for variable in self.get_applicable_variables(ds): msgs = [] # Check units and dims for v...
Checks each applicable variable for the units attribute :param netCDF4.Dataset ds: An open netCDF dataset
def get_histogram_bins(min_, max_, std, count): """ Return optimal bins given the input parameters """ width = _get_bin_width(std, count) count = int(round((max_ - min_) / width) + 1) if count: bins = [i * width + min_ for i in xrange(1, count + 1)] else: bins = [min_] ...
Return optimal bins given the input parameters
def node_validate(node_dict, node_num, cmd_name): """Validate that command can be performed on target node.""" # cmd: [required-state, action-to-displayed, error-statement] req_lu = {"run": ["stopped", "Already Running"], "stop": ["running", "Already Stopped"], "connect": ["runni...
Validate that command can be performed on target node.
def NRMSE_sliding(data, pred, windowSize): """ Computing NRMSE in a sliding window :param data: :param pred: :param windowSize: :return: (window_center, NRMSE) """ halfWindowSize = int(round(float(windowSize)/2)) window_center = range(halfWindowSize, len(data)-halfWindowSize, int(round(float(halfWind...
Computing NRMSE in a sliding window :param data: :param pred: :param windowSize: :return: (window_center, NRMSE)