code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _clean_block(response_dict): ''' Pythonize a blockcypher API response ''' response_dict['received_time'] = parser.parse(response_dict['received_time']) response_dict['time'] = parser.parse(response_dict['time']) return response_dict
Pythonize a blockcypher API response
def get_locale_choices(locale_dir): """ Get a list of locale file names in the given locale dir. """ #/ file_name_s = os.listdir(locale_dir) #/ choice_s = [] for file_name in file_name_s: if file_name.endswith(I18n.TT_FILE_EXT...
Get a list of locale file names in the given locale dir.
def itemComment(self, commentId): """ returns details of a single comment """ url = "%s/comments/%s" % (self.root, commentId) params = { "f": "json" } return self._get(url, params, securityHandler=self._securityH...
returns details of a single comment
def translate(self, content): """ Translate using the XSD type information. Python I{dict} is translated to a suds object. Most importantly, primative values are translated from python types to XML types using the XSD type. @param content: The content to translate. ...
Translate using the XSD type information. Python I{dict} is translated to a suds object. Most importantly, primative values are translated from python types to XML types using the XSD type. @param content: The content to translate. @type content: L{Object} @return: self ...
def analyze(self, handle, filename): """Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: Task ID as a string """ ...
Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: Task ID as a string
def AgregarBonificacionPenalizacion(self, codigo, detalle, resultado=None, porcentaje=None, importe=None, **kwargs): "Agrega la información referente a las bonificaciones o penalizaciones" ret = dict(codBonificacionPenalizacion=codigo, detalle=detalle, ...
Agrega la información referente a las bonificaciones o penalizaciones
def read_dna(path): '''Read DNA from file. Uses BioPython and coerces to coral format. :param path: Full path to input file. :type path: str :returns: DNA sequence. :rtype: coral.DNA ''' filename, ext = os.path.splitext(os.path.split(path)[-1]) genbank_exts = ['.gb', '.ape'] fasta...
Read DNA from file. Uses BioPython and coerces to coral format. :param path: Full path to input file. :type path: str :returns: DNA sequence. :rtype: coral.DNA
def update_extent_location(self, extent_loc): # type: (int) -> None ''' A method to update the extent location for this Path Table Record. Parameters: extent_loc - The new extent location. Returns: Nothing. ''' if not self._initialized: ...
A method to update the extent location for this Path Table Record. Parameters: extent_loc - The new extent location. Returns: Nothing.
def flip(a, axis): """Reverse the order of elements in an array along the given axis. This function is a backport of `numpy.flip` introduced in NumPy 1.12. See Also -------- numpy.flip """ if not hasattr(a, 'ndim'): a = np.asarray(a) indexer = [slice(None)] * a.ndim try: ...
Reverse the order of elements in an array along the given axis. This function is a backport of `numpy.flip` introduced in NumPy 1.12. See Also -------- numpy.flip
def clear(self): """ convinience function to empty this fastrun container """ self.prop_dt_map = dict() self.prop_data = dict() self.rev_lookup = defaultdict(set)
convinience function to empty this fastrun container
def delete(self, subject): """ :type subject: subject_abcs.Subject """ session = subject.get_session(False) if (session): session.remove_internal_attribute(self.dsc_ask) session.remove_internal_attribute(self.dsc_isk)
:type subject: subject_abcs.Subject
def check_directories(self): """ Creates base directories for app, virtualenv, and nginx """ self.log.debug('Checking directories') if not os.path.exists(self._ve_dir): os.makedirs(self._ve_dir) if not os.path.exists(self._app_dir): os.makedirs(se...
Creates base directories for app, virtualenv, and nginx
def clean_key(cls, key): """ Replace things that look like variables with a '#' so tests aren't affected by random variables """ for var_re in cls.VARIABLE_RES: key = var_re.sub('#', key) return key
Replace things that look like variables with a '#' so tests aren't affected by random variables
def register_periodic_tasks(self, tasks: Iterable[Task]): """Register tasks that need to be scheduled periodically.""" for task in tasks: self._scheduler.enter( int(task.periodicity.total_seconds()), 0, self._schedule_periodic_task, ...
Register tasks that need to be scheduled periodically.
def receive(self, decode=True): """ Receive from socket, authenticate and decode payload """ payload = self.socket.recv() payload = self.verify(payload) if decode: payload = self.decode(payload) return payload
Receive from socket, authenticate and decode payload
def hline_score(self, y, xmin, xmax): """Returns the number of unbroken paths of qubits >>> [(x,y,0,k) for x in range(xmin,xmax+1)] for :math:`k = 0,1,\cdots,L-1`. This is precomputed for speed. """ return self._hline_score[y, xmin, xmax]
Returns the number of unbroken paths of qubits >>> [(x,y,0,k) for x in range(xmin,xmax+1)] for :math:`k = 0,1,\cdots,L-1`. This is precomputed for speed.
def call_for_nodes(node, callback, recursive=False): """If callback returns `True` the child nodes are skipped""" result = callback(node) if recursive and not result: for child in get_child_nodes(node): call_for_nodes(child, callback, recursive)
If callback returns `True` the child nodes are skipped
def to_string(self, format_, fps=None, **kwargs): """ Get subtitle file as a string. See :meth:`SSAFile.save()` for full description. Returns: str """ fp = io.StringIO() self.to_file(fp, format_, fps=fps, **kwargs) return fp.getvalue()
Get subtitle file as a string. See :meth:`SSAFile.save()` for full description. Returns: str
def lifting_condensation_level(T, RH): '''Compute the Lifiting Condensation Level (LCL) for a given temperature and relative humidity Inputs: T is temperature in Kelvin RH is relative humidity (dimensionless) Output: LCL in meters This is height (relative to parcel height) at which the p...
Compute the Lifiting Condensation Level (LCL) for a given temperature and relative humidity Inputs: T is temperature in Kelvin RH is relative humidity (dimensionless) Output: LCL in meters This is height (relative to parcel height) at which the parcel would become saturated during adiabatic ...
def set_columns(self, columns): """Set edge line columns values.""" if isinstance(columns, tuple): self.columns = columns elif is_text_string(columns): self.columns = tuple(int(e) for e in columns.split(',')) self.update()
Set edge line columns values.
def cmd(): '''Handler for command line invocation''' # Try to handle any reasonable thing thrown at this. # Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout # and treat any subsequent arguments as a space separated string to # be titlecased (so it still works if people forget quote...
Handler for command line invocation
def get_provider_info(self, user_descriptor): """GetProviderInfo. [Preview API] :param str user_descriptor: :rtype: :class:`<GraphProviderInfo> <azure.devops.v5_0.graph.models.GraphProviderInfo>` """ route_values = {} if user_descriptor is not None: ro...
GetProviderInfo. [Preview API] :param str user_descriptor: :rtype: :class:`<GraphProviderInfo> <azure.devops.v5_0.graph.models.GraphProviderInfo>`
def _num2deg(self, tile): """ Taken from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Python """ n = 2.0 ** tile.zoom lon_deg = tile.x / n * 360.0 - 180.0 lat_rad = mod_math.atan(mod_math.sinh(mod_math.pi * (1 - 2 * tile.y / n))) lat_deg = mod_math.degrees(lat_rad) ...
Taken from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Python
def delete(self, **kwargs): """ Removes this app object from the platform. The current user must be a developer of the app. """ if self._dxid is not None: return dxpy.api.app_delete(self._dxid, **kwargs) else: return dxpy.api.app_delete('app-' + s...
Removes this app object from the platform. The current user must be a developer of the app.
def unset_key(dotenv_path, key_to_unset, quote_mode="always"): """ Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails """ if not os.path.exists(dotenv_path): warnings.warn("can't delete from %s - it doesn...
Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails
def _extract_file(self, tgz, tarinfo, dst_path, buffer_size=10<<20): """Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'.""" src = tgz.extractfile(tarinfo) dst = tf_v1.gfile.GFile(dst_path, "wb") while 1: buf = src.read(buffer_size) if not buf: break dst.write(buf) ...
Extracts 'tarinfo' from 'tgz' and writes to 'dst_path'.
def remove_all_annotations_from_tier(self, id_tier, clean=True): """remove all annotations from a tier :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent. """ for aid in self.tiers[id_tier][0]: del(self.annotations[aid]) for a...
remove all annotations from a tier :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent.
def _get_odoo_version_info(addons_dir, odoo_version_override=None): """ Detect Odoo version from an addons directory """ odoo_version_info = None addons = os.listdir(addons_dir) for addon in addons: addon_dir = os.path.join(addons_dir, addon) if is_installable_addon(addon_dir): ...
Detect Odoo version from an addons directory
def clear_cached_realms(self, realms, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the ...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the cache
def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0): """ Return batch of frames for given indexes """ if forward_steps > 1: transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor) else...
Return batch of frames for given indexes
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 4.1.0 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 4.1.0 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
def setup(): """ Call this before using the refactoring tools to create them on demand if needed. """ if None in [RTs._rt, RTs._rtp]: RTs._rt = RefactoringTool(myfixes) RTs._rtp = RefactoringTool(myfixes, {'print_function': True})
Call this before using the refactoring tools to create them on demand if needed.
def divmod_neg(a, b): """Return divmod with closest result to zero""" q, r = divmod(a, b) # make sure r is close to zero sr = np.sign(r) if np.abs(r) > b/2: q += sr r -= b * sr return q, r
Return divmod with closest result to zero
def _update_ret(ret, goids, go2color): """Update 'GOs' and 'go2color' in dict with goids and go2color.""" if goids: ret['GOs'].update(goids) if go2color: for goid, color in go2color.items(): ret['go2color'][goid] = color
Update 'GOs' and 'go2color' in dict with goids and go2color.
def expand_env_variables(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Replace all environment variables that can be retrieved via `os.getenv`. The only allowed format for environment variables defined in the requirement file is `${MY_VARIABLE_1}` to ensure two things: 1. Strings that con...
Replace all environment variables that can be retrieved via `os.getenv`. The only allowed format for environment variables defined in the requirement file is `${MY_VARIABLE_1}` to ensure two things: 1. Strings that contain a `$` aren't accidentally (partially) expanded. 2. Ensure consistency across pl...
def format_info_response(value): """Format the response from redis :param str value: The return response from redis :rtype: dict """ info = {} for line in value.decode('utf-8').splitlines(): if not line or line[0] == '#': continue if ':' in line: key, va...
Format the response from redis :param str value: The return response from redis :rtype: dict
def _lazy_load_units_by_code(): """Populate dict of units by code iff UNITS_BY_CODE is empty.""" if UNITS_BY_CODE: # already populated return for unit in units.UNITS_BY_NAME.values(): UNITS_BY_CODE[unit.code] = unit
Populate dict of units by code iff UNITS_BY_CODE is empty.
def block(self, userId, minute): """ 封禁用户方法(每秒钟限 100 次) 方法 @param userId:用户 Id。(必传) @param minute:封禁时长,单位为分钟,最大值为43200分钟。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslut", "desc": ...
封禁用户方法(每秒钟限 100 次) 方法 @param userId:用户 Id。(必传) @param minute:封禁时长,单位为分钟,最大值为43200分钟。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
def remove_context(self, name): """Remove a context from kubeconfig. """ context = self.get_context(name) contexts = self.get_contexts() contexts.remove(context)
Remove a context from kubeconfig.
def explain(code, signals=SIGNALS): """ Explain what a given integer signal *code* does, including it's signal name. :param code: An integer signal. :param signals: A database of signals. """ if code not in signals: raise NoSuchSignal(code) signal, action, description = signals[...
Explain what a given integer signal *code* does, including it's signal name. :param code: An integer signal. :param signals: A database of signals.
def start_plugins(conf, watcher_plugin_class, health_plugin_class, sleep_time): """ Start the working threads: - Health monitor (the health plugin) - Config change monitor (the watcher plugin) """ # No matter what the chosen plugin to watch for config updates: We get a # ...
Start the working threads: - Health monitor (the health plugin) - Config change monitor (the watcher plugin)
def add_dictionary(self, dictionary): """ Supply a word-id dictionary to allow similarity queries. """ if self.word_vectors is None: raise Exception('Model must be fit before adding a dictionary') if len(dictionary) > self.word_vectors.shape[0]: raise Ex...
Supply a word-id dictionary to allow similarity queries.
def complete_tags(arg): """ Complete NIPAP prefix type """ search_string = '^' if arg is not None: search_string += arg res = Tag.search({ 'operator': 'regex_match', 'val1': 'name', 'val2': search_string }) ret = [] for t in res['result']: ret.ap...
Complete NIPAP prefix type
def import_settings(self, filename): '''Import settings from a JSON file Args: filename (string): name of the file to import from ''' if not os.path.isfile(filename): self._logger.log( 'error', 'File: {} not found, continuing with...
Import settings from a JSON file Args: filename (string): name of the file to import from
def _multicomplex2(f, fx, x, h): """Calculate Hessian with Bicomplex-step derivative approximation""" n = len(x) ee = np.diag(h) hess = np.outer(h, h) cmplx_wrap = Bicomplex.__array_wrap__ for i in range(n): for j in range(i, n): zph = Bicomple...
Calculate Hessian with Bicomplex-step derivative approximation
def run(command, num_retries=1, timeout=-1, **kwargs): """ Run a command with optional timeout and retries. Provides a convenience method for executing a subprocess with additional error handling. Arguments: command (list of str): The command to execute. num_retries (int, optional)...
Run a command with optional timeout and retries. Provides a convenience method for executing a subprocess with additional error handling. Arguments: command (list of str): The command to execute. num_retries (int, optional): If the subprocess fails, the number of attempts to exec...
def _add_sequence(self, pdbID, chainID, sequence): '''This is a 'private' function. If you call it directly, call _find_identical_sequences() afterwards to update identical_sequences.''' pdbID = pdbID.upper() self[pdbID] = self.get(pdbID, {}) self[pdbID][chainID] = sequence self....
This is a 'private' function. If you call it directly, call _find_identical_sequences() afterwards to update identical_sequences.
def delay(self, n, start_time): """Calculate delay before the next retry. Args: n: the number of current attempt. The first attempt should be 1. start_time: the time when retry started in unix time. Returns: Number of seconds to wait before next retry. -1 if retry should give up. """...
Calculate delay before the next retry. Args: n: the number of current attempt. The first attempt should be 1. start_time: the time when retry started in unix time. Returns: Number of seconds to wait before next retry. -1 if retry should give up.
def print_factoids(input_dict, environment_dict): """ <Purpose> Used to print seash factoids when user uses 'show factoids' command. <Arguments> input_dict: Input dictionary generated by seash_dictionary.parse_command(). environment_dict: Dictionary describing the current seash enviro...
<Purpose> Used to print seash factoids when user uses 'show factoids' command. <Arguments> input_dict: Input dictionary generated by seash_dictionary.parse_command(). environment_dict: Dictionary describing the current seash environment. For more information, see command_callback...
def include_revision(revision_num, skip_factor=1.1): """Decide whether to include a revision. If the number of revisions is large, we exclude some revisions to avoid a quadratic blowup in runtime, since the article is likely also large. We make the ratio between consecutive included revision numbers appprox...
Decide whether to include a revision. If the number of revisions is large, we exclude some revisions to avoid a quadratic blowup in runtime, since the article is likely also large. We make the ratio between consecutive included revision numbers appproximately equal to "factor". Args: revision_num: an i...
def get_scheme(self): """When Splunk starts, it looks for all the modular inputs defined by its configuration, and tries to run them with the argument --scheme. Splunkd expects the modular inputs to print a description of the input in XML on stdout. The modular input framework takes care...
When Splunk starts, it looks for all the modular inputs defined by its configuration, and tries to run them with the argument --scheme. Splunkd expects the modular inputs to print a description of the input in XML on stdout. The modular input framework takes care of all the details of fo...
def exists(self, relpath): """Returns True if path exists and is not ignored.""" if self.isignored(self._append_slash_if_dir_path(relpath)): return False return self._exists_raw(relpath)
Returns True if path exists and is not ignored.
def get_option_help_info(self, args, kwargs): """Returns an OptionHelpInfo for the option registered with the given (args, kwargs).""" display_args = [] scoped_cmd_line_args = [] unscoped_cmd_line_args = [] for arg in args: is_short_arg = len(arg) == 2 unscoped_cmd_line_args.append(arg)...
Returns an OptionHelpInfo for the option registered with the given (args, kwargs).
def main(args=None): """ Main entry point """ # parse args if args is None: args = parse_args(sys.argv[1:]) # dump example config if that action if args.action == 'example-config': conf, doc = Config.example_config() print(conf) sys.stderr.write(doc + "\n") ...
Main entry point
def delete_entry_tag(sender, instance, **kwargs): """ Deletes EntryTag for Entry corresponding to specified TaggedItemBase instance. :param sender: the sending TaggedItemBase class. :param instance: the TaggedItemBase instance. """ from ..models import ( Entry, EntryTag ...
Deletes EntryTag for Entry corresponding to specified TaggedItemBase instance. :param sender: the sending TaggedItemBase class. :param instance: the TaggedItemBase instance.
def resolve_sid(sid): """Get the PID to which the ``sid`` currently maps. Preconditions: - ``sid`` is verified to exist. E.g., with d1_gmn.app.views.asserts.is_sid(). """ return d1_gmn.app.models.Chain.objects.get(sid__did=sid).head_pid.did
Get the PID to which the ``sid`` currently maps. Preconditions: - ``sid`` is verified to exist. E.g., with d1_gmn.app.views.asserts.is_sid().
def iter_events(self, number=-1): """Iterate over events associated with this issue only. :param int number: (optional), number of events to return. Default: -1 returns all events available. :returns: generator of :class:`IssueEvent <github3.issues.event.IssueEvent>`\ s ...
Iterate over events associated with this issue only. :param int number: (optional), number of events to return. Default: -1 returns all events available. :returns: generator of :class:`IssueEvent <github3.issues.event.IssueEvent>`\ s
def _svgcolor(color): """ Convert a PyChart color object to an SVG rgb() value. See color.py. """ return 'rgb(%d,%d,%d)' % tuple([int(255 * x) for x in [color.r, color.g, color.b]])
Convert a PyChart color object to an SVG rgb() value. See color.py.
def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(StatsiteHandler, self).get_default_config_help() config.update({ 'host': '', 'tcpport': '', 'udpport': '', ...
Returns the help text for the configuration options for this handler
def initauth(self): """Initialise authentication, for internal use""" headers = {'User-agent': 'CLAMClientAPI-' + clam.common.data.VERSION} if self.oauth: if not self.oauth_access_token: r = requests.get(self.url,headers=headers, verify=self.verify) if...
Initialise authentication, for internal use
def parse_expression(self, expr): """ split expression into prefix and expression tested with ``` operator== != std::rel_ops::operator!= std::atomic::operator= std::array::operator[] std::function::operat...
split expression into prefix and expression tested with ``` operator== != std::rel_ops::operator!= std::atomic::operator= std::array::operator[] std::function::operator() std::vector::at std::relation...
def filter_query(self, query, filter_info, model): """Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :return Query...
Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :return Query: the sorted query
def _rc_dbsize(self): "Returns the number of keys in the current database" result = 0 for alias, redisent in iteritems(self.redises): if alias.find('_slave') == -1: continue result += redisent.dbsize() return result
Returns the number of keys in the current database
def _create_element_list_(self): """ Extract an alphabetically sorted list of elements from the compounds of the material. :returns: An alphabetically sorted list of elements. """ element_set = stoich.elements(self.compounds) return sorted(list(element_set))
Extract an alphabetically sorted list of elements from the compounds of the material. :returns: An alphabetically sorted list of elements.
def es_indexers(cls, base_class=None, role='rdf_class', **kwargs): """ Returns the es mapping for the class args: ----- base_class: The root class being indexed role: the role states how the class should be mapped depending upon whether it is used as a ...
Returns the es mapping for the class args: ----- base_class: The root class being indexed role: the role states how the class should be mapped depending upon whether it is used as a subject of an object. options are es_Nested or rdf_class
async def del_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT): """ Remove the specified Data-ID from the list of alternative commands. Only one occurrence is deleted. If the Data-ID appears multiple times in the list of alternative commands, this command must be repeated to ...
Remove the specified Data-ID from the list of alternative commands. Only one occurrence is deleted. If the Data-ID appears multiple times in the list of alternative commands, this command must be repeated to delete all occurrences. The table of alternative Data-IDs is stored in non-volat...
def _next_radiotap_extpm(pkt, lst, cur, s): """Generates the next RadioTapExtendedPresenceMask""" if cur is None or (cur.present and cur.present.Ext): st = len(lst) + (cur is not None) return lambda *args: RadioTapExtendedPresenceMask(*args, index=st) return None
Generates the next RadioTapExtendedPresenceMask
def all_tensorboard_jobs(self): """ Similar to tensorboard_jobs, but uses the default manager to return archived experiments as well. """ from db.models.tensorboards import TensorboardJob return TensorboardJob.all.filter(project=self)
Similar to tensorboard_jobs, but uses the default manager to return archived experiments as well.
def nest(*content): """Define a delimited list by enumerating each element of the list.""" if len(content) == 0: raise ValueError('no arguments supplied') return And([LPF, content[0]] + list(itt.chain.from_iterable(zip(itt.repeat(C), content[1:]))) + [RPF])
Define a delimited list by enumerating each element of the list.
def list_qos_policies(self, retrieve_all=True, **_params): """Fetches a list of all qos policies for a project.""" # Pass filters in "params" argument to do_request return self.list('policies', self.qos_policies_path, retrieve_all, **_params)
Fetches a list of all qos policies for a project.
def reload_components_ui(self): """ Reloads user selected Components. :return: Method success. :rtype: bool :note: May require user interaction. """ selected_components = self.get_selected_components() self.__engine.start_processing("Reloading Componen...
Reloads user selected Components. :return: Method success. :rtype: bool :note: May require user interaction.
def returner(ret): ''' Return data to the local syslog ''' _options = _get_options(ret) if not _verify_options(_options): return # Get values from syslog module level = getattr(syslog, _options['level']) facility = getattr(syslog, _options['facility']) # parse for syslog ...
Return data to the local syslog
def _dispatch(self, typ): """ returns the appropriate handler, for the object passed. """ for can_handle, handler in self._handler_pairs: # can handle could raise an exception here # such as issubclass being called on an instance. # it's easier to just...
returns the appropriate handler, for the object passed.
def generate(env): """Add Builders and construction variables for clang to an Environment.""" SCons.Tool.cc.generate(env) env['CC'] = env.Detect(compilers) or 'clang' if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = ...
Add Builders and construction variables for clang to an Environment.
def switch_showfilter_icon(self, toggled): """Switch the icon on the showfilter_tb :param toggled: the state of the button :type toggled: :class:`bool` :returns: None :rtype: None :raises: None """ at = QtCore.Qt.DownArrow if toggled else QtCore.Qt.RightA...
Switch the icon on the showfilter_tb :param toggled: the state of the button :type toggled: :class:`bool` :returns: None :rtype: None :raises: None
def get_model(model_id): """ Load a model from the server. :param model_id: The model identification in H2O :returns: Model object, a subclass of H2OEstimator """ assert_is_type(model_id, str) model_json = api("GET /3/Models/%s" % model_id)["models"][0] algo = model_json["algo"] if...
Load a model from the server. :param model_id: The model identification in H2O :returns: Model object, a subclass of H2OEstimator
def _add_to_upload_queue(self, src, rfile, uid): # type: (Uploader, blobxfer.models.upload.LocalPath, # blobxfer.models.azure.StorageEntity, str) -> None """Add remote file to download queue :param Uploader self: this :param blobxfer.models.upload.LocalPath src: local path...
Add remote file to download queue :param Uploader self: this :param blobxfer.models.upload.LocalPath src: local path :param blobxfer.models.azure.StorageEntity rfile: remote file :param str uid: unique id
def query_feature(): """ Returns list of sequence feature by query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Feature type default: 'splice variant' - name: identif...
Returns list of sequence feature by query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Feature type default: 'splice variant' - name: identifier in: query typ...
def patch_namespaced_stateful_set_status(self, name, namespace, body, **kwargs): """ partially update status of the specified StatefulSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.pat...
partially update status of the specified StatefulSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_status(name, namespace, body, async_req=True) >>> result = thread....
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True): """dump vtkjs texture coordinates""" if root is None: root = {} tcoords = dataset.GetPointData().GetTCoords() if tcoords: dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress) root...
dump vtkjs texture coordinates
def write(self, text): """Write text in the terminal without breaking the spinner.""" # similar to tqdm.write() # https://pypi.python.org/pypi/tqdm#writing-messages sys.stdout.write("\r") self._clear_line() _text = to_unicode(text) if PY2: _text = _te...
Write text in the terminal without breaking the spinner.
def reliability_curve(self): """ Calculates the reliability diagram statistics. The key columns are Bin_Start and Positive_Relative_Freq Returns: pandas.DataFrame """ total = self.frequencies["Total_Freq"].sum() curve = pd.DataFrame(columns=["Bin_Start", "Bin...
Calculates the reliability diagram statistics. The key columns are Bin_Start and Positive_Relative_Freq Returns: pandas.DataFrame
def store_async_result(async_id, async_result): """Persist the Async's result to the datastore.""" logging.debug("Storing result for %s", async_id) key = FuriousAsyncMarker( id=async_id, result=json.dumps(async_result.to_dict()), status=async_result.status).put() logging.debug("Settin...
Persist the Async's result to the datastore.
def add_bits4subtree_ids(self, relevant_ids): """Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!) relevant_ids can be a dict of _id to bit representation. If it is not supplied, a dict will be created by registering the leaf._id into a dict ...
Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!) relevant_ids can be a dict of _id to bit representation. If it is not supplied, a dict will be created by registering the leaf._id into a dict (and returning the dict) the bits4subtree_ids wil...
def check_and_adjust_sighandler(self, signame, sigs): """ Check to see if a single signal handler that we are interested in has changed or has not been set initially. On return self.sigs[signame] should have our signal handler. True is returned if the same or adjusted, False or N...
Check to see if a single signal handler that we are interested in has changed or has not been set initially. On return self.sigs[signame] should have our signal handler. True is returned if the same or adjusted, False or None if error or not found.
def tag(self, name, user, revision=None, message=None, date=None, **kwargs): """ Creates and returns a tag for the given ``revision``. :param name: name for new tag :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param revision: changeset id for wh...
Creates and returns a tag for the given ``revision``. :param name: name for new tag :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param revision: changeset id for which new tag would be created :param message: message of the tag's commit :param date: date of...
def repl(): """Read-Eval-Print-Loop for reading the query, printing it and its parse tree. Exit the loop either with an interrupt or "quit". """ while True: try: sys.stdout.write("Type in next query: \n> ") import locale query_str = raw_input().decode(sys.std...
Read-Eval-Print-Loop for reading the query, printing it and its parse tree. Exit the loop either with an interrupt or "quit".
def delete(self, group_id, session): '''taobao.crm.group.delete 删除分组 将该分组下的所有会员移除出该组,同时删除该分组。注:删除分组为异步任务,必须先调用taobao.crm.grouptask.check 确保涉及属性上没有任务。''' request = TOPRequest('taobao.crm.group.delete') request['group_id'] = group_id self.create(self.execute(request, sessi...
taobao.crm.group.delete 删除分组 将该分组下的所有会员移除出该组,同时删除该分组。注:删除分组为异步任务,必须先调用taobao.crm.grouptask.check 确保涉及属性上没有任务。
def get_config(key): ''' Get an identicon configuration parameter. Precedance order is: - application config (`udata.cfg`) - theme config - default ''' key = 'AVATAR_{0}'.format(key.upper()) local_config = current_app.config.get(key) return local_config or getattr(th...
Get an identicon configuration parameter. Precedance order is: - application config (`udata.cfg`) - theme config - default
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._avatar is not None: return F...
:rtype: bool
def get_return_elements(return_columns, namespace, subscript_dict): """ Takes a list of return elements formatted in vensim's format Varname[Sub1, SUb2] and returns first the model elements (in python safe language) that need to be computed and collected, and secondly the addresses that each ele...
Takes a list of return elements formatted in vensim's format Varname[Sub1, SUb2] and returns first the model elements (in python safe language) that need to be computed and collected, and secondly the addresses that each element in the return columns list translates to Parameters ---------- ...
def create_rule_section(self, name, add_pos=None, after=None, before=None): """ Create a rule section in a Firewall Policy. To specify a specific numbering position for the rule section, use the `add_pos` field. If no position or before/after is specified, the rule section will be placed...
Create a rule section in a Firewall Policy. To specify a specific numbering position for the rule section, use the `add_pos` field. If no position or before/after is specified, the rule section will be placed at the top which will encapsulate all rules below. Create a rule section for th...
def from_url(location): """ HTTP request for page at location returned as string malformed url returns ValueError nonexistant IP returns URLError wrong subnet IP return URLError reachable IP, no HTTP server returns URLError reachable IP, HTTP, wrong page returns HTTPError """ req = urll...
HTTP request for page at location returned as string malformed url returns ValueError nonexistant IP returns URLError wrong subnet IP return URLError reachable IP, no HTTP server returns URLError reachable IP, HTTP, wrong page returns HTTPError
def _check_file_exists_unix(self, remote_cmd=""): """Check if the dest_file already exists on the file system (return boolean).""" if self.direction == "put": self.ssh_ctl_chan._enter_shell() remote_cmd = "ls {}".format(self.file_system) remote_out = self.ssh_ctl_chan...
Check if the dest_file already exists on the file system (return boolean).
def get(self): """Returns the bgp routing configuration as a dict object """ config = self.get_block('^router bgp .*') if not config: return None response = dict() response.update(self._parse_bgp_as(config)) response.update(self._parse_router_id(confi...
Returns the bgp routing configuration as a dict object
def _get_sorting_message(request, key): """Parses the reverse query into a list of ClientSortControls protobuf messages. """ control_list = [] reverse = request.url.query.get('reverse', None) if reverse is None: return control_list if reverse.lower() ...
Parses the reverse query into a list of ClientSortControls protobuf messages.
def _get_filename(request, item): """ Creates a filename """ if request.keep_image_names: filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_')) else: filename = OgcImageService.finalize_filename( '_'.join([str(GeopediaSer...
Creates a filename
def write_exports(self, exports): """ Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. ...
Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries.
def _ParseTokenType(self, file_object, file_offset): """Parses a token type. Args: file_object (dfvfs.FileIO): file-like object. file_offset (int): offset of the token relative to the start of the file-like object. Returns: int: token type """ token_type_map = self._Get...
Parses a token type. Args: file_object (dfvfs.FileIO): file-like object. file_offset (int): offset of the token relative to the start of the file-like object. Returns: int: token type
def create_app(name, site, sourcepath, apppool=None): ''' Create an IIS application. .. note:: This function only validates against the application name, and will return True even if the application already exists with a different configuration. It will not modify the configuration...
Create an IIS application. .. note:: This function only validates against the application name, and will return True even if the application already exists with a different configuration. It will not modify the configuration of an existing application. Args: name (str)...