code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def make_error_redirect(self, authorization_error=None): """ Return a Django ``HttpResponseRedirect`` describing the request failure. If the :py:meth:`validate` method raises an error, the authorization endpoint should return the result of calling this method like so: >>> auth_code_generator = ( ...
Return a Django ``HttpResponseRedirect`` describing the request failure. If the :py:meth:`validate` method raises an error, the authorization endpoint should return the result of calling this method like so: >>> auth_code_generator = ( >>> AuthorizationCodeGenerator('/oauth2/missing_redirect_u...
def option(default_value): ''' The @option(x) decorator, usable in an immutable class (see immutable), is identical to the @param decorator except that the parameter is not required and instead takes on the default value x when the immutable is created. ''' def _option(f): (args, varargs...
The @option(x) decorator, usable in an immutable class (see immutable), is identical to the @param decorator except that the parameter is not required and instead takes on the default value x when the immutable is created.
def nginx_web_ssl_config(self): """ Nginx web ssl config """ dt = [self.nginx_web_dir, self.nginx_ssl_dir] return nginx_conf_string.simple_ssl_web_conf.format(dt=dt)
Nginx web ssl config
def send_game(self, *args, **kwargs): """See :func:`send_game`""" return send_game(*args, **self._merge_overrides(**kwargs)).run()
See :func:`send_game`
def sequence_diversity(pos, ac, start=None, stop=None, is_accessible=None): """Estimate nucleotide diversity within a given region, which is the average proportion of sites (including monomorphic sites not present in the data) that differ between randomly chosen pairs of chromosomes. ...
Estimate nucleotide diversity within a given region, which is the average proportion of sites (including monomorphic sites not present in the data) that differ between randomly chosen pairs of chromosomes. Parameters ---------- pos : array_like, int, shape (n_items,) Variant positions, usi...
def reqHistoricalData(self, id, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, chartOptions): """reqHistoricalData(EClientSocketBase self, TickerId id, Contract contract, IBString const & endDateTime, IBString const & durationStr, IBString const & barSizeSetting, IBString co...
reqHistoricalData(EClientSocketBase self, TickerId id, Contract contract, IBString const & endDateTime, IBString const & durationStr, IBString const & barSizeSetting, IBString const & whatToShow, int useRTH, int formatDate, TagValueListSPtr const & chartOptions)
def _get_qgrams(self, src, tar, qval=0, skip=0): """Return the Q-Grams in src & tar. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval :...
Return the Q-Grams in src & tar. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int The length of each q-gram; 0 for non-q-gram...
def top_commenters(self, num): """Return a markdown representation of the top commenters.""" num = min(num, len(self.commenters)) if num <= 0: return '' top_commenters = sorted( iteritems(self.commenters), key=lambda x: (-sum(y.score for y in x[1]), ...
Return a markdown representation of the top commenters.
def salt_ssh(): ''' Execute the salt-ssh system ''' import salt.cli.ssh if '' in sys.path: sys.path.remove('') try: client = salt.cli.ssh.SaltSSH() _install_signal_handlers(client) client.run() except SaltClientError as err: trace = traceback.format_ex...
Execute the salt-ssh system
def attach_events(*args): """Class decorator for SQLAlchemy models to attach listeners on class methods decorated with :func:`.on` Usage:: @attach_events class User(Model): email = Column(String(50)) @on('email', 'set') def lowercase_email(self, new_val...
Class decorator for SQLAlchemy models to attach listeners on class methods decorated with :func:`.on` Usage:: @attach_events class User(Model): email = Column(String(50)) @on('email', 'set') def lowercase_email(self, new_value, old_value, initiating_event):...
def set_description(self): """ Set the node description """ if self.device_info['type'] == 'Router': self.node['description'] = '%s %s' % (self.device_info['type'], self.device_info['model']) else: self.nod...
Set the node description
def piper(self, in_sock, out_sock, out_addr, onkill): "Worker thread for data reading" try: while True: written = in_sock.recv(32768) if not written: try: out_sock.shutdown(socket.SHUT_WR) except ...
Worker thread for data reading
def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1): """ Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squares algorithm for the computation of several minimal eigenvalues. If you want maximal eigenvalues, just send -A to the funct...
Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squares algorithm for the computation of several minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function. :Reference: S. V. Dolgov, B. N. Khoromskij, I. V. Oselede...
def get_nameserver_detail_output_show_nameserver_nameserver_xlatedomain(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_nameserv...
Auto Generated Code
def run(self): """Run the simulation.""" # Define the resource requirements of each component in the simulation. vertices_resources = { # Every component runs on exactly one core and consumes a certain # amount of SDRAM to hold configuration data. component: {...
Run the simulation.
def regroup_vectorized(srccat, eps, far=None, dist=norm_dist): """ Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters ---------- srccat : np.rec.arry or pd.DataFrame Sho...
Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters ---------- srccat : np.rec.arry or pd.DataFrame Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b...
def start(self, wait_for_completion=True, operation_timeout=None, status_timeout=None): """ Start (activate) this Partition, using the HMC operation "Start Partition". This HMC operation has deferred status behavior: If the asynchronous job on the HMC is complete, ...
Start (activate) this Partition, using the HMC operation "Start Partition". This HMC operation has deferred status behavior: If the asynchronous job on the HMC is complete, it takes a few seconds until the partition status has reached the desired value (it still may show status ...
def get_hull_energy(self, comp): """ Args: comp (Composition): Input composition Returns: Energy of lowest energy equilibrium at desired composition. Not normalized by atoms, i.e. E(Li4O2) = 2 * E(Li2O) """ e = 0 for k, v in self.get_d...
Args: comp (Composition): Input composition Returns: Energy of lowest energy equilibrium at desired composition. Not normalized by atoms, i.e. E(Li4O2) = 2 * E(Li2O)
def write_xsd(cls) -> None: """Write the complete base schema file `HydPyConfigBase.xsd` based on the template file `HydPyConfigBase.xsdt`. Method |XSDWriter.write_xsd| adds model specific information to the general information of template file `HydPyConfigBase.xsdt` regarding r...
Write the complete base schema file `HydPyConfigBase.xsd` based on the template file `HydPyConfigBase.xsdt`. Method |XSDWriter.write_xsd| adds model specific information to the general information of template file `HydPyConfigBase.xsdt` regarding reading and writing of time series data ...
def freeze(self): """ Freeze all settings so that they can't be altered """ self.target.disable() self.filter.configure(state='disable') self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.observers.configure(state='disable') ...
Freeze all settings so that they can't be altered
def merge(self, config): """ Load configuration from given configuration. :param config: config to load. If config is a string type, then it's treated as .ini filename :return: None """ if isinstance(config, ConfigParser) is True: self.update(config) elif isinstance(config, str): self.read(config)
Load configuration from given configuration. :param config: config to load. If config is a string type, then it's treated as .ini filename :return: None
def isPow2(num) -> bool: """ Check if number or constant is power of two """ if not isinstance(num, int): num = int(num) return num != 0 and ((num & (num - 1)) == 0)
Check if number or constant is power of two
def _clean_key_type(key_name, escape_char=ESCAPE_SEQ): """Removes type specifier returning detected type and a key name without type specifier. :param str key_name: A key name containing type postfix. :rtype: tuple[type|None, str] :returns: Type definition and cleaned key name. """ for i i...
Removes type specifier returning detected type and a key name without type specifier. :param str key_name: A key name containing type postfix. :rtype: tuple[type|None, str] :returns: Type definition and cleaned key name.
def _str_replace(txt): """Makes a small text amenable to being used in a filename.""" txt = txt.replace(",", "") txt = txt.replace(" ", "_") txt = txt.replace(":", "") txt = txt.replace(".", "") txt = txt.replace("/", "") txt = txt.replace("", "") return t...
Makes a small text amenable to being used in a filename.
def combine(self, members, output_file, dimension=None, start_index=None, stop_index=None, stride=None): """ Combine many files into a single file on disk. Defaults to using the 'time' dimension. """ nco = None try: nco = Nco() except BaseException: # This is not...
Combine many files into a single file on disk. Defaults to using the 'time' dimension.
def dead(name, enable=None, sig=None, init_delay=None, **kwargs): ''' Ensure that the named service is dead by stopping the service if it is running name The name of the init or rc script used to manage the service enable Set the service to be enable...
Ensure that the named service is dead by stopping the service if it is running name The name of the init or rc script used to manage the service enable Set the service to be enabled at boot time, ``True`` sets the service to be enabled, ``False`` sets the named service to be disabled. ...
def linear_interpolation(first, last, steps): """Interpolates all missing values using linear interpolation. :param numeric first: Start value for the interpolation. :param numeric last: End Value for the interpolation :param integer steps: Number of missing values that have to be calculated. ...
Interpolates all missing values using linear interpolation. :param numeric first: Start value for the interpolation. :param numeric last: End Value for the interpolation :param integer steps: Number of missing values that have to be calculated. :return: Returns a list of floats containing ...
def move_images(self, image_directory): """ Moves png-files one directory up from path/image/*.png -> path/*.png""" image_paths = glob(image_directory + "/**/*.png", recursive=True) for image_path in image_paths: destination = image_path.replace("\\image\\", "\\") shutil...
Moves png-files one directory up from path/image/*.png -> path/*.png
def transform_metadata(blob): """ Transforms metadata types about channels / users / bots / etc. into a dict rather than a list in order to enable faster lookup. """ o = {} for e in blob: i = e[u'id'] o[i] = e return o
Transforms metadata types about channels / users / bots / etc. into a dict rather than a list in order to enable faster lookup.
def cli(ctx, project_dir): """Launch the verilog simulation.""" exit_code = SCons(project_dir).sim() ctx.exit(exit_code)
Launch the verilog simulation.
def get_consul(self, resource_type): """ Returns an object that a :class:`~bang.deployers.deployer.Deployer` uses to control resources of :attr:`resource_type`. :param str service: Any of the resources defined in :mod:`bang.resources`. """ consul = self.CON...
Returns an object that a :class:`~bang.deployers.deployer.Deployer` uses to control resources of :attr:`resource_type`. :param str service: Any of the resources defined in :mod:`bang.resources`.
def check_mq_connection(self): """ RabbitMQ checks the connection It displays on the screen whether or not you have a connection. """ import pika from zengine.client_queue import BLOCKING_MQ_PARAMS from pika.exceptions import ProbableAuthenticationError, Connectio...
RabbitMQ checks the connection It displays on the screen whether or not you have a connection.
def import_activity_to_graph(diagram_graph, process_id, process_attributes, element): """ Method that adds the new element that represents BPMN activity. Should not be used directly, only as a part of method, that imports an element which extends Activity element (task, subprocess etc.) ...
Method that adds the new element that represents BPMN activity. Should not be used directly, only as a part of method, that imports an element which extends Activity element (task, subprocess etc.) :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param process_...
def _getInstrumentsVoc(self): """ This function returns the registered instruments in the system as a vocabulary. The instruments are filtered by the selected method. """ cfilter = {'portal_type': 'Instrument', 'is_active': True} if self.getMethod(): cfilter['...
This function returns the registered instruments in the system as a vocabulary. The instruments are filtered by the selected method.
def create_replication_interface(self, sp, ip_port, ip_address, netmask=None, v6_prefix_length=None, gateway=None, vlan_id=None): """ Creates a replication interface. :param sp: `UnityStorageProcessor` object. Storage pro...
Creates a replication interface. :param sp: `UnityStorageProcessor` object. Storage processor on which the replication interface is running. :param ip_port: `UnityIpPort` object. Physical port or link aggregation on the storage processor on which the interface is running. ...
def to_json(self): """ Serializes the event to JSON. :returns: a string """ event_as_dict = copy.deepcopy(self.event_body) if self.timestamp: if "keen" in event_as_dict: event_as_dict["keen"]["timestamp"] = self.timestamp.isoformat() else:...
Serializes the event to JSON. :returns: a string
def post_message2(consumers, lti_key, url, body, method='POST', content_type='application/xml'): """ Posts a signed message to LTI consumer using LTI 2.0 format :param: consumers: consumers from config :param: lti_key: key to find appropriate consumer :param: url: post url ...
Posts a signed message to LTI consumer using LTI 2.0 format :param: consumers: consumers from config :param: lti_key: key to find appropriate consumer :param: url: post url :param: body: xml body :return: success
def group_and_sort_nodes(self): """ Groups and then sorts the nodes according to the criteria passed into the Plot constructor. """ if self.node_grouping and not self.node_order: if self.group_order == "alphabetically": self.nodes = [ ...
Groups and then sorts the nodes according to the criteria passed into the Plot constructor.
def consumer(cfg_uri, queue, logger=None, fetchsize=1): """ 分布式爬虫的爬虫端(具体爬虫部分) 被包装的函数必须满足如下要求: 1. 有且仅有一个参数 2. 对于每个任务,返回两个参数: code, message :param cfg_uri: 读取任务的路径 :param queue: Queue的名字 :param logger: 日志记录工具 :param fetchsize: 每次取出消息数量 """ from stompest.protocol import S...
分布式爬虫的爬虫端(具体爬虫部分) 被包装的函数必须满足如下要求: 1. 有且仅有一个参数 2. 对于每个任务,返回两个参数: code, message :param cfg_uri: 读取任务的路径 :param queue: Queue的名字 :param logger: 日志记录工具 :param fetchsize: 每次取出消息数量
def pckw02(handle, classid, frname, first, last, segid, intlen, n, polydg, cdata, btime): """ Write a type 2 segment to a PCK binary file given the file handle, frame class ID, base frame, time range covered by the segment, and the Chebyshev polynomial coefficients. https://naif.jpl.nasa.gov/pu...
Write a type 2 segment to a PCK binary file given the file handle, frame class ID, base frame, time range covered by the segment, and the Chebyshev polynomial coefficients. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckw02_c.html :param handle: Handle of binary PCK file open for ...
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._year is not None: return Fal...
:rtype: bool
def load(stream, container=dict): """ Load and parse a file or file-like object 'stream' provides simple shell variables' definitions. :param stream: A file or file like object :param container: Factory function to create a dict-like object to store properties :return: Dict-like object ...
Load and parse a file or file-like object 'stream' provides simple shell variables' definitions. :param stream: A file or file like object :param container: Factory function to create a dict-like object to store properties :return: Dict-like object holding shell variables' definitions >>> ...
def _handle_socket(self, event: int, fd: int, multi: Any, data: bytes) -> None: """Called by libcurl when it wants to change the file descriptors it cares about. """ event_map = { pycurl.POLL_NONE: ioloop.IOLoop.NONE, pycurl.POLL_IN: ioloop.IOLoop.READ, ...
Called by libcurl when it wants to change the file descriptors it cares about.
def stretch(arr, fields=None, return_indices=False): """Stretch an array. Stretch an array by ``hstack()``-ing multiple array fields while preserving column names and record array structure. If a scalar field is specified, it will be stretched along with array fields. Parameters ---------- ...
Stretch an array. Stretch an array by ``hstack()``-ing multiple array fields while preserving column names and record array structure. If a scalar field is specified, it will be stretched along with array fields. Parameters ---------- arr : NumPy structured or record array The array t...
def get(ctx, job): """Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get ``` \...
Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get ``` \b ```bash $ polyax...
def vrrpe_vip(self, **kwargs): """Set vrrpe VIP. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, ve, etc). name (str): Name of interface. (1/0/5, 1/0/10, VE name etc). vrid (str): vrrpev3 ID. get (bool): Get ...
Set vrrpe VIP. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, ve, etc). name (str): Name of interface. (1/0/5, 1/0/10, VE name etc). vrid (str): vrrpev3 ID. get (bool): Get config instead of editing config. (True, F...
def lt(lt_value): """ Validates that a field value is less than the value given to this validator. """ def validate(value): if value >= lt_value: return e("{} is not less than {}", value, lt_value) return validate
Validates that a field value is less than the value given to this validator.
def lock_excl(self, timeout='default'): """Establish an exclusive lock to the resource. :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self.timeou...
Establish an exclusive lock to the resource. :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self.timeout)
def backup(self, paths=None): """Backup method driver.""" if not paths: paths = self._get_paths() try: self._backup_compresslevel(paths) except TypeError: try: self._backup_pb_gui(paths) except ImportError: ...
Backup method driver.
def write_xml(self): ''' Writes a VocabularyKey Xml as per Healthvault schema. :returns: lxml.etree.Element representing a single VocabularyKey ''' key = None if self. language is not None: lang = {} lang['{http://www.w3.org/XML/1998/names...
Writes a VocabularyKey Xml as per Healthvault schema. :returns: lxml.etree.Element representing a single VocabularyKey
def yesterday(hour=None, minute=None): """ Gives the ``datetime.datetime`` object corresponding to yesterday. The default value for optional parameters is the current value of hour and minute. I.e: when called without specifying values for parameters, the resulting object will refer to the time = no...
Gives the ``datetime.datetime`` object corresponding to yesterday. The default value for optional parameters is the current value of hour and minute. I.e: when called without specifying values for parameters, the resulting object will refer to the time = now - 24 hours; when called with only hour specif...
def _build_kwargs(keys, input_dict): """ Parameters ---------- keys : iterable Typically a list of strings. adict : dict-like A dictionary from which to attempt to pull each key. Returns ------- kwargs : dict A dictionary with only the keys that were in input_dic...
Parameters ---------- keys : iterable Typically a list of strings. adict : dict-like A dictionary from which to attempt to pull each key. Returns ------- kwargs : dict A dictionary with only the keys that were in input_dict
def _linux_stp(br, state): ''' Internal, sets STP state ''' brctl = _tool_path('brctl') return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state), python_shell=False)
Internal, sets STP state
def _take_screenshot(self, screenshot=False, name_prefix='unknown'): """ This is different from _save_screenshot. The return value maybe None or the screenshot path Args: screenshot: bool or PIL image """ if isinstance(screenshot, bool): if not sc...
This is different from _save_screenshot. The return value maybe None or the screenshot path Args: screenshot: bool or PIL image
def _start_thread(self): """Start an enqueueing thread.""" self._stopping_event = Event() self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,)) self._enqueueing_thread.start()
Start an enqueueing thread.
def qteDefVar(self, varName: str, value, module=None, doc: str=None): """ Define and document ``varName`` in an arbitrary name space. If ``module`` is **None** then ``qte_global`` will be used. .. warning: If the ``varName`` was already defined in ``module`` then its value a...
Define and document ``varName`` in an arbitrary name space. If ``module`` is **None** then ``qte_global`` will be used. .. warning: If the ``varName`` was already defined in ``module`` then its value and documentation are overwritten without warning. |Args| * ``...
def collect_diagnostic_data_45(self, end_datetime, bundle_size_bytes, cluster_name=None, roles=None, collect_metrics=False, start_datetime=None): """ Issue the command to collect diagnostic data. If start_datetime is specified, diagnostic data is collected for the entire per...
Issue the command to collect diagnostic data. If start_datetime is specified, diagnostic data is collected for the entire period between start_datetime and end_datetime provided that bundle size is less than or equal to bundle_size_bytes. Diagnostics data collection fails if the bundle size is greater than ...
def unregisterWalkthrough(self, walkthrough): """ Unregisters the inputed walkthrough from the application walkthroug list. :param walkthrough | <XWalkthrough> """ if type(walkthrough) in (str, unicode): walkthrough = self.findWalkthrough...
Unregisters the inputed walkthrough from the application walkthroug list. :param walkthrough | <XWalkthrough>
def run_script(self, script, identifier=_DEFAULT_SCRIPT_NAME): """ Run a JS script within the context.\ All code is ran synchronously,\ there is no event loop. It's thread-safe :param script: utf-8 encoded or unicode string :type script: bytes or str :param ident...
Run a JS script within the context.\ All code is ran synchronously,\ there is no event loop. It's thread-safe :param script: utf-8 encoded or unicode string :type script: bytes or str :param identifier: utf-8 encoded or unicode string.\ This is used as the name of the sc...
def _interpret_as_minutes(sval, mdict): """ Times like "1:22" are ambiguous; do they represent minutes and seconds or hours and minutes? By default, timeparse assumes the latter. Call this function after parsing out a dictionary to change that assumption. >>> import pprint >>> pprint.ppri...
Times like "1:22" are ambiguous; do they represent minutes and seconds or hours and minutes? By default, timeparse assumes the latter. Call this function after parsing out a dictionary to change that assumption. >>> import pprint >>> pprint.pprint(_interpret_as_minutes('1:24', {'secs': '24', 'min...
def retrieve_version(self, obj, version): """Retrieve the version of the object """ current_version = getattr(obj, VERSION_ID, None) if current_version is None: # No initial version return obj if str(current_version) == str(version): # Same v...
Retrieve the version of the object
def _build_input_args(input_filepath_list, input_format_list): ''' Builds input arguments by stitching input filepaths and input formats together. ''' if len(input_format_list) != len(input_filepath_list): raise ValueError( "input_format_list & input_filepath_list are not the same si...
Builds input arguments by stitching input filepaths and input formats together.
def add(self, response, condition=None): """ Add a new Response object :param response: The Response object :type response: parser.trigger.response.Response :param condition: An optional Conditional statement for the Response :type condition: parser.condition.Condition...
Add a new Response object :param response: The Response object :type response: parser.trigger.response.Response :param condition: An optional Conditional statement for the Response :type condition: parser.condition.Condition or None
def execute(self): """ Execute the actions necessary to perform a `molecule lint` and returns None. :return: None """ self.print_info() linters = [ l for l in [ self._config.lint, self._config.verifier.lint, ...
Execute the actions necessary to perform a `molecule lint` and returns None. :return: None
def _pop_params(cls, kwargs): """ Pop entries from the `kwargs` passed to cls.__new__ based on the values in `cls.params`. Parameters ---------- kwargs : dict The kwargs passed to cls.__new__. Returns ------- params : list[(str, objec...
Pop entries from the `kwargs` passed to cls.__new__ based on the values in `cls.params`. Parameters ---------- kwargs : dict The kwargs passed to cls.__new__. Returns ------- params : list[(str, object)] A list of string, value pairs cont...
def set_cache_implementation(self, cache_name, impl_name, maxsize, **kwargs): """ Changes the cache implementation for the named cache """ self._get_cache(cache_name).set_cache_impl(impl_name, maxsize, **kwargs)
Changes the cache implementation for the named cache
def extract_yaml(yaml_files): """ Take a list of yaml_files and load them to return back to the testing program """ loaded_yaml = [] for yaml_file in yaml_files: try: with open(yaml_file, 'r') as fd: loaded_yaml.append(yaml.safe_load(fd)) except IOErro...
Take a list of yaml_files and load them to return back to the testing program
def per_chunk(iterable, n=1, fillvalue=None): """ From http://stackoverflow.com/a/8991553/610569 >>> list(per_chunk('abcdefghi', n=2)) [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('i', None)] >>> list(per_chunk('abcdefghi', n=3)) [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h'...
From http://stackoverflow.com/a/8991553/610569 >>> list(per_chunk('abcdefghi', n=2)) [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('i', None)] >>> list(per_chunk('abcdefghi', n=3)) [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
def argument_types(self): """Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance. """ class ArgumentsIterator(collections.Sequence): def __init__(self, parent)...
Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance.
def create(self, data): """ Add a new store to your MailChimp account. Error checking on the currency code verifies that it is in the correct three-letter, all-caps format as specified by ISO 4217 but does not check that it is a valid code as the list of valid codes changes over...
Add a new store to your MailChimp account. Error checking on the currency code verifies that it is in the correct three-letter, all-caps format as specified by ISO 4217 but does not check that it is a valid code as the list of valid codes changes over time. :param data: The req...
def plot(self): """ Plots reaction energy as a function of mixing ratio x in self.c1 - self.c2 tie line using pylab. Returns: Pylab object that plots reaction energy as a function of mixing ratio x. """ plt.rcParams['xtick.major.pad'] = '6' ...
Plots reaction energy as a function of mixing ratio x in self.c1 - self.c2 tie line using pylab. Returns: Pylab object that plots reaction energy as a function of mixing ratio x.
def watch_and_wait(self, poll_interval=10, idle_log_timeout=None, kill_on_timeout=False, stash_log_method=None, tag_instances=False, **kwargs): """This provides shortcut access to the wait_for_complete_function.""" return wait_for_complete(self._job_queue, j...
This provides shortcut access to the wait_for_complete_function.
def _translate_response(self, response, state): """ Translates a saml authorization response to an internal response :type response: saml2.response.AuthnResponse :rtype: satosa.internal.InternalData :param response: The saml authorization response :return: A translated i...
Translates a saml authorization response to an internal response :type response: saml2.response.AuthnResponse :rtype: satosa.internal.InternalData :param response: The saml authorization response :return: A translated internal response
def remove(self, experiment): """Remove the configuration of an experiment""" try: project_path = self.projects[self[experiment]['project']]['root'] except KeyError: return config_path = osp.join(project_path, '.project', experiment + '.yml') for f in [con...
Remove the configuration of an experiment
def mapping(self, struct, key_depth=1000, tree_depth=1, update_callable=None): """ Generates random values for dict-like objects @struct: the dict-like structure you want to fill with random data @size: #int number of random values to include in each @tree_depth ...
Generates random values for dict-like objects @struct: the dict-like structure you want to fill with random data @size: #int number of random values to include in each @tree_depth @tree_depth: #int dict tree dimensions size, i.e. 1=|{key: value}| 2=|{...
def forwards(self, orm): "Write your forwards methods here." orm['avocado.DataField'].objects.get_or_create( app_name='variants', model_name='variantphenotype', field_name='hgmd_id', defaults={ 'name': 'HGMD', 'published': T...
Write your forwards methods here.
def as_binary(s, encoding='utf-8'): """Force conversion of given string to binary type. Binary is ``bytes`` type for Python 3.x and ``str`` for Python 2.x . If the string is already in binary, then no conversion is done and the same string is returned and ``encoding`` argument is ignored. Paramete...
Force conversion of given string to binary type. Binary is ``bytes`` type for Python 3.x and ``str`` for Python 2.x . If the string is already in binary, then no conversion is done and the same string is returned and ``encoding`` argument is ignored. Parameters ---------- s: str or bytes (Pyth...
def setup_pilotpoints_grid(ml=None,sr=None,ibound=None,prefix_dict=None, every_n_cell=4, use_ibound_zones=False, pp_dir='.',tpl_dir='.', shapename="pp.shp"): """ setup regularly-spaced (gridded) pilot point p...
setup regularly-spaced (gridded) pilot point parameterization Parameters ---------- ml : flopy.mbase a flopy mbase dervied type. If None, sr must not be None. sr : flopy.utils.reference.SpatialReference a spatial reference use to locate the model grid in space. If None, ml mus...
def job_count_enabled(self): """ Return the number of enabled jobs. :return: The number of jobs that are enabled. :rtype: int """ enabled = 0 for job_desc in self._jobs.values(): if job_desc['enabled']: enabled += 1 return enabled
Return the number of enabled jobs. :return: The number of jobs that are enabled. :rtype: int
def upload(self, remote, reader): """ Uploads a file :param remote: remote file name :param reader: an object that implements the read(size) method (typically a file descriptor) :return: """ fd = self.open(remote, 'w') while True: chunk = read...
Uploads a file :param remote: remote file name :param reader: an object that implements the read(size) method (typically a file descriptor) :return:
def restore_all_edges(self): """ Restores all hidden edges. """ for edge in self.hidden_edges.keys(): try: self.restore_edge(edge) except GraphError: pass
Restores all hidden edges.
def nodata(self): """Returns read only property for band nodata value, assuming single band rasters for now. """ if self._nodata is None: self._nodata = self[0].GetNoDataValue() return self._nodata
Returns read only property for band nodata value, assuming single band rasters for now.
def msg_filter(self): """Validate/return msg_filter from request (e.g. 'fuzzy', 'untranslated'), or a default. If a query is also specified in the request, then return None. """ if self.query: msg_filter = None else: msg_filter = self._request_req...
Validate/return msg_filter from request (e.g. 'fuzzy', 'untranslated'), or a default. If a query is also specified in the request, then return None.
def spec_from_thresh(thresh, labels, scores, *args, **kwargs): r"""Compute the specifity that a particular threshold on the scores can acheive specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) >>> scores = np.arange(0, 1, 0.1) >>> spec_from_thresh(0.5, labels=(scores > .5).astyp...
r"""Compute the specifity that a particular threshold on the scores can acheive specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) >>> scores = np.arange(0, 1, 0.1) >>> spec_from_thresh(0.5, labels=(scores > .5).astype(int), scores=scores) 1.0 >>> spec_from_thresh(0.5, labels...
def put(self, bucket=None, key=None, upload_id=None): """Update a new object or upload a part of a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param upload_id: The upl...
Update a new object or upload a part of a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response.
def ipv4_reassembly(packet, *, count=NotImplemented): """Make data for IPv4 reassembly.""" if 'IP' in packet: ipv4 = packet['IP'] if ipv4.flags.DF: # dismiss not fragmented packet return False, None data = dict( bufid=( ipaddress.ip_address(i...
Make data for IPv4 reassembly.
def find_pore_to_pore_distance(network, pores1=None, pores2=None): r''' Find the distance between all pores on set one to each pore in set 2 Parameters ---------- network : OpenPNM Network Object The network object containing the pore coordinates pores1 : array_like The pore in...
r''' Find the distance between all pores on set one to each pore in set 2 Parameters ---------- network : OpenPNM Network Object The network object containing the pore coordinates pores1 : array_like The pore indices of the first set pores2 : array_Like The pore indice...
def _convert_bundle(bundle): """ Converts ambry bundle to dict ready to send to CKAN API. Args: bundle (ambry.bundle.Bundle): bundle to convert. Returns: dict: dict to send to CKAN to create dataset. See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_creat...
Converts ambry bundle to dict ready to send to CKAN API. Args: bundle (ambry.bundle.Bundle): bundle to convert. Returns: dict: dict to send to CKAN to create dataset. See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_create
def save_session(self, sid, session, namespace=None): """Store the user session for a client. :param sid: The session id of the client. :param session: The session dictionary. :param namespace: The Socket.IO namespace. If this argument is omitted the default na...
Store the user session for a client. :param sid: The session id of the client. :param session: The session dictionary. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used.
def abbreviate(labels, rfill=' '): """ Abbreviate labels without introducing ambiguities. """ max_len = max(len(l) for l in labels) for i in range(1, max_len): abbrev = [l[:i].ljust(i, rfill) for l in labels] if len(abbrev) == len(set(abbrev)): break return abbrev
Abbreviate labels without introducing ambiguities.
def duplicate(self): ''' Returns a copy of the current group, including its lines. @returns: Group ''' instance = self.__class__(name=self.name, description=self.description) for line in self.lines: instance.lines.append(line.duplicate()) return instan...
Returns a copy of the current group, including its lines. @returns: Group
def detect_mean_shift(self, ts, B=1000): """ Detect mean shift in a time series. B is number of bootstrapped samples to draw. """ x = np.arange(0, len(ts)) stat_ts_func = self.compute_balance_mean_ts null_ts_func = self.shuffle_timeseries stats_ts, pvals, nums...
Detect mean shift in a time series. B is number of bootstrapped samples to draw.
def maintainer(self): """ >>> package = yarg.get('yarg') >>> package.maintainer Maintainer(name=u'Kura', email=u'kura@kura.io') """ maintainer = namedtuple('Maintainer', 'name email') return maintainer(name=self._package['maintainer'], ...
>>> package = yarg.get('yarg') >>> package.maintainer Maintainer(name=u'Kura', email=u'kura@kura.io')
def process_climis_livestock_data(data_dir: str): """ Process CliMIS livestock data. """ records = [] livestock_data_dir = f"{data_dir}/Climis South Sudan Livestock Data" for filename in glob( f"{livestock_data_dir}/Livestock Body Condition/*2017.csv" ): records += process_file_wi...
Process CliMIS livestock data.
def read(self, filepath): """Read the metadata values from a file path.""" fp = codecs.open(filepath, 'r', encoding='utf-8') try: self.read_file(fp) finally: fp.close()
Read the metadata values from a file path.
def down_alpha_beta(returns, factor_returns, **kwargs): """ Computes alpha and beta for periods when the benchmark return is negative. Parameters ---------- see documentation for `alpha_beta`. Returns ------- alpha : float beta : float """ return down(returns, factor_return...
Computes alpha and beta for periods when the benchmark return is negative. Parameters ---------- see documentation for `alpha_beta`. Returns ------- alpha : float beta : float
def add_toc_entry(self, title, level, slide_number): """ Adds a new entry to current presentation Table of Contents. """ self.__toc.append({'title': title, 'number': slide_number, 'level': level})
Adds a new entry to current presentation Table of Contents.
def arp_suppression(self, **kwargs): """ Enable Arp Suppression on a Vlan. Args: name:Vlan name on which the Arp suppression needs to be enabled. enable (bool): If arp suppression should be enabled or disabled.Default:``True``. get (bool) : Ge...
Enable Arp Suppression on a Vlan. Args: name:Vlan name on which the Arp suppression needs to be enabled. enable (bool): If arp suppression should be enabled or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) ...
def _check_events(tk): """Checks events in the queue on a given Tk instance""" used = False try: # Process all enqueued events, then exit. while True: try: # Get an event request from the queue. method, args, kwargs, response_queue = tk.tk._event_...
Checks events in the queue on a given Tk instance
def raise_thread_exception(thread_id, exception): """Raise an exception in a thread. Currently, this is only available on CPython. Note: This works by setting an async exception in the thread. This means that the exception will only get called the next time that thread acquires the GIL....
Raise an exception in a thread. Currently, this is only available on CPython. Note: This works by setting an async exception in the thread. This means that the exception will only get called the next time that thread acquires the GIL. Concretely, this means that this middleware can't ...