code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def histogram_voltage(self, timestep=None, title=True, **kwargs): """ Plots histogram of voltages. For more information see :func:`edisgo.tools.plots.histogram`. Parameters ---------- timestep : :pandas:`pandas.Timestamp<timestamp>` or None, optional Specifi...
Plots histogram of voltages. For more information see :func:`edisgo.tools.plots.histogram`. Parameters ---------- timestep : :pandas:`pandas.Timestamp<timestamp>` or None, optional Specifies time step histogram is plotted for. If timestep is None all time steps ...
def yaml_dump(data, stream=None): # type: (YamlData, Optional[TextIO]) -> Text """ Dump data to a YAML string/file. Args: data (YamlData): The data to serialize as YAML. stream (TextIO): The file-like object to save to. If given, this function will write ...
Dump data to a YAML string/file. Args: data (YamlData): The data to serialize as YAML. stream (TextIO): The file-like object to save to. If given, this function will write the resulting YAML to that stream. Returns: str: The YAML string.
def _dict_increment(self, dictionary, key): """Increments the value of the dictionary at the specified key.""" if key in dictionary: dictionary[key] += 1 else: dictionary[key] = 1
Increments the value of the dictionary at the specified key.
def reply_message(self, reply_token, messages, timeout=None): """Call reply message API. https://devdocs.line.me/en/#reply-message Respond to events from users, groups, and rooms. Webhooks are used to notify you when an event occurs. For events that you can respond to, a reply...
Call reply message API. https://devdocs.line.me/en/#reply-message Respond to events from users, groups, and rooms. Webhooks are used to notify you when an event occurs. For events that you can respond to, a replyToken is issued for replying to messages. Because the replyToken...
def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str, password: str) -> Membership: """ Get a Membership document :param membership_type: "IN" to ask for membership or "OUT" to cancel membership :param current_block: Current bl...
Get a Membership document :param membership_type: "IN" to ask for membership or "OUT" to cancel membership :param current_block: Current block data :param identity: Identity document :param salt: Passphrase of the account :param password: Password of the account :rtype: Membership
def define(cls, name, parent=None, interleave=False): """Create define node.""" node = cls("define", parent, interleave=interleave) node.occur = 0 node.attr["name"] = name return node
Create define node.
def _member_def(self, member): """ Return an individual member definition formatted as an RST glossary entry, wrapped to fit within 78 columns. """ member_docstring = textwrap.dedent(member.docstring).strip() member_docstring = textwrap.fill( member_docstring,...
Return an individual member definition formatted as an RST glossary entry, wrapped to fit within 78 columns.
def make_application_error(name, tag): """ Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Er...
Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Error.as_application_condition`. Keep in mind th...
def authorization_url(self, **kwargs): """ Get authorization URL to redirect the resource owner to. https://tools.ietf.org/html/rfc6749#section-4.1.1 :param str redirect_uri: (optional) Absolute URL of the client where the user-agent will be redirected to. :param st...
Get authorization URL to redirect the resource owner to. https://tools.ietf.org/html/rfc6749#section-4.1.1 :param str redirect_uri: (optional) Absolute URL of the client where the user-agent will be redirected to. :param str scope: (optional) Space delimited list of strings. ...
def cartesian_to_index(ranges, maxima=None): """ Inverts tuples from a cartesian product to a numeric index ie. the index this tuple would have in a cartesian product. Each column gets multiplied with a place value according to the preceding columns maxmimum and all columns are sum...
Inverts tuples from a cartesian product to a numeric index ie. the index this tuple would have in a cartesian product. Each column gets multiplied with a place value according to the preceding columns maxmimum and all columns are summed up. This function in the same direction as utils...
def readFromProto(cls, proto): """ Read state from proto object. :param proto: SDRClassifierRegionProto capnproto object """ instance = cls() instance.implementation = proto.implementation instance.steps = proto.steps instance.stepsList = [int(i) for i in proto.steps.split(",")] in...
Read state from proto object. :param proto: SDRClassifierRegionProto capnproto object
def _get_operator_param_name_and_values(operator_class_name, task_details): """ Internal helper gets the name of the python parameter for the Airflow operator class. In some cases, we do not expose the airflow parameter name in its native form, but choose to expose a name that's more standard for Datala...
Internal helper gets the name of the python parameter for the Airflow operator class. In some cases, we do not expose the airflow parameter name in its native form, but choose to expose a name that's more standard for Datalab, or one that's more friendly. For example, Airflow's BigQueryOperator uses '...
def atFontFace(self, declarations): """ Embed fonts """ result = self.ruleset([self.selector('*')], declarations) data = list(result[0].values())[0] if "src" not in data: # invalid - source is required, ignore this specification return {}, {} ...
Embed fonts
def set_bank_1(self, bits): """ Sets gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be set. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of...
Sets gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be set. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the gpios. ... pi.set_bank_1(i...
def make_form(fields=None, layout=None, layout_class=None, base_class=None, get_form_field=None, name=None, rules=None, **kwargs): """ Make a from according dict data: {'fields':[ {'name':'name', 'type':'str', 'label':'label, 'rules':{ 'requ...
Make a from according dict data: {'fields':[ {'name':'name', 'type':'str', 'label':'label, 'rules':{ 'required': 'email' 'required:back|front' #back means server side, front means front side } ...
def acquire_lock(self): """ Acquire the lock. Blocks indefinitely until lock is available unless `lock_timeout` was supplied. If the lock_timeout elapses, raises LockTimeout. """ # first ensure that a record exists for this session id try: self.collection.insert_one(dict(_id=self.id)) except pymongo....
Acquire the lock. Blocks indefinitely until lock is available unless `lock_timeout` was supplied. If the lock_timeout elapses, raises LockTimeout.
def windowed(seq, n, fillvalue=None, step=1): """Return a sliding window of width *n* over the given iterable. >>> all_windows = windowed([1, 2, 3, 4, 5], 3) >>> list(all_windows) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] When the window is larger than the iterable, *fillvalue* is used in plac...
Return a sliding window of width *n* over the given iterable. >>> all_windows = windowed([1, 2, 3, 4, 5], 3) >>> list(all_windows) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] When the window is larger than the iterable, *fillvalue* is used in place of missing values:: >>> list(windowed(...
def add_JSsource(self, new_src): """add additional js script source(s)""" if isinstance(new_src, list): for h in new_src: self.JSsource.append(h) elif isinstance(new_src, basestring): self.JSsource.append(new_src) else: raise OptionType...
add additional js script source(s)
def oauth_client_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/oauth_clients#create-client" api_path = "/api/v2/oauth/clients.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/oauth_clients#create-client
def autodiff(func, wrt=(0,), optimized=True, motion='joint', mode='reverse', preserve_result=False, check_dims=True, input_derivative=INPUT_DERIVATIVE.Required, verbose=0): """Build the vector-Jacobian or Jacobian-...
Build the vector-Jacobian or Jacobian-vector product of a function `func`. For a vector-Jacobian product (reverse-mode autodiff): This function proceeds by finding the primals and adjoints of all the functions in the call tree. For a Jacobian-vector product (forward-mode autodiff): We first find the primals ...
def stop(logfile, time_format): "stop tracking for the active project" def save_and_output(records): records = server.stop(records) write(records, logfile, time_format) def output(r): print "worked on %s" % colored(r[0], attrs=['bold']) print " from %s" % colored( server.date_t...
stop tracking for the active project
def knx_to_time(knxdata): """Converts a KNX time to a tuple of a time object and the day of week""" if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to time") dow = knxdata[0] >> 5 res = time(knxdata[0] & 0x1f, knxdata[1], knxdata[2]) return [res, dow]
Converts a KNX time to a tuple of a time object and the day of week
def ram_dp_rf(clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob): ''' RAM: Dual-Port, Read-First ''' memL = [Signal(intbv(0)[len(dia):]) for _ in range(2**len(addra))] @always(clka.posedge) def writea(): if wea: memL[int(addra)].next = dia doa.next = memL[int(addra)] ...
RAM: Dual-Port, Read-First
def get_dependency_graph_for_set(self, id, **kwargs): """ Gets dependency graph for a Build Group Record (running and completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invo...
Gets dependency graph for a Build Group Record (running and completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respons...
def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict: """Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either a direct expression (equal to `expr` for a successful match), or an instance of :class:`Pattern`. expr: the expression to...
Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either a direct expression (equal to `expr` for a successful match), or an instance of :class:`Pattern`. expr: the expression to be matched
def dict2dzn( objs, declare=False, assign=True, declare_enums=True, wrap=True, fout=None ): """Serializes the objects in input and produces a list of strings encoding them into dzn format. Optionally, the produced dzn is written on a file. Supported types of objects include: ``str``, ``int``, ``float``...
Serializes the objects in input and produces a list of strings encoding them into dzn format. Optionally, the produced dzn is written on a file. Supported types of objects include: ``str``, ``int``, ``float``, ``set``, ``list`` or ``dict``. List and dict are serialized into dzn (multi-dimensional) arra...
def add_node(self, payload): """ Returns ------- int Identifier for the inserted node. """ self.nodes.append(Node(len(self.nodes), payload)) return len(self.nodes) - 1
Returns ------- int Identifier for the inserted node.
def logging_syslog_facility_local(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras") syslog_facility = ET.SubElement(logging, "syslog-facility") local = ET.SubEleme...
Auto Generated Code
def load_default_moderator(): """ Find a moderator object """ if appsettings.FLUENT_COMMENTS_DEFAULT_MODERATOR == 'default': # Perform spam checks return moderation.FluentCommentsModerator(None) elif appsettings.FLUENT_COMMENTS_DEFAULT_MODERATOR == 'deny': # Deny all comments...
Find a moderator object
def find_or_create_by_name(self, item_name, items_list, item_type): """ See if item with item_name exists in item_list. If not, create that item. Either way, return an item of type item_type. """ item = self.find_by_name(item_name, items_list) if not item: ...
See if item with item_name exists in item_list. If not, create that item. Either way, return an item of type item_type.
def _ensure_set_contains(test_object, required_object, test_set_name=None): """ Ensure that the required entries (set or keys of a dict) are present in the test set or keys of the test dict. :param set|dict test_object: The test set or dict :param set|dict required_object: The entries that need to ...
Ensure that the required entries (set or keys of a dict) are present in the test set or keys of the test dict. :param set|dict test_object: The test set or dict :param set|dict required_object: The entries that need to be present in the test set (keys of input dict if input is dict) :param ...
def tvdb_login(api_key): """ Logs into TVDb using the provided api key Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister Online docs: api.thetvdb.com/swagger#!/Authentication/post_login= """ url = "https://api.thetvdb.com/login" body = {"apikey": api_key} status, co...
Logs into TVDb using the provided api key Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister Online docs: api.thetvdb.com/swagger#!/Authentication/post_login=
def complex_validates(validate_rule): """Quickly setup attributes validation by one-time, based on `sqlalchemy.orm.validates`. Don't like `sqlalchemy.orm.validates`, you don't need create many model method, as long as pass formatted validate rule. (Cause of SQLAlchemy's validate mechanism, you need ass...
Quickly setup attributes validation by one-time, based on `sqlalchemy.orm.validates`. Don't like `sqlalchemy.orm.validates`, you don't need create many model method, as long as pass formatted validate rule. (Cause of SQLAlchemy's validate mechanism, you need assignment this funciton's return value to a...
def get_members(self, api=None): """Retrieve dataset members :param api: Api instance :return: Collection object """ api = api or self._API response = api.get(url=self._URL['members'].format(id=self.id)) data = response.json() total = response.headers['x...
Retrieve dataset members :param api: Api instance :return: Collection object
def K(self, parm): """ Returns the Gram Matrix Parameters ---------- parm : np.ndarray Parameters for the Gram Matrix Returns ---------- - Gram Matrix (np.ndarray) """ return RQ_K_matrix(self.X, parm) + np.identity(self.X.shape[0])*(1...
Returns the Gram Matrix Parameters ---------- parm : np.ndarray Parameters for the Gram Matrix Returns ---------- - Gram Matrix (np.ndarray)
def delete(self, key, **kwargs): """DeleteRange deletes the given range from the key-value store. A delete request increments the revision of the key-value store and generates a delete event in the event history for every deleted key. :param key: :param kwargs: :return:...
DeleteRange deletes the given range from the key-value store. A delete request increments the revision of the key-value store and generates a delete event in the event history for every deleted key. :param key: :param kwargs: :return:
def load_app_resource(**kwargs): ''' :param kwargs: keyword args for :func:`~dxpy.bindings.search.find_one_data_object`, with the exception of "project" :raises: :exc:`~dxpy.exceptions.DXError` if "project" is given, if this is called with dxpy.JOB_ID not set, or if "DX_RESOURCES_ID" or "DX_PROJECT_CONTEXT_...
:param kwargs: keyword args for :func:`~dxpy.bindings.search.find_one_data_object`, with the exception of "project" :raises: :exc:`~dxpy.exceptions.DXError` if "project" is given, if this is called with dxpy.JOB_ID not set, or if "DX_RESOURCES_ID" or "DX_PROJECT_CONTEXT_ID" is not found in the environment variables...
def heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10): """ heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10) Produce a 2D plot of the distance matrix, with values encoded by coloured cells. Args: partition: treeCl.Partition object - if supplied, will reorder ...
heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10) Produce a 2D plot of the distance matrix, with values encoded by coloured cells. Args: partition: treeCl.Partition object - if supplied, will reorder rows and columns of the distance matrix to reflect ...
def apply(self, func, applyto='measurement', noneval=nan, setdata=False): """ Apply func either to self or to associated data. If data is not already parsed, try and read it. Parameters ---------- func : callable The function either accepts a measurement obje...
Apply func either to self or to associated data. If data is not already parsed, try and read it. Parameters ---------- func : callable The function either accepts a measurement object or an FCS object. Does some calculation and returns the result. applyto...
def submit_job(job_ini, username, hazard_job_id=None): """ Create a job object from the given job.ini file in the job directory and run it in a new process. Returns the job ID and PID. """ job_id = logs.init('job') oq = engine.job_from_file( job_ini, job_id, username, hazard_calculation_...
Create a job object from the given job.ini file in the job directory and run it in a new process. Returns the job ID and PID.
def dir_df_boot(dir_df, nb=5000, par=False): """ Performs a bootstrap for direction DataFrame with optional parametric bootstrap Parameters _________ dir_df : Pandas DataFrame with columns: dir_dec : mean declination dir_inc : mean inclination Required for parametric bootstrap...
Performs a bootstrap for direction DataFrame with optional parametric bootstrap Parameters _________ dir_df : Pandas DataFrame with columns: dir_dec : mean declination dir_inc : mean inclination Required for parametric bootstrap dir_n : number of data points in mean di...
def remove_container(self, container, **kwargs): """ Identical to :meth:`dockermap.client.base.DockerClientWrapper.remove_container` with additional logging. """ self.push_log("Removing container '{0}'.".format(container)) set_raise_on_error(kwargs) super(DockerFabricClie...
Identical to :meth:`dockermap.client.base.DockerClientWrapper.remove_container` with additional logging.
def _run_atstart(): '''Hook frameworks must invoke this before running the main hook body.''' global _atstart for callback, args, kwargs in _atstart: callback(*args, **kwargs) del _atstart[:]
Hook frameworks must invoke this before running the main hook body.
def _parse_uri(uri): """Parse and validate MediaFire URI.""" tokens = urlparse(uri) if tokens.netloc != '': logger.error("Invalid URI: %s", uri) raise ValueError("MediaFire URI format error: " "host should be empty - mf:///path") if...
Parse and validate MediaFire URI.
def execute(self): """ Main method to call to run the worker """ self.prepare_models() self.prepare_worker() if self.options.print_options: self.print_options() self.run()
Main method to call to run the worker
def get(self, source, media, collection=None, start_date=None, days=None, query=None, years=None, genres=None, languages=None, countries=None, runtimes=None, ratings=None, certifications=None, networks=None, status=None, **kwargs): """Retrieve calendar items. The `all` calendar ...
Retrieve calendar items. The `all` calendar displays info for all shows airing during the specified period. The `my` calendar displays episodes for all shows that have been watched, collected, or watchlisted. :param source: Calendar source (`all` or `my`) :type source: str :pa...
def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: """Get a list of sub-commands for an ArgumentParser""" sub_cmds = [] # Check if this is parser has sub-commands if parser is not None and parser._subparsers is not None: # Find the _SubParsersAction for the sub-commands of thi...
Get a list of sub-commands for an ArgumentParser
def pos_by_percent(self, x_percent, y_percent): """ Finds a point inside the box that is exactly at the given percentage place. :param x_percent: how much percentage from left edge :param y_percent: how much percentage from top edge :return: A point inside the box """ ...
Finds a point inside the box that is exactly at the given percentage place. :param x_percent: how much percentage from left edge :param y_percent: how much percentage from top edge :return: A point inside the box
def _retf(ins): """ Returns from a procedure / function a Floating Point (40bits) value """ output = _float_oper(ins.quad[1]) output.append('#pragma opt require a,bc,de') output.append('jp %s' % str(ins.quad[2])) return output
Returns from a procedure / function a Floating Point (40bits) value
def map_single_end(credentials, instance_config, instance_name, script_dir, index_dir, fastq_file, output_dir, num_threads=None, seed_start_lmax=None, mismatch_nmax=None, multimap_nmax=None, splice_min_overhang=None, out_mult...
Maps single-end reads using STAR. Reads are expected in FASTQ format. By default, they are also expected to be compressed with gzip. - recommended machine type: "n1-standard-16" (60 GB of RAM, 16 vCPUs). - recommended disk size: depends on size of FASTQ files, at least 128 GB. TODO: docstring
def create_hit(MaxAssignments=None, AutoApprovalDelayInSeconds=None, LifetimeInSeconds=None, AssignmentDurationInSeconds=None, Reward=None, Title=None, Keywords=None, Description=None, Question=None, RequesterAnnotation=None, QualificationRequirements=None, UniqueRequestToken=None, AssignmentReviewPolicy=None, HITRevie...
The CreateHIT operation creates a new Human Intelligence Task (HIT). The new HIT is made available for Workers to find and accept on the Amazon Mechanical Turk website. This operation allows you to specify a new HIT by passing in values for the properties of the HIT, such as its title, reward amount and number of a...
def handle_hooks(stage, hooks, provider, context, dump, outline): """Handle pre/post hooks. Args: stage (str): The name of the hook stage - pre_build/post_build. hooks (list): A list of dictionaries containing the hooks to execute. provider (:class:`stacker.provider.base.BaseProvider`):...
Handle pre/post hooks. Args: stage (str): The name of the hook stage - pre_build/post_build. hooks (list): A list of dictionaries containing the hooks to execute. provider (:class:`stacker.provider.base.BaseProvider`): The provider the current stack is using. context (:c...
def isdir(self, path=None, client_kwargs=None, virtual_dir=True, assume_exists=None): """ Return True if path is an existing directory. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. virtual_dir (bool): If True, checks if...
Return True if path is an existing directory. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. virtual_dir (bool): If True, checks if directory exists virtually if an object path if not exists as a specific object. assume_exi...
def main(arguments=None): """Main command line entry point.""" if not arguments: arguments = sys.argv[1:] wordlist, sowpods, by_length, start, end = argument_parser(arguments) for word in wordlist: pretty_print( word, anagrams_in_word(word, sowpods, start, end),...
Main command line entry point.
def handle_call(self, body, message): """Handle call message.""" try: r = self._DISPATCH(body, ticket=message.properties['reply_to']) except self.Next: # don't reply, delegate to other agents. pass else: self.reply(message, r)
Handle call message.
def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check to see if an RDS subnet group exists. CLI example:: salt myminion boto_rds.subnet_group_exists my-param-group \ region=us-east-1 ''' try: con...
Check to see if an RDS subnet group exists. CLI example:: salt myminion boto_rds.subnet_group_exists my-param-group \ region=us-east-1
def progress_view(shell): """ updates the view """ while not ShellProgressView.done: _, col = get_window_dim() col = int(col) progress = get_progress_message() if '\n' in progress: prog_list = progress.split('\n') prog_val = len(prog_list[-1]) else...
updates the view
def set_climate_hold(self, index, climate, hold_type="nextTransition"): ''' Set a climate hold - ie away, home, sleep ''' body = {"selection": { "selectionType": "thermostats", "selectionMatch": self.thermostats[index]['identifier']}, "functions": ...
Set a climate hold - ie away, home, sleep
def chop(array, epsilon=1e-10): """ Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero. """ ret = np.array(array) if np.isrea...
Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero.
def update_room_name(self): """Updates self.name and returns True if room name has changed.""" try: response = self.client.api.get_room_name(self.room_id) if "name" in response and response["name"] != self.name: self.name = response["name"] return ...
Updates self.name and returns True if room name has changed.
def list_handler(HandlerResult="nparray"): """Wraps a function to handle list inputs.""" def decorate(func): def wrapper(*args, **kwargs): """Run through the wrapped function once for each array element. :param HandlerResult: output type. Defaults to numpy arrays. ""...
Wraps a function to handle list inputs.
def from_api_repr(cls, resource, client): """Factory: construct a zone given its API representation :type resource: dict :param resource: zone resource representation returned from the API :type client: :class:`google.cloud.dns.client.Client` :param client: Client which holds ...
Factory: construct a zone given its API representation :type resource: dict :param resource: zone resource representation returned from the API :type client: :class:`google.cloud.dns.client.Client` :param client: Client which holds credentials and project config...
def add_paragraph(self, text='', style=None): """ Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, t...
Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, the result is as though the 'Normal' style was applied. Not...
def first(o): """If o is a ISeq, return the first element from o. If o is None, return None. Otherwise, coerces o to a Seq and returns the first.""" if o is None: return None if isinstance(o, ISeq): return o.first s = to_seq(o) if s is None: return None return s.first
If o is a ISeq, return the first element from o. If o is None, return None. Otherwise, coerces o to a Seq and returns the first.
def mod_bufsize(iface, *args, **kwargs): ''' Modify network interface buffers (currently linux only) CLI Example: .. code-block:: bash salt '*' network.mod_bufsize tx=<val> rx=<val> rx-mini=<val> rx-jumbo=<val> ''' if __grains__['kernel'] == 'Linux': if os.path.exists('/sbin/e...
Modify network interface buffers (currently linux only) CLI Example: .. code-block:: bash salt '*' network.mod_bufsize tx=<val> rx=<val> rx-mini=<val> rx-jumbo=<val>
def get_preferred(self, addr_1, addr_2): '''Return the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 return self._cache.get((addr_1, addr_2))
Return the preferred address.
def checkUserManage(worksheet, request, redirect=True): """ Checks if the current user has granted access to the worksheet and if has also privileges for managing it. If the user has no granted access and redirect's value is True, redirects to /manage_results view. Otherwise, does nothing ...
Checks if the current user has granted access to the worksheet and if has also privileges for managing it. If the user has no granted access and redirect's value is True, redirects to /manage_results view. Otherwise, does nothing
def get_version_url(self, version): """ Retrieve the URL for the designated version of the hive. """ for each_version in self.other_versions(): if version == each_version['version'] and 'location' in each_version: return each_version.get('location') ra...
Retrieve the URL for the designated version of the hive.
def delete(self, url, headers=None, **kwargs): """Sends a DELETE request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``...
Sends a DELETE request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: ...
def add_self_defined_objects(raw_objects): """Add self defined command objects for internal processing ; bp_rule, _internal_host_up, _echo, _internal_host_check, _interna_service_check :param raw_objects: Raw config objects dict :type raw_objects: dict :return: raw_objects with ...
Add self defined command objects for internal processing ; bp_rule, _internal_host_up, _echo, _internal_host_check, _interna_service_check :param raw_objects: Raw config objects dict :type raw_objects: dict :return: raw_objects with some more commands :rtype: dict
def _snakify_name(self, name): """Snakify a name string. In this context, "to snakify" means to strip a name of all diacritics, convert it to lower case, and replace any spaces inside the name with hyphens. This way the name is made "machine-friendly", and ready to be c...
Snakify a name string. In this context, "to snakify" means to strip a name of all diacritics, convert it to lower case, and replace any spaces inside the name with hyphens. This way the name is made "machine-friendly", and ready to be combined with a second name component into ...
def key_from_keybase(username, fingerprint=None): """Look up a public key from a username""" url = keybase_lookup_url(username) resp = requests.get(url) if resp.status_code == 200: j_resp = json.loads(polite_string(resp.content)) if 'them' in j_resp and len(j_resp['them']) == 1: ...
Look up a public key from a username
def revert(self, unchanged_only=False): """Revert all files in this changelist :param unchanged_only: Only revert unchanged files :type unchanged_only: bool :raises: :class:`.ChangelistError` """ if self._reverted: raise errors.ChangelistError('This changelis...
Revert all files in this changelist :param unchanged_only: Only revert unchanged files :type unchanged_only: bool :raises: :class:`.ChangelistError`
def text_extract(path, password=None): """Extract text from a PDF file""" pdf = Info(path, password).pdf return [pdf.getPage(i).extractText() for i in range(pdf.getNumPages())]
Extract text from a PDF file
def create_process_behavior(self, behavior, process_id): """CreateProcessBehavior. [Preview API] Creates a single behavior in the given process. :param :class:`<ProcessBehaviorCreateRequest> <azure.devops.v5_0.work_item_tracking_process.models.ProcessBehaviorCreateRequest>` behavior: :pa...
CreateProcessBehavior. [Preview API] Creates a single behavior in the given process. :param :class:`<ProcessBehaviorCreateRequest> <azure.devops.v5_0.work_item_tracking_process.models.ProcessBehaviorCreateRequest>` behavior: :param str process_id: The ID of the process :rtype: :class:`<P...
def get_relationships_for_source_on_date(self, source_id, from_, to): """Pass through to provider RelationshipLookupSession.get_relationships_for_source_on_date""" # Implemented from azosid template for - # osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template...
Pass through to provider RelationshipLookupSession.get_relationships_for_source_on_date
def _initializer_wrapper(actual_initializer, *rest): """ We ignore SIGINT. It's up to our parent to kill us in the typical condition of this arising from ``^C`` on a terminal. If someone is manually killing us with that signal, well... nothing will happen. """ signal.signal(signal.SIGINT, signa...
We ignore SIGINT. It's up to our parent to kill us in the typical condition of this arising from ``^C`` on a terminal. If someone is manually killing us with that signal, well... nothing will happen.
def add_seconds(self, datetimestr, n): """Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = self.parse_datetime(datetim...
Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。
def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return with self._lock: try: stream_created = self.open() for message in email_messages: if six...
Write all messages to the stream in a thread-safe way.
def dump_info(): '''Shows various details about the account & servers''' vultr = Vultr(API_KEY) try: logging.info('Listing account info:\n%s', dumps( vultr.account.info(), indent=2 )) logging.info('Listing apps:\n%s', dumps( vultr.app.list(), indent=2 ...
Shows various details about the account & servers
def params_values(self): """ Get a list of the ``Parameter`` values if they have a value. This does not include the basis regularizer. """ return [p.value for p in atleast_list(self.params) if p.has_value]
Get a list of the ``Parameter`` values if they have a value. This does not include the basis regularizer.
def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1): """Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object""" QUERY =( """ SELECT """ """ COORD1(CENTROID(Plane.position_bounds)) AS "RAJ2000", COORD2(CENTROID(Plane.position_bounds)) AS "DEJ...
Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object
def loader_for_type(self, ctype): """ Gets a function ref to deserialize content for a certain mimetype. """ for loadee, mimes in Mimer.TYPES.iteritems(): for mime in mimes: if ctype.startswith(mime): return loadee
Gets a function ref to deserialize content for a certain mimetype.
def obtainInfo(self): """ Method for obtaining information about the movie. """ try: info = self.ytdl.extract_info(self.yid, download=False) except youtube_dl.utils.DownloadError: raise ConnectionError if not self.preferences['stream']: ...
Method for obtaining information about the movie.
def make_levels_set(levels): '''make set efficient will convert all lists of items in levels to a set to speed up operations''' for level_key,level_filters in levels.items(): levels[level_key] = make_level_set(level_filters) return levels
make set efficient will convert all lists of items in levels to a set to speed up operations
def interactive_update_stack(self, fqn, template, old_parameters, parameters, stack_policy, tags, **kwargs): """Update a Cloudformation stack in interactive mode. Args: fqn (str): The fully qualified name of the Cloudformatio...
Update a Cloudformation stack in interactive mode. Args: fqn (str): The fully qualified name of the Cloudformation stack. template (:class:`stacker.providers.base.Template`): A Template object to use when updating the stack. old_parameters (list): A list of d...
def _get_absolute_reference(self, ref_key): """Returns absolute reference code for key.""" key_str = u", ".join(map(str, ref_key)) return u"S[" + key_str + u"]"
Returns absolute reference code for key.
def filter(self, func): """ A lazy way to skip elements in the stream that gives False for the given function. """ self._data = xfilter(func, self._data) return self
A lazy way to skip elements in the stream that gives False for the given function.
def set_errors(self, errors): """Set parameter error estimate """ if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
Set parameter error estimate
def vdistg(v1, v2, ndim): """ Return the distance between two vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdistg_c.html :param v1: ndim-dimensional double precision vector. :type v1: list[ndim] :param v2: ndim-dimensional double precision vector. ...
Return the distance between two vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdistg_c.html :param v1: ndim-dimensional double precision vector. :type v1: list[ndim] :param v2: ndim-dimensional double precision vector. :type v2: list[ndim] :param ndi...
def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 """ return sum([x * y for x, y in zip(X, Y)])
Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230
def build_variant(variant, institute_id, gene_to_panels = None, hgncid_to_gene=None, sample_info=None): """Build a variant object based on parsed information Args: variant(dict) institute_id(str) gene_to_panels(dict): A dictionary with {...
Build a variant object based on parsed information Args: variant(dict) institute_id(str) gene_to_panels(dict): A dictionary with {<hgnc_id>: { 'panel_names': [<panel_name>, ..], 'disease_associated_transcripts': [<trans...
def _unsigned_bounds(self): """ Get lower bound and upper bound for `self` in unsigned arithmetic. :return: a list of (lower_bound, upper_bound) tuples. """ ssplit = self._ssplit() if len(ssplit) == 1: lb = ssplit[0].lower_bound ub = ssplit[0].up...
Get lower bound and upper bound for `self` in unsigned arithmetic. :return: a list of (lower_bound, upper_bound) tuples.
def process_embed(embed_items=None, embed_tracks=None, embed_metadata=None, embed_insights=None): """Returns an embed field value based on the parameters.""" result = None embed = '' if embed_items: embed = 'items' if embed_tracks: ...
Returns an embed field value based on the parameters.
def remove_block(self, block, index="-1"): """Remove block element from scope Args: block (Block): Block object """ self[index]["__blocks__"].remove(block) self[index]["__names__"].remove(block.raw())
Remove block element from scope Args: block (Block): Block object
def disassociate(self, eip_or_aid): """Disassociates an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. """ if "." in eip_or_aid: # If an IP is given (Classic) return "true" == self.call("Disassociat...
Disassociates an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp.
def from_raw(self, rval: RawValue, jptr: JSONPointer = "") -> Value: """Override the superclass method.""" def convert(val): if isinstance(val, list): res = ArrayValue([convert(x) for x in val]) elif isinstance(val, dict): res = ObjectValue({x: con...
Override the superclass method.
def get_user_logins(self, user_id, params={}): """ Return a user's logins for the given user_id. https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.index """ url = USERS_API.format(user_id) + "/logins" data = self._get_paged_resource(url, params=params...
Return a user's logins for the given user_id. https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.index
def invalid(cls, data, context=None): """Shortcut to create an INVALID Token.""" return cls(cls.TagType.INVALID, data, context)
Shortcut to create an INVALID Token.
def calc_max_flexural_wavelength(self): """ Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good characteristic...
Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good characteristic distance for any truncation limit