code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def check_error(res, error_enum): """Raise if the result has an error, otherwise return the result.""" if res.HasField("error"): enum_name = error_enum.DESCRIPTOR.full_name error_name = error_enum.Name(res.error) details = getattr(res, "error_details", "<none>") raise RequestError("%s.%s: '%s'" % (e...
Raise if the result has an error, otherwise return the result.
def get_schema_model(): """ Returns the schema model that is active in this project. """ try: return django_apps.get_model(settings.POSTGRES_SCHEMA_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("POSTGRES_SCHEMA_MODEL must be of the form 'app_label.model_na...
Returns the schema model that is active in this project.
def create(cls, api, run_id=None, project=None, username=None): """Create a run for the given project""" run_id = run_id or util.generate_id() project = project or api.settings.get("project") mutation = gql(''' mutation upsertRun($project: String, $entity: String, $name: String!)...
Create a run for the given project
def distinct_seeds(k): """ returns k distinct seeds for random number generation """ seeds = [] for _ in range(k): while True: s = random.randint(2**32 - 1) if s not in seeds: break seeds.append(s) return seeds
returns k distinct seeds for random number generation
def delta(self,local=False): """ Returns the number of days of difference """ (s,e) = self.get(local) return e-s
Returns the number of days of difference
def read_user_data(self, user_data_path): """Reads and parses a user_data file. Args: user_data_path (str): path to the userdata file Returns: str: the parsed user data file """ raw_user_data = read_value_from_path(user_data_path) ...
Reads and parses a user_data file. Args: user_data_path (str): path to the userdata file Returns: str: the parsed user data file
def shrink(self, shrink): """ Remove unnecessary parts :param shrink: Object to shringk :type shrink: dict | list :return: Shrunk object :rtype: dict | list """ if isinstance(shrink, list): return self._shrink_list(shrink) if isinstanc...
Remove unnecessary parts :param shrink: Object to shringk :type shrink: dict | list :return: Shrunk object :rtype: dict | list
def path_components(path): """Convert a path into group and channel name components""" def yield_components(path): # Iterate over each character and the next character chars = zip_longest(path, path[1:]) try: # Iterate over components while True: ...
Convert a path into group and channel name components
def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYP...
Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version
def normalizeInterpolationFactor(value): """ Normalizes interpolation factor. * **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``. * If **value** is a ``tuple`` or ``list``, it must have exactly two items. These items must be instances of :ref:`type-int-float`. * Returned valu...
Normalizes interpolation factor. * **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``. * If **value** is a ``tuple`` or ``list``, it must have exactly two items. These items must be instances of :ref:`type-int-float`. * Returned value is a ``tuple`` of two ``float``.
def gen_modules(self, initial_load=False): ''' Tell the minion to reload the execution modules CLI Example: .. code-block:: bash salt '*' sys.reload_modules ''' self.utils = salt.loader.utils(self.opts) self.functions = salt.loader.minion_mods( ...
Tell the minion to reload the execution modules CLI Example: .. code-block:: bash salt '*' sys.reload_modules
def echo_via_pager(*args, **kwargs): """Display pager only if it does not fit in one terminal screen. NOTE: The feature is available only on ``less``-based pager. """ try: restore = 'LESS' not in os.environ os.environ.setdefault('LESS', '-iXFR') click.echo_via_pager(*args, **kwa...
Display pager only if it does not fit in one terminal screen. NOTE: The feature is available only on ``less``-based pager.
def delete_and_rm_options(*args, **kwargs): """ Options which apply both to `globus delete` and `globus rm` """ def inner_decorator(f, supports_batch=True, default_enable_globs=False): f = click.option( "--recursive", "-r", is_flag=True, help="Recursively delete dirs" )(f) ...
Options which apply both to `globus delete` and `globus rm`
def gen_file_lines(path, mode='rUb', strip_eol=True, ascii=True, eol='\n'): """Generate a sequence of "documents" from the lines in a file Arguments: path (file or str): path to a file or an open file_obj ready to be read mode (str): file mode to open a file in strip_eol (bool): whether to st...
Generate a sequence of "documents" from the lines in a file Arguments: path (file or str): path to a file or an open file_obj ready to be read mode (str): file mode to open a file in strip_eol (bool): whether to strip the EOL char from lines as they are read/generated/yielded ascii (bool): ...
def _match_member(self, i, column): """Looks at line 'i' to see if the line matches a module member def.""" self.col_match = self.RE_MEMBERS.match(self._source[i]) if self.col_match is not None: if column < self._source[i].index(":"): self.el_call = "name" ...
Looks at line 'i' to see if the line matches a module member def.
async def connect_controller(self, controller_name=None): """Connect to a controller by name. If the name is empty, it connect to the current controller. """ if not controller_name: controller_name = self.jujudata.current_controller() if not controller_name: ...
Connect to a controller by name. If the name is empty, it connect to the current controller.
def GetPeaksExons(bed,parsedGTF): """ Annotates a bedtool, BED narrow peak :param bed: a pandas dataframe in bed format :param parsedGTF: a parsed GTF file as outputed by parseGTF() with the following columns :returns: a Pandas dataframe """ bedtool_AB=dfTObedtool(bed) exonsGTF=parse...
Annotates a bedtool, BED narrow peak :param bed: a pandas dataframe in bed format :param parsedGTF: a parsed GTF file as outputed by parseGTF() with the following columns :returns: a Pandas dataframe
def get_pmag_dir(): """ Returns directory in which PmagPy is installed """ # this is correct for py2exe (DEPRECATED) #win_frozen = is_frozen() #if win_frozen: # path = os.path.abspath(unicode(sys.executable, sys.getfilesystemencoding())) # path = os.path.split(path)[0] # ret...
Returns directory in which PmagPy is installed
def __initialize_instance(self): """ Take any predefined methods/handlers and insert them into Sanic JWT """ config = self.config # Initialize instance of the Authentication class self.instance.auth = self.authentication_class(self.app, config=config) init_handl...
Take any predefined methods/handlers and insert them into Sanic JWT
def get_attributes(path): ''' Return a dictionary object with the Windows file attributes for a file. Args: path (str): The path to the file or directory Returns: dict: A dictionary of file attributes CLI Example: .. code-block:: bash salt '*' file.get_attributes...
Return a dictionary object with the Windows file attributes for a file. Args: path (str): The path to the file or directory Returns: dict: A dictionary of file attributes CLI Example: .. code-block:: bash salt '*' file.get_attributes c:\\temp\\a.txt
def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._abilities( lambda c: c.name != "Smart"), key=lambda c: c.name), start=2): if self._queued_action and cmd ==...
Draw the list of available commands.
def position_target_global_int_send(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the ...
Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being controlled this way. time_boot_ms ...
def _getMostActiveCells(self): """ Gets the most active cells in the Union SDR having at least non-zero activation in sorted order. @return: a list of cell indices """ poolingActivation = self._poolingActivation nonZeroCells = numpy.argwhere(poolingActivation > 0)[:,0] # include a tie-b...
Gets the most active cells in the Union SDR having at least non-zero activation in sorted order. @return: a list of cell indices
def clean_proc_dir(opts): ''' Clean out old tracked jobs running on the master Generally, anything tracking a job should remove the job once the job has finished. However, this will remove any jobs that for some reason were not properly removed when finished or errored. ''' serial = sal...
Clean out old tracked jobs running on the master Generally, anything tracking a job should remove the job once the job has finished. However, this will remove any jobs that for some reason were not properly removed when finished or errored.
def extensions(): """How do we handle cython: 1. when on git, require cython during setup time (do not distribute generated .c files via git) a) cython present -> fine b) no cython present -> install it on the fly. Extensions have to have .pyx suffix This is solved via a lazy evaluation of the...
How do we handle cython: 1. when on git, require cython during setup time (do not distribute generated .c files via git) a) cython present -> fine b) no cython present -> install it on the fly. Extensions have to have .pyx suffix This is solved via a lazy evaluation of the extension list. This is ...
def build_chain(self, source, chain): """ Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source """ ...
Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source
def remote_delete_user(model, request): """Remove user via remote service. Returns a JSON response containing success state and a message indicating what happened:: { success: true, // respective false message: 'message' } Expected request parameters: id Id of use...
Remove user via remote service. Returns a JSON response containing success state and a message indicating what happened:: { success: true, // respective false message: 'message' } Expected request parameters: id Id of user to delete.
def render_template(template_name: str, **kwargs): """ Renders the template file with the given filename from within Cauldron's template environment folder. :param template_name: The filename of the template to render. Any path elements should be relative to Cauldron's root template fol...
Renders the template file with the given filename from within Cauldron's template environment folder. :param template_name: The filename of the template to render. Any path elements should be relative to Cauldron's root template folder. :param kwargs: Any elements passed to Jinja2 f...
def _setup_dmtf_schema(self): """ Install the DMTF CIM schema from the DMTF web site if it is not already installed. This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by `schema_mof_dir`. Onc...
Install the DMTF CIM schema from the DMTF web site if it is not already installed. This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by `schema_mof_dir`. Once the schema zip file is downloaded into `schema_r...
def get_bytes(self, n): """ Return the next ``n`` bytes of the message (as a `str`), without decomposing into an int, decoded string, etc. Just the raw bytes are returned. Returns a string of ``n`` zero bytes if there weren't ``n`` bytes remaining in the message. """ ...
Return the next ``n`` bytes of the message (as a `str`), without decomposing into an int, decoded string, etc. Just the raw bytes are returned. Returns a string of ``n`` zero bytes if there weren't ``n`` bytes remaining in the message.
def remove_replica(self, partition_name, osr_broker_ids, count=1): """Removing a replica is done by trying to remove a replica from every broker and choosing the resulting state with the highest fitness score. Out-of-sync replicas will always be removed before in-sync replicas. :param p...
Removing a replica is done by trying to remove a replica from every broker and choosing the resulting state with the highest fitness score. Out-of-sync replicas will always be removed before in-sync replicas. :param partition_name: (topic_id, partition_id) of the partition to remove replicas of...
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix
def nt_counts(bam, positions, stranded=False, vcf=False, bed=False): """ Find the number of nucleotides covered at all positions in a bed or vcf file. Parameters ---------- bam : str or pysam.calignmentfile.AlignmentFile Bam file opened with pysam or path to bam file (must be s...
Find the number of nucleotides covered at all positions in a bed or vcf file. Parameters ---------- bam : str or pysam.calignmentfile.AlignmentFile Bam file opened with pysam or path to bam file (must be sorted and indexed). positions : str or pybedtools.BedTool Path t...
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
Convert things on the way from Python to the database.
def parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. ...
Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names.
def compute_y(self, coefficients, num_x): """ Return calculated y-values for the domain of x-values in [1, num_x]. """ y_vals = [] for x in range(1, num_x + 1): y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])]) y_vals.append(y) return y_vals
Return calculated y-values for the domain of x-values in [1, num_x].
def committees_legislators(self, *args, **kwargs): '''Return an iterable of committees with all the legislators cached for reference in the Committee model. So do a "select_related" operation on committee members. ''' committees = list(self.committees(*args, **kwargs)) le...
Return an iterable of committees with all the legislators cached for reference in the Committee model. So do a "select_related" operation on committee members.
def nic_remove(self, nic): """ Detach a nic from a bridge :param nic: nic name to detach """ args = { 'nic': nic, } self._nic_remove_chk.check(args) return self._client.json('bridge.nic-remove', args)
Detach a nic from a bridge :param nic: nic name to detach
def cov_trob(x, wt=None, cor=False, center=True, nu=5, maxit=25, tol=0.01): """ Covariance Estimation for Multivariate t Distribution Estimates a covariance or correlation matrix assuming the data came from a multivariate t distribution: this provides some degree of robustness to outli...
Covariance Estimation for Multivariate t Distribution Estimates a covariance or correlation matrix assuming the data came from a multivariate t distribution: this provides some degree of robustness to outlier without giving a high breakdown point. **credit**: This function a port of the R function...
def newComment(content): """Creation of a new node containing a comment. """ ret = libxml2mod.xmlNewComment(content) if ret is None:raise treeError('xmlNewComment() failed') return xmlNode(_obj=ret)
Creation of a new node containing a comment.
def l2traceroute_input_protocolType_IP_l4_dest_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") l2traceroute = ET.Element("l2traceroute") config = l2traceroute input = ET.SubElement(l2traceroute, "input") protocolType = ET.SubElement(...
Auto Generated Code
def _update_data(self, name, value, timestamp, interval, config, conn): '''Support function for insert. Should be called within a transaction''' i_time = config['i_calc'].to_bucket(timestamp) if not config['coarse']: r_time = config['r_calc'].to_bucket(timestamp) else: r_time = None stmt...
Support function for insert. Should be called within a transaction
def _write_stream(self, src, dst, size=None, size_limit=None, chunk_size=None, progress_callback=None): """Get helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact...
Get helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact amount of bytes will be written to the destination file. :param size_limit: ``FileSizeLimit`` instance to limit numb...
def __Logout(si): """ Disconnect (logout) service instance @param si: Service instance (returned from Connect) """ try: if si: content = si.RetrieveContent() content.sessionManager.Logout() except Exception as e: pass
Disconnect (logout) service instance @param si: Service instance (returned from Connect)
def lagrange_polynomial(abscissas, sort="GR"): """ Create Lagrange polynomials. Args: abscissas (numpy.ndarray): Sample points where the Lagrange polynomials shall be defined. Example: >>> print(chaospy.around(lagrange_polynomial([-10, 10]), 4)) [-0.05q0+0.5, 0.05q0...
Create Lagrange polynomials. Args: abscissas (numpy.ndarray): Sample points where the Lagrange polynomials shall be defined. Example: >>> print(chaospy.around(lagrange_polynomial([-10, 10]), 4)) [-0.05q0+0.5, 0.05q0+0.5] >>> print(chaospy.around(lagrange_polynomial(...
def second_order_diff(arr, x): """Compute second order difference of an array. A 2nd order forward difference is used for the first point, 2nd order central difference for interior, and 2nd order backward difference for last point, returning an array the same length as the input array. """ # Co...
Compute second order difference of an array. A 2nd order forward difference is used for the first point, 2nd order central difference for interior, and 2nd order backward difference for last point, returning an array the same length as the input array.
def project(self, projection): ''' Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar ''' x, y = projection(self.lon.decimal_degree, self.lat.decimal_degree) return (x, y)
Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar
def to_doc(name, thing, header_level, source_location): """ Generate markdown for a class or function Parameters ---------- name : str Name of the thing being documented thing : class or function Class or function to document header_level : int Heading level sour...
Generate markdown for a class or function Parameters ---------- name : str Name of the thing being documented thing : class or function Class or function to document header_level : int Heading level source_location : str URL of repo containing source code
def paddedInt(i): ''' return a string that contains `i`, left-padded with 0's up to PAD_LEN digits ''' i_str = str(i) pad = PAD_LEN - len(i_str) return (pad * "0") + i_str
return a string that contains `i`, left-padded with 0's up to PAD_LEN digits
def constant_compare(a, b): """ Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal """ if not isinstance(a, byte_cls): ra...
Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal
def get_repos(self): """ Gets the repos for the organization and builds the URL/headers for getting timestamps of stargazers. """ print 'Getting repos.' #Uses the developer API. Note this could change. headers = {'Accept': 'application/vnd.github.v3.star+json', '...
Gets the repos for the organization and builds the URL/headers for getting timestamps of stargazers.
def download(url, save_to_file=True, save_dir=".", filename=None, block_size=64000, overwrite=False, quiet=False): """ Download a given URL to either file or memory :param url: Full url (with protocol) of path to download :param save_to_file: boolean if it should be saved to file or not ...
Download a given URL to either file or memory :param url: Full url (with protocol) of path to download :param save_to_file: boolean if it should be saved to file or not :param save_dir: location of saved file, default is current working dir :param filename: filename to save as :param block_size: do...
def update_probes(self, progress): """ update the probe tree """ new_values = self.read_probes.probes_values probe_count = len(self.read_probes.probes) if probe_count > self.tree_probes.topLevelItemCount(): # when run for the first time, there are no probes i...
update the probe tree
def process(*args, **kwargs): """Runs the decorated function in a concurrent process, taking care of the result and error management. Decorated functions will return a concurrent.futures.Future object once called. The timeout parameter will set a maximum execution time for the decorated functi...
Runs the decorated function in a concurrent process, taking care of the result and error management. Decorated functions will return a concurrent.futures.Future object once called. The timeout parameter will set a maximum execution time for the decorated function. If the execution exceeds the time...
def check_url(url): """Check whether the given URL is dead or alive. Returns a dict with four keys: "url": The URL that was checked (string) "alive": Whether the URL was working, True or False "status": The HTTP status code of the response from the URL, e.g. 200, 401, 500 (...
Check whether the given URL is dead or alive. Returns a dict with four keys: "url": The URL that was checked (string) "alive": Whether the URL was working, True or False "status": The HTTP status code of the response from the URL, e.g. 200, 401, 500 (int) "reason": The ...
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: errata /repositories/<id>/errata files /repositories/<id>/files packages /repositories/<id>/packag...
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: errata /repositories/<id>/errata files /repositories/<id>/files packages /repositories/<id>/packages module_streams /...
async def _loadNodeValu(self, full, valu): ''' Load a node from storage into the tree. ( used by initialization routines to build the tree) ''' node = self.root for path in iterpath(full): name = path[-1] step = node.kids.get(name) if...
Load a node from storage into the tree. ( used by initialization routines to build the tree)
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ parser_context = self.get_parser_context(request) return Request( request, parsers=self.get_parsers(), authenticators=self.get_authenticators()...
Returns the initial request object.
def transform(self, X, y=None): ''' :X: list of dict :y: labels ''' return [{ new_feature: self._fisher_pval(x, old_features) for new_feature, old_features in self.feature_groups.items() if len(set(x.keys()) & set(old_features)) } for x...
:X: list of dict :y: labels
def handle_internal_commands(command): """Run repl-internal commands. Repl-internal commands are all commands starting with ":". """ if command.startswith(":"): target = _get_registered_target(command[1:], default=None) if target: return target()
Run repl-internal commands. Repl-internal commands are all commands starting with ":".
def fetch_file(self, in_path, out_path): ''' save a remote file to the specified path ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host) data = dict(mode='fetch', in_path=in_path) data = utils.jsonify(data) data = utils.encrypt(self.key, data) self.socket.se...
save a remote file to the specified path
def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] ...
List with tuples of section names and positions. Positions of section names are measured by cumulative word count.
def cancel_download_task(self, task_id, expires=None, **kwargs): """取消离线下载任务. :param task_id: 要取消的任务ID号。 :type task_id: str :param expires: 请求失效时间,如果有,则会校验。 :type expires: int :return: Response 对象 """ data = { 'expires': expires, ...
取消离线下载任务. :param task_id: 要取消的任务ID号。 :type task_id: str :param expires: 请求失效时间,如果有,则会校验。 :type expires: int :return: Response 对象
def bibtex(self): """Represent the source in BibTeX format. :return: string encoding the source in BibTeX syntax. """ m = max(itertools.chain(map(len, self), [0])) fields = (" %s = {%s}" % (k.ljust(m), self[k]) for k in self) return "@%s{%s,\n%s\n}" % ( geta...
Represent the source in BibTeX format. :return: string encoding the source in BibTeX syntax.
def validate(cpf_number): """This function validates a CPF number. This function uses calculation package to calculate both digits and then validates the number. :param cpf_number: a CPF number to be validated. Only numbers. :type cpf_number: string :return: Bool -- True for a valid number, F...
This function validates a CPF number. This function uses calculation package to calculate both digits and then validates the number. :param cpf_number: a CPF number to be validated. Only numbers. :type cpf_number: string :return: Bool -- True for a valid number, False otherwise.
def _return_retry_timer(self): ''' Based on the minion configuration, either return a randomized timer or just return the value of the return_retry_timer. ''' msg = 'Minion return retry timer set to %s seconds' if self.opts.get('return_retry_timer_max'): try: ...
Based on the minion configuration, either return a randomized timer or just return the value of the return_retry_timer.
def _add_case(self, case_obj): """Add a case to the database If the case already exists exception is raised Args: case_obj(Case) """ if self.case(case_obj['_id']): raise IntegrityError("Case %s already exists in database" % case_obj['_id']) ...
Add a case to the database If the case already exists exception is raised Args: case_obj(Case)
def set_npn_advertise_callback(self, callback): """ Specify a callback function that will be called when offering `Next Protocol Negotiation <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server. :param callback: The callback function. It will be invoked with o...
Specify a callback function that will be called when offering `Next Protocol Negotiation <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server. :param callback: The callback function. It will be invoked with one argument, the :class:`Connection` instance. It shoul...
def _load_json(self, filename): """Load sensors from json file.""" with open(filename, 'r') as file_handle: self._sensors.update(json.load( file_handle, cls=MySensorsJSONDecoder))
Load sensors from json file.
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None, password=None): ''' Make the server a slave of another instance, or promote it as master CLI Example: .. code-block:: bash # Become slave of redis-n01.example.com:6379 salt '*' redis.slaveof red...
Make the server a slave of another instance, or promote it as master CLI Example: .. code-block:: bash # Become slave of redis-n01.example.com:6379 salt '*' redis.slaveof redis-n01.example.com 6379 salt '*' redis.slaveof redis-n01.example.com # Become master salt '*' r...
def ungroup_state(self, state_id): """ Ungroup state with state id state_id into its parent and remain internal linkage in parent. Interconnecting transitions and data flows to parent and other child states are preserved except: - a transition that is going from income to outcome directl...
Ungroup state with state id state_id into its parent and remain internal linkage in parent. Interconnecting transitions and data flows to parent and other child states are preserved except: - a transition that is going from income to outcome directly and - a data-flow that is linking...
def index(): """Basic test view.""" identity = g.identity actions = {} for action in access.actions.values(): actions[action.value] = DynamicPermission(action).allows(identity) if current_user.is_anonymous: return render_template("invenio_access/open.html", ...
Basic test view.
def apply_operation_to(self, path): """Add `a:lnTo` element to *path* for this line segment. Returns the `a:lnTo` element newly added to the path. """ return path.add_lnTo( self._x - self._freeform_builder.shape_offset_x, self._y - self._freeform_builder.shape_of...
Add `a:lnTo` element to *path* for this line segment. Returns the `a:lnTo` element newly added to the path.
def handle(self): "The actual service to which the user has connected." if self.TELNET_ISSUE: self.writeline(self.TELNET_ISSUE) if not self.authentication_ok(): return if self.DOECHO: self.writeline(self.WELCOME) self.session_start() w...
The actual service to which the user has connected.
def pexpireat(self, name, when): """ Set an expire flag on key ``name``. ``when`` can be represented as an integer representing unix time in milliseconds (unix time * 1000) or a Python datetime object. """ with self.pipe as pipe: return pipe.pexpireat(self.red...
Set an expire flag on key ``name``. ``when`` can be represented as an integer representing unix time in milliseconds (unix time * 1000) or a Python datetime object.
def to_representation(self, value): """Project outgoing native value.""" value = apply_subfield_projection(self, value, deep=True) return super().to_representation(value)
Project outgoing native value.
def get_html_output(self): """ Return line generator. """ def html_splitlines(lines): # this cool function was taken from trac. # http://projects.edgewall.com/trac/ open_tag_re = re.compile(r'<(\w+)(\s.*)?[^/]?>') close_tag_re = re.compile(r'</(\w+)>') ...
Return line generator.
def lambda_handler(event, context=None, settings_name="zappa_settings"): # NoQA """ An AWS Lambda function which parses specific API Gateway input into a WSGI request. The request get fed it to Django, processes the Django response, and returns that back to the API Gateway. """ time_start = da...
An AWS Lambda function which parses specific API Gateway input into a WSGI request. The request get fed it to Django, processes the Django response, and returns that back to the API Gateway.
def new_signal(celf, path, iface, name) : "creates a new DBUS.MESSAGE_TYPE_SIGNAL message." result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode()) if result == None : raise CallFailed("dbus_message_new_signal") #end if return \ ...
creates a new DBUS.MESSAGE_TYPE_SIGNAL message.
def build_data_table( energy, flux, flux_error=None, flux_error_lo=None, flux_error_hi=None, energy_width=None, energy_lo=None, energy_hi=None, ul=None, cl=None, ): """ Read data into data dict. Parameters ---------- energy : :class:`~astropy.units.Quantity`...
Read data into data dict. Parameters ---------- energy : :class:`~astropy.units.Quantity` array instance Observed photon energy array [physical type ``energy``] flux : :class:`~astropy.units.Quantity` array instance Observed flux array [physical type ``flux`` or ``differential flux``]...
def send_and_require(self, send, regexps, not_there=False, shutit_pexpect_child=None, echo=None, note=None, loglevel=logging.INFO): """Send string and require the i...
Send string and require the item in the output. See send_until
def createPortForm(self, req, tag): """ Create and return a L{LiveForm} for adding a new L{TCPPort} or L{SSLPort} to the site store. """ def port(s): n = int(s) if n < 0 or n > 65535: raise ValueError(s) return n factor...
Create and return a L{LiveForm} for adding a new L{TCPPort} or L{SSLPort} to the site store.
def is_equivalent(self, other, ignore=False): """ Return ``True`` if the IPA string is equivalent to the ``other`` object. The ``other`` object can be: 1. a Unicode string, 2. a list of IPAChar objects, and 3. another IPAString. :param variant other: the object...
Return ``True`` if the IPA string is equivalent to the ``other`` object. The ``other`` object can be: 1. a Unicode string, 2. a list of IPAChar objects, and 3. another IPAString. :param variant other: the object to be compared against :param bool ignore: if other is a ...
def _prepare_request(reddit_session, url, params, data, auth, files, method=None): """Return a requests Request object that can be "prepared".""" # Requests using OAuth for authorization must switch to using the oauth # domain. if getattr(reddit_session, '_use_oauth', False): ...
Return a requests Request object that can be "prepared".
def generate_protocol(self,sweep=None): """ Create (x,y) points necessary to graph protocol for the current sweep. """ #TODO: make a line protocol that's plottable if sweep is None: sweep = self.currentSweep if sweep is None: sweep = 0 if n...
Create (x,y) points necessary to graph protocol for the current sweep.
def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides, padding, dimension_numbers): """Generalized computation of conv shape.""" lhs_perm, rhs_perm, out_perm = self._conv_general_permutations( dimension_numbers) lhs_trans = onp.take(lhs_shape, lhs_p...
Generalized computation of conv shape.
def _set_index(self, schema, name, fields, **index_options): """ https://www.sqlite.org/lang_createindex.html """ query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format( 'UNIQUE ' if index_options.get('unique', False) else '', schema, nam...
https://www.sqlite.org/lang_createindex.html
def _new_object(self, objtype, name=None): r""" """ if objtype.startswith('net'): obj = openpnm.network.GenericNetwork(project=self, name=name) elif objtype.startswith('geo'): obj = openpnm.geometry.GenericGeometry(project=self, name=name) elif objtype.sta...
r"""
def _value_is_dynamic(self,obj,objtype=None): """ Return True if the parameter is actually dynamic (i.e. the value is being generated). """ return hasattr(super(Dynamic,self).__get__(obj,objtype),'_Dynamic_last')
Return True if the parameter is actually dynamic (i.e. the value is being generated).
def load_stock_prices(self): """ Load latest prices for securities """ from pricedb import SecuritySymbol info = StocksInfo(self.config) for item in self.model.stocks: symbol = SecuritySymbol("", "") symbol.parse(item.symbol) price: PriceModel = info...
Load latest prices for securities
def export(self, path, session): """Exports the module with the variables from the session in `path`. Note that it is the module definition in the ModuleSpec used to create this module that gets exported. The session is only used to provide the value of variables. Args: path: path where to e...
Exports the module with the variables from the session in `path`. Note that it is the module definition in the ModuleSpec used to create this module that gets exported. The session is only used to provide the value of variables. Args: path: path where to export the module to. session: sess...
def pixel_to_icrs_coords(x, y, wcs): """ Convert pixel coordinates to ICRS Right Ascension and Declination. This is merely a convenience function to extract RA and Dec. from a `~astropy.coordinates.SkyCoord` instance so they can be put in separate columns in a `~astropy.table.Table`. Parameter...
Convert pixel coordinates to ICRS Right Ascension and Declination. This is merely a convenience function to extract RA and Dec. from a `~astropy.coordinates.SkyCoord` instance so they can be put in separate columns in a `~astropy.table.Table`. Parameters ---------- x : float or array-like ...
def residual_block(x, hparams): """A stack of convolution blocks with residual connection.""" k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((1, 1), k) for _ in range(3)] y = common_layers.subseparable_conv_block( x, hparams.hidden_size, dilations_and_kernels, ...
A stack of convolution blocks with residual connection.
def mark_backward(output_tensor, used_node_names): """Function to propagate backwards in the graph and mark nodes as used. Traverses recursively through the graph from the end tensor, through the op that generates the tensor, and then to the input tensors that feed the op. Nodes encountered are stored in used_...
Function to propagate backwards in the graph and mark nodes as used. Traverses recursively through the graph from the end tensor, through the op that generates the tensor, and then to the input tensors that feed the op. Nodes encountered are stored in used_node_names. Args: output_tensor: A Tensor which w...
def convert_pattern_to_pil(pattern, version=1): """Convert Pattern to PIL Image.""" from PIL import Image mode = get_pil_mode(pattern.image_mode.name, False) # The order is different here. size = pattern.data.rectangle[3], pattern.data.rectangle[2] channels = [ _create_channel(size, c.ge...
Convert Pattern to PIL Image.
def concatenate_fields(fields, dim): 'Create an INstanceAttribute from a list of InstnaceFields' if len(fields) == 0: raise ValueError('fields cannot be an empty list') if len(set((f.name, f.shape, f.dtype) for f in fields)) != 1: raise ValueError('fields should have homogeneous name, s...
Create an INstanceAttribute from a list of InstnaceFields
def update_environment(self, environment, environment_ids): """ Method to update environment :param environment_ids: Ids of Environment """ uri = 'api/v3/environment/%s/' % environment_ids data = dict() data['environments'] = list() data['environments']...
Method to update environment :param environment_ids: Ids of Environment
def _AddEvents(cls, Class): """Adds events based on the attributes of the given ``...Events`` class. :Parameters: Class : class An `...Events` class whose methods define events that may occur in the instances of the current class. """ def make_e...
Adds events based on the attributes of the given ``...Events`` class. :Parameters: Class : class An `...Events` class whose methods define events that may occur in the instances of the current class.
def parse_unstruct(unstruct): """ Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair For example, the JSON { "data": { "data": { "key": "value" }, "schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschem...
Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair For example, the JSON { "data": { "data": { "key": "value" }, "schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1" }, "schema": "iglu:co...
def get_settings_from_interface(iface): """Get the configuration settings associated to a list of schema interfaces :param iface: The schema interface from which we want to get its fields :return: Dictionary with iface name as key and as value a dictionary with the setting names (keys) linked t...
Get the configuration settings associated to a list of schema interfaces :param iface: The schema interface from which we want to get its fields :return: Dictionary with iface name as key and as value a dictionary with the setting names (keys) linked to that schema and its values.