code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_descriptor_by_id(self, id, is_master_id=None):
"""GetDescriptorById.
[Preview API]
:param str id:
:param bool is_master_id:
:rtype: :class:`<str> <azure.devops.v5_0.identity.models.str>`
"""
route_values = {}
if id is not None:
route_va... | GetDescriptorById.
[Preview API]
:param str id:
:param bool is_master_id:
:rtype: :class:`<str> <azure.devops.v5_0.identity.models.str>` |
def execute_java(classpath, main, jvm_options=None, args=None, executor=None,
workunit_factory=None, workunit_name=None, workunit_labels=None,
cwd=None, workunit_log_config=None, distribution=None,
create_synthetic_jar=True, synthetic_jar_dir=None, stdin=None):
"""Ex... | Executes the java program defined by the classpath and main.
If `workunit_factory` is supplied, does so in the context of a workunit.
:param list classpath: the classpath for the java program
:param string main: the fully qualified class name of the java program's entry point
:param list jvm_options: an optio... |
def _normalize_tags_type(self, tags, device_name=None, metric_name=None):
"""
Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list
"""
normalized_tags = []
if ... | Normalize tags contents and type:
- append `device_name` as `device:` tag
- normalize tags type
- doesn't mutate the passed list, returns a new list |
def by_location(self, location, cc=None):
"""
Perform a Yelp Neighborhood API Search based on a location specifier.
Args:
location - textual location specifier of form: "address, city, state or zip, optional country"
cc - ISO 3166-1 alpha-2 country code. (Optional)
... | Perform a Yelp Neighborhood API Search based on a location specifier.
Args:
location - textual location specifier of form: "address, city, state or zip, optional country"
cc - ISO 3166-1 alpha-2 country code. (Optional) |
def generate_mtime_map(opts, path_map):
'''
Generate a dict of filename -> mtime
'''
file_map = {}
for saltenv, path_list in six.iteritems(path_map):
for path in path_list:
for directory, _, filenames in salt.utils.path.os_walk(path):
for item in filenames:
... | Generate a dict of filename -> mtime |
def _set_persistent_module(mod):
'''
Add a module to loader.conf to make it persistent.
'''
if not mod or mod in mod_list(True) or mod not in \
available():
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
return set([mod]) | Add a module to loader.conf to make it persistent. |
def get_or_add_image_part(self, image_file):
"""
Return an ``(image_part, rId)`` 2-tuple corresponding to an
|ImagePart| object containing the image in *image_file*, and related
to this slide with the key *rId*. If either the image part or
relationship already exists, they are re... | Return an ``(image_part, rId)`` 2-tuple corresponding to an
|ImagePart| object containing the image in *image_file*, and related
to this slide with the key *rId*. If either the image part or
relationship already exists, they are reused, otherwise they are
newly created. |
def _hotellings_time(self):
""" hotelling's T2 tests for time domain waveforms"""
# get residuals
df = self._df
R = self._A - np.dot(self._X, self._Bhat)
Sigma_Z = np.dot(R.T,R)*(1./df)
# compute p-values
T_2_list = []
p_value_list = []
for i in np... | hotelling's T2 tests for time domain waveforms |
def __vciFormatError(library_instance, function, HRESULT):
""" Format a VCI error and attach failed function and decoded HRESULT
:param CLibrary library_instance:
Mapped instance of IXXAT vcinpl library
:param callable function:
Failed function
:param HRESULT HRESULT:... | Format a VCI error and attach failed function and decoded HRESULT
:param CLibrary library_instance:
Mapped instance of IXXAT vcinpl library
:param callable function:
Failed function
:param HRESULT HRESULT:
HRESULT returned by vcinpl call
:return:
... |
def _set_module_names_for_sphinx(modules: List, new_name: str):
""" Trick sphinx into displaying the desired module in these objects' documentation. """
for obj in modules:
obj.__module__ = new_name | Trick sphinx into displaying the desired module in these objects' documentation. |
def swipe_bottom(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.down(steps=steps) | Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details. |
def ignore_import_warnings_for_related_fields(orig_method, self, node):
"""
Replaces the leave_module method on the VariablesChecker class to
prevent unused-import warnings which are caused by the ForeignKey
and OneToOneField transformations. By replacing the nodes in the
AST with their type rather ... | Replaces the leave_module method on the VariablesChecker class to
prevent unused-import warnings which are caused by the ForeignKey
and OneToOneField transformations. By replacing the nodes in the
AST with their type rather than the django field, imports of the
form 'from django.db.models import OneToOn... |
def subs(self, *args):
"""Substitute a symbolic expression in ``['x', 'y', 'z']``
This is a wrapper around the substitution mechanism of
`sympy <http://docs.sympy.org/latest/tutorial/basic_operations.html>`_.
Any symbolic expression in the columns
``['x', 'y', 'z']`` of ``self``... | Substitute a symbolic expression in ``['x', 'y', 'z']``
This is a wrapper around the substitution mechanism of
`sympy <http://docs.sympy.org/latest/tutorial/basic_operations.html>`_.
Any symbolic expression in the columns
``['x', 'y', 'z']`` of ``self`` will be substituted
with ... |
def get(self, uri):
"""
Return node for uri or None if not exists:
{uri: x, content: y}
"""
cache_key = self._build_cache_key(uri)
value = self._get(cache_key)
if value is not None:
return self._decode_node(uri, value) | Return node for uri or None if not exists:
{uri: x, content: y} |
def job_history(backend):
"""Widget for displaying job history
Args:
backend (IBMQbackend): The backend.
Returns:
Tab: A tab widget for history images.
"""
year = widgets.Output(layout=widgets.Layout(display='flex-inline',
align_items='c... | Widget for displaying job history
Args:
backend (IBMQbackend): The backend.
Returns:
Tab: A tab widget for history images. |
def _fill_form_exclude_cols(self, exclude_cols, form):
"""
fill the form with the suppressed cols, generated from exclude_cols
"""
for filter_key in exclude_cols:
filter_value = self._filters.get_filter_value(filter_key)
rel_obj = self.datamodel.get_related_ob... | fill the form with the suppressed cols, generated from exclude_cols |
def setMinimumWidth(self, width):
"""
Sets the minimum width value to the inputed width and emits the \
sizeConstraintChanged signal.
:param width | <int>
"""
super(XView, self).setMinimumWidth(width)
if ( not self.signalsBlocked() ):
... | Sets the minimum width value to the inputed width and emits the \
sizeConstraintChanged signal.
:param width | <int> |
def get(self, key, default=None):
"""
Returns a list of payloads (as byte objects) for a given key
or ``default`` if the key is not found.
"""
if not isinstance(key, bytes):
key = key.encode('utf8')
return self.b_get_value(key) or default | Returns a list of payloads (as byte objects) for a given key
or ``default`` if the key is not found. |
def hours(start, end=None):
"""Iterate over the hours between the given datetime_tzs.
Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.
Returns:
An iterator which generates datetime_tz objects a hour apart.
... | Iterate over the hours between the given datetime_tzs.
Args:
start: datetime_tz to start from.
end: (Optional) Date to end at, if not given the iterator will never
terminate.
Returns:
An iterator which generates datetime_tz objects a hour apart. |
def cvm_unif_fix1(statistic):
"""
Approximates the first-term of the small sample count Gotze expansion.
After equation 1.10 (with coefficients pulled out as csa / csb).
"""
args = fix1_args / statistic
kvs = kv((.25, .75, 1.25), args[:, :, newaxis])
gs, hs = exp(-args) * tensordot(((1, 1, ... | Approximates the first-term of the small sample count Gotze expansion.
After equation 1.10 (with coefficients pulled out as csa / csb). |
def _init_map(self):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'] = \
self._zone_conditions_metadata['default_object_values'][0]
self.my_osid_object_form._my_map['coordinateConditions'] = \
self._coordinate_conditions_metadata['default_object_values'][0]
... | stub |
def _handle_processing_error(err, errstream, client):
"""Handle ProcessingError exceptions."""
errors = sorted(err.events, key=operator.attrgetter("index"))
failed = [e.event for e in errors]
silent = all(isinstance(e.error, OutOfOrderError) for e in errors)
if errstream:
_deliver_errored_e... | Handle ProcessingError exceptions. |
def from_product(cls, iterables, sortorder=None, names=None):
"""
Make a MultiIndex from the cartesian product of multiple iterables.
Parameters
----------
iterables : list / sequence of iterables
Each iterable has unique labels for each level of the index.
s... | Make a MultiIndex from the cartesian product of multiple iterables.
Parameters
----------
iterables : list / sequence of iterables
Each iterable has unique labels for each level of the index.
sortorder : int or None
Level of sortedness (must be lexicographically ... |
def pretty_template_plot(template, size=(10.5, 7.5), background=False,
picks=False, **kwargs):
"""
Plot of a single template, possibly within background data.
:type template: obspy.core.stream.Stream
:param template: Template stream to plot
:type size: tuple
:param size... | Plot of a single template, possibly within background data.
:type template: obspy.core.stream.Stream
:param template: Template stream to plot
:type size: tuple
:param size: tuple of plot size
:type background: obspy.core.stream.stream
:param background: Stream to plot the template within.
:... |
def enrich(self, columns):
""" This method appends at the end of the dataframe as many
rows as items are found in the list of elemnents in the
provided columns.
This assumes that the length of the lists for the several
specified columns is the same. As an example, for the row A
... | This method appends at the end of the dataframe as many
rows as items are found in the list of elemnents in the
provided columns.
This assumes that the length of the lists for the several
specified columns is the same. As an example, for the row A
{"C1":"V1", "C2":field1, "C3":f... |
def copy_path_to_clipboard(self):
"""
Copies the file path to the clipboard
"""
path = self.get_current_path()
QtWidgets.QApplication.clipboard().setText(path)
debug('path copied: %s' % path) | Copies the file path to the clipboard |
def users_forgot_password(self, email, **kwargs):
"""Send email to reset your password."""
return self.__call_api_post('users.forgotPassword', email=email, data=kwargs) | Send email to reset your password. |
def _fetch_AlignmentMapper(self, tx_ac, alt_ac, alt_aln_method):
"""
Get a new AlignmentMapper for the given transcript accession (ac),
possibly caching the result.
"""
return hgvs.alignmentmapper.AlignmentMapper(
self.hdp, tx_ac=tx_ac, alt_ac=alt_ac, alt_aln_method=a... | Get a new AlignmentMapper for the given transcript accession (ac),
possibly caching the result. |
def tree_to_stream(entries, write):
"""Write the give list of entries into a stream using its write method
:param entries: **sorted** list of tuples with (binsha, mode, name)
:param write: write method which takes a data string"""
ord_zero = ord('0')
bit_mask = 7 # 3 bits set
for bin... | Write the give list of entries into a stream using its write method
:param entries: **sorted** list of tuples with (binsha, mode, name)
:param write: write method which takes a data string |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`ManageOffer`.
"""
selling = self.selling.to_xdr_object()
buying = self.buying.to_xdr_object()
price = Operation.to_xdr_price(self.price)
price = Xdr.types.Price(price['n'], p... | Creates an XDR Operation object that represents this
:class:`ManageOffer`. |
def chshell(name, shell):
'''
Change the default shell of the user
CLI Example:
.. code-block:: bash
salt '*' user.chshell foo /bin/zsh
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
... | Change the default shell of the user
CLI Example:
.. code-block:: bash
salt '*' user.chshell foo /bin/zsh |
def on_action_begin(self, action, logs={}):
""" Called at beginning of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_begin', None)):
callback.on_action_begin(action, logs=logs) | Called at beginning of each action for each callback in callbackList |
def _id(self):
"""What this object is equal to."""
return (self.__class__, self.number_of_needles, self.needle_positions,
self.left_end_needle) | What this object is equal to. |
def url_download(url, topath=None, create_dirs=True):
'''
url_download(url) yields the contents of the given url as a byte-string.
url_download(url, topath) downloads the given url to the given path, topath and yields that path
on success.
The option create_dirs (default: True) may be set to Fals... | url_download(url) yields the contents of the given url as a byte-string.
url_download(url, topath) downloads the given url to the given path, topath and yields that path
on success.
The option create_dirs (default: True) may be set to False to prevent the topath directory from
being created. |
def _convert_rename(self, fc):
"""Convert a FileRenameCommand into a new FileCommand.
:return: None if the rename is being ignored, otherwise a
new FileCommand based on the whether the old and new paths
are inside or outside of the interesting locations.
"""
old = ... | Convert a FileRenameCommand into a new FileCommand.
:return: None if the rename is being ignored, otherwise a
new FileCommand based on the whether the old and new paths
are inside or outside of the interesting locations. |
def save_all(yaml_dicts, filepath):
'''
Save *all* YAML settings to the specified file path.
'''
yamldict.dump_all(yaml_dicts, open(filepath, 'w'),
default_flow_style=False) | Save *all* YAML settings to the specified file path. |
def _validate_config(self, config):
"""
Validates some parts of the module config
:type config: dict[str, dict[str, Any] | str]
:param config: The module config
"""
required_keys = [
self.KEY_IDP_CONFIG,
self.KEY_ENDPOINTS,
]
if no... | Validates some parts of the module config
:type config: dict[str, dict[str, Any] | str]
:param config: The module config |
def stop(self, timeout=None):
"""
Stops the task thread. Synchronous!
"""
with self._lock:
if self._thread:
self._queue.put_nowait(self._terminator)
self._thread.join(timeout=timeout)
self._thread = None
self._th... | Stops the task thread. Synchronous! |
def get_organization(self, **kwargs):
"""Get the organization to which the user belongs
Returns:
dictionary of the response
"""
resp = self._get(self._u(self._ORGANIZATION_ENDPOINT_SUFFIX),
**kwargs)
resp.raise_for_status()
return res... | Get the organization to which the user belongs
Returns:
dictionary of the response |
def insert(self, index, child, **kwargs):
'''add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended.
... | add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended. |
def get_explore_posts(self) -> Iterator[Post]:
"""Get Posts which are worthy of exploring suggested by Instagram.
:return: Iterator over Posts of the user's suggested posts.
"""
data = self.context.get_json('explore/', {})
yield from (Post(self.context, node)
... | Get Posts which are worthy of exploring suggested by Instagram.
:return: Iterator over Posts of the user's suggested posts. |
def groups(self):
""" returns the group object """
return Groups(url="%s/groups" % self.root,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initalize=False) | returns the group object |
def settings_api():
"""
Virtual ``settings.py`` with values transported from real
:mod:`settings.py`, so the Brython frontend may be configured same way as
backend.
Some of the critical values are intentionally left out.
"""
variables = [
"%s = %s" % (var, repr(getattr(settings, var... | Virtual ``settings.py`` with values transported from real
:mod:`settings.py`, so the Brython frontend may be configured same way as
backend.
Some of the critical values are intentionally left out. |
def check_file_paths(self, *args):
"""
Ensure all arguments provided correspond to a file
"""
for path in enumerate(args):
path = path[1]
if path is not None:
try:
self.check_file_path(path)
except OSError as ex:... | Ensure all arguments provided correspond to a file |
def AddOption(self, descriptor, constant=False):
"""Registers an option with the configuration system.
Args:
descriptor: A TypeInfoObject instance describing the option.
constant: If this is set, the option is treated as a constant - it can be
read at any time (before parsing the configurat... | Registers an option with the configuration system.
Args:
descriptor: A TypeInfoObject instance describing the option.
constant: If this is set, the option is treated as a constant - it can be
read at any time (before parsing the configuration) and it's an error to
try to override it in ... |
def version_state(name, prefix=False, no_content=False):
"""
If the server state exists return parsed json as a python object or True
prefix=True returns True if any files exist with ls [prefix]*
"""
if env.project_fullname: full_name = '-'.join([env.project_fullname,name])
else: full_name = na... | If the server state exists return parsed json as a python object or True
prefix=True returns True if any files exist with ls [prefix]* |
def libvlc_video_set_aspect_ratio(p_mi, psz_aspect):
'''Set new video aspect ratio.
@param p_mi: the media player.
@param psz_aspect: new video aspect-ratio or NULL to reset to default @note Invalid aspect ratios are ignored.
'''
f = _Cfunctions.get('libvlc_video_set_aspect_ratio', None) or \
... | Set new video aspect ratio.
@param p_mi: the media player.
@param psz_aspect: new video aspect-ratio or NULL to reset to default @note Invalid aspect ratios are ignored. |
def split(self, into = "edges", loc = None,
at = "labels", sort_index = True):
"""
Returns the decomposition of the elements.
Inputs:
* into: must be in ['edges', 'faces', 'simplices', 'angles']
* loc: None or labels of the chosen elements.
* at: must be in ['labels', 'coords']... | Returns the decomposition of the elements.
Inputs:
* into: must be in ['edges', 'faces', 'simplices', 'angles']
* loc: None or labels of the chosen elements.
* at: must be in ['labels', 'coords'] |
def _delete_deployment(self, deployment_name):
""" Delete deployment """
api_response = self.kube_client.delete_namespaced_deployment(
name=deployment_name,
namespace=self.namespace,
body=client.V1DeleteOptions(
propagation_policy='Foreground',
... | Delete deployment |
def color(self) -> str:
"""Get a random name of color.
:return: Color name.
:Example:
Red.
"""
colors = self._data['color']
return self.random.choice(colors) | Get a random name of color.
:return: Color name.
:Example:
Red. |
def guest_create_disks(self, userid, disk_list):
"""Add disks to an existing guest vm.
:param userid: (str) the userid of the vm to be created
:param disk_list: (list) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
... | Add disks to an existing guest vm.
:param userid: (str) the userid of the vm to be created
:param disk_list: (list) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
each disk, the root disk should be the first element in the... |
def is_game_over(self, *, claim_draw: bool = False) -> bool:
"""
Checks if the game is over due to
:func:`checkmate <chess.Board.is_checkmate()>`,
:func:`stalemate <chess.Board.is_stalemate()>`,
:func:`insufficient material <chess.Board.is_insufficient_material()>`,
the :... | Checks if the game is over due to
:func:`checkmate <chess.Board.is_checkmate()>`,
:func:`stalemate <chess.Board.is_stalemate()>`,
:func:`insufficient material <chess.Board.is_insufficient_material()>`,
the :func:`seventyfive-move rule <chess.Board.is_seventyfive_moves()>`,
:func:... |
def load_krebsregister(block=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
missing_values=None, shuffle=True):
"""Load the Krebsregister dataset.
This dataset of comparison patterns was obtained in a
epidemiological cancer study in Germany. The comparison patterns
were created by the Institut... | Load the Krebsregister dataset.
This dataset of comparison patterns was obtained in a
epidemiological cancer study in Germany. The comparison patterns
were created by the Institute for Medical Biostatistics,
Epidemiology and Informatics (IMBEI) and the University Medical
Center of Johannes Gutenber... |
def measurementReport():
"""MEASUREMENT REPORT Section 9.1.21"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x15) # 00010101
c = MeasurementResults()
packet = a / b / c
return packet | MEASUREMENT REPORT Section 9.1.21 |
def write_run_output(run, **kwargs):
"""Writes PolyChord output files corresponding to the input nested sampling
run. The file root is
.. code-block:: python
root = os.path.join(run['output']['base_dir'],
run['output']['file_root'])
Output files which can be made w... | Writes PolyChord output files corresponding to the input nested sampling
run. The file root is
.. code-block:: python
root = os.path.join(run['output']['base_dir'],
run['output']['file_root'])
Output files which can be made with this function (see the PolyChord
doc... |
def _patch_dict(diff, base):
"""Patch a dictionary, substituting in changed items from the nested diff.
"""
for k, v in diff.items():
if isinstance(v, dict):
base[k] = _patch_dict(v, base.get(k, {}))
elif not v:
base.pop(k, None)
else:
base[k] = v
... | Patch a dictionary, substituting in changed items from the nested diff. |
def parse(cls, args):
"""
Parse command line arguments to construct a dictionary of command
parameters that can be used to create a command
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used in create method
Raises:
... | Parse command line arguments to construct a dictionary of command
parameters that can be used to create a command
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used in create method
Raises:
ParseError: when the arguments are no... |
def saves(self, store_password):
"""
Saves the keystore so that it can be read by other applications.
If any of the private keys are unencrypted, they will be encrypted
with the same password as the keystore.
:param str store_password: Password for the created keystore
... | Saves the keystore so that it can be read by other applications.
If any of the private keys are unencrypted, they will be encrypted
with the same password as the keystore.
:param str store_password: Password for the created keystore
(and for any unencrypted keys)
:returns: A... |
def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
index):
"""Creates a method descriptor from a MethodDescriptorProto.
Args:
method_proto: The proto describing the method.
service_name: The name of the containing service.
package: Optional... | Creates a method descriptor from a MethodDescriptorProto.
Args:
method_proto: The proto describing the method.
service_name: The name of the containing service.
package: Optional package name to look up for types.
scope: Scope containing available types.
index: Index of the method in ... |
def starts_new_line(item: str) -> bool:
"""
Returns True if the given element should start a new report line
"""
if item in TAF_NEWLINE:
return True
for start in TAF_NEWLINE_STARTSWITH:
if item.startswith(start):
return True
return False | Returns True if the given element should start a new report line |
def _temporary_filenames(total):
"""Context manager to create temporary files and remove them after use."""
temp_files = [_get_temporary_filename('optimage-') for i in range(total)]
yield temp_files
for temp_file in temp_files:
try:
os.remove(temp_file)
except OSError:
... | Context manager to create temporary files and remove them after use. |
def _get_specification(self, specification):
"""
Read the specification provided. It can either be a url or a file
location.
"""
result = six.moves.urllib.parse.urlparse(specification)
# If the specification has an http or an https scheme we can
# retrieve it via... | Read the specification provided. It can either be a url or a file
location. |
def format_page(self, page, link_resolver, output):
"""
Called by `project.Project.format_page`, to leave full control
to extensions over the formatting of the pages they are
responsible of.
Args:
page: tree.Page, the page to format.
link_resolver: links.... | Called by `project.Project.format_page`, to leave full control
to extensions over the formatting of the pages they are
responsible of.
Args:
page: tree.Page, the page to format.
link_resolver: links.LinkResolver, object responsible
for resolving links pot... |
def save_nd_to_pickle(nd, path='', filename=None):
"""Use pickle to save the whole nd-object to disc
The network instance is entirely pickled to a file.
Parameters
----------
nd : NetworkDing0
Ding0 grid container object
path : str
Absolute or relative path where pickle should ... | Use pickle to save the whole nd-object to disc
The network instance is entirely pickled to a file.
Parameters
----------
nd : NetworkDing0
Ding0 grid container object
path : str
Absolute or relative path where pickle should be saved. Default is ''
which means pickle is save... |
def apply_queryset_rules(self, qs):
"""
First collect all filter/exclude kwargs and apply any annotations.
Then apply all filters at once, and all excludes at once.
"""
clauses = {
'filter': [],
'exclude': []}
for rule in self.drip_model.queryset_... | First collect all filter/exclude kwargs and apply any annotations.
Then apply all filters at once, and all excludes at once. |
def parse_list(cls, api, json_list):
"""
Parse a list of JSON objects into
a result set of model instances.
"""
results = []
for json_obj in json_list:
if json_obj:
obj = cls.parse(api, json_obj)
results.append(obj)
... | Parse a list of JSON objects into
a result set of model instances. |
def call (self, to, **options):
"""
Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code.
Arguments: to is a String.
Argument: **options is a set of optional keyword arguments.
See https://www.tropo.com/d... | Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code.
Arguments: to is a String.
Argument: **options is a set of optional keyword arguments.
See https://www.tropo.com/docs/webapi/call |
def _dump(self, tree):
""" Run a DUMP statement """
schema = []
if tree.tables:
for table in tree.tables:
desc = self.describe(table, refresh=True, require=True)
schema.append(desc.schema)
else:
for table in self.describe_all():
... | Run a DUMP statement |
def add_or_update(uid, post_data):
'''
Add or update the post.
'''
cur_rec = MPost.get_by_uid(uid)
if cur_rec:
MPost.update(uid, post_data)
else:
MPost.create_post(uid, post_data) | Add or update the post. |
def block_windows(self, res=None): # setter and getter ?
"""Load windows for chunks-wise processing from raster internal tiling (first raster of given resolution).
Arguments:
res {numeric} -- Resolution determining the raster (1st of resolution group) from which to take the tiling.
... | Load windows for chunks-wise processing from raster internal tiling (first raster of given resolution).
Arguments:
res {numeric} -- Resolution determining the raster (1st of resolution group) from which to take the tiling. |
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = Duration.lex_pattern.match(text)
if m is None:
raise EvaluateException('Illegal duration', ps.Backtrace(elt))
d = m.groupdict()... | convert text into typecode specific data. |
def init(self, settings_file="zappa_settings.json"):
"""
Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.
This should probably be broken up into few separate componants once it's stable.
Testing these inputs requires monkeypatching with mock, whi... | Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.
This should probably be broken up into few separate componants once it's stable.
Testing these inputs requires monkeypatching with mock, which isn't pretty. |
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or... | Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found. |
def parse_argv(self, argv=None):
# type: (Optional[tuple]) -> dict
"""
Parses arguments for the command.
:param argv:
Arguments to pass to the argument parser.
If ``None``, defaults to ``sys.argv[1:]``.
"""
arguments = vars(self.create_argument_pa... | Parses arguments for the command.
:param argv:
Arguments to pass to the argument parser.
If ``None``, defaults to ``sys.argv[1:]``. |
def display_view(self):
"""Update information about the size of the traces."""
self.idx_start.setText(str(self.parent.value('window_start')))
self.idx_length.setText(str(self.parent.value('window_length')))
self.idx_scaling.setText(str(self.parent.value('y_scale')))
self.idx_dist... | Update information about the size of the traces. |
def insert_media(self, url):
"""Inserts Virtual Media to the device
:param url: URL to image.
:raises: SushyError, on an error from iLO.
"""
try:
super(VirtualMedia, self).insert_media(url, write_protected=True)
except sushy_exceptions.SushyError:
... | Inserts Virtual Media to the device
:param url: URL to image.
:raises: SushyError, on an error from iLO. |
def prettify(elem):
# from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.etree import ElementTree
from xml.dom import minidom
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseS... | Return a pretty-printed XML string for the Element. |
def write_grid_tpl(self,name,tpl_file,zn_array):
""" write a template file a for grid-based multiplier parameters
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write
zn_array : numpy.ndarray
... | write a template file a for grid-based multiplier parameters
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write
zn_array : numpy.ndarray
an array used to skip inactive cells
Returns
... |
def _robust_column_name(base_name, column_names):
"""
Generate a new column name that is guaranteed not to conflict with an
existing set of column names.
Parameters
----------
base_name : str
The base of the new column name. Usually this does not conflict with
the existing colum... | Generate a new column name that is guaranteed not to conflict with an
existing set of column names.
Parameters
----------
base_name : str
The base of the new column name. Usually this does not conflict with
the existing column names, in which case this function simply returns
`b... |
def login(self, principal, loginProperties):
"""
Parameters:
- principal
- loginProperties
"""
self.send_login(principal, loginProperties)
return self.recv_login() | Parameters:
- principal
- loginProperties |
def get_form(self, key, form_class=None):
"""
Returns an instance of the form to be used in this view.
"""
if form_class is None:
form_class = self.get_form_class(key)
return form_class(**self.get_form_kwargs(key)) | Returns an instance of the form to be used in this view. |
def random_split(df, first_portion=.1):
"""Randomly sample Dataframe rows. Typically for testset/training set cross-valication
random_split(pd.DataFrame())
"""
mask = np.random.binomial(1, first_portion, size=len(df)).astype(bool)
return df[mask].copy(), df[~mask].copy() | Randomly sample Dataframe rows. Typically for testset/training set cross-valication
random_split(pd.DataFrame()) |
def CLI(ctx, config, list_lookups):
"""Lookup basic phone number information or send SMS messages"""
loglevel = 'info'
verbosity = getattr(logging, loglevel.upper(), 'INFO')
#verbosity = logging.DEBUG
ctx.obj = {
'verbosity': verbosity,
'logfile': None,
'config': {'lookups': ... | Lookup basic phone number information or send SMS messages |
def connect(self):
"""Connect to beanstalkd server."""
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(self._connect_timeout)
SocketError.wrap(self._socket.connect, (self.host, self.port))
self._socket.settimeout(None)
self._socket... | Connect to beanstalkd server. |
def strftime_string(C, msformat):
"convert Word date/time picture (msformat) into a strftime format string"
s = msformat
s = re.sub(r"%", "%%", s) # percent sign
s = re.sub(r"(?<!%)\b(y(?:yyy)?)\b", "%Y", s) # 4-digit year
s = re.sub(r"(?<!%)\b(yy)\b", "%y", s... | convert Word date/time picture (msformat) into a strftime format string |
def this_year(self):
""" Get AnnouncementRequests from this school year only. """
start_date, end_date = get_date_range_this_year()
return Announcement.objects.filter(added__gte=start_date, added__lte=end_date) | Get AnnouncementRequests from this school year only. |
def _add_model(self, model):
"""
Save this model as one existing on this database, to deny many models
with same namespace and name.
If the model already exists, check if it is the same. It can happen if the
module is imported twice in different ways.
If it's a new model ... | Save this model as one existing on this database, to deny many models
with same namespace and name.
If the model already exists, check if it is the same. It can happen if the
module is imported twice in different ways.
If it's a new model or an existing and valid one, return the model in... |
def metadata(sceneid, pmin=2, pmax=98, **kwargs):
"""
Return band bounds and statistics.
Attributes
----------
sceneid : str
CBERS sceneid.
pmin : int, optional, (default: 2)
Histogram minimum cut.
pmax : int, optional, (default: 98)
Histogram maximum cut.
kwargs... | Return band bounds and statistics.
Attributes
----------
sceneid : str
CBERS sceneid.
pmin : int, optional, (default: 2)
Histogram minimum cut.
pmax : int, optional, (default: 98)
Histogram maximum cut.
kwargs : optional
These are passed to 'rio_tiler.utils.raste... |
def reset_input_generators(self, seed):
"""
Helper method which explicitly resets all input generators
to the derived generator. This should only ever be called
for testing or debugging.
"""
seed_generator = SeedGenerator().reset(seed=seed)
for gen in self.input_... | Helper method which explicitly resets all input generators
to the derived generator. This should only ever be called
for testing or debugging. |
def print_tf_op(tf_op, indent="| ", max_depth=-1, depth=0):
""" print_tf_op(tf_tensor, indent=" ", max_depth=-1)
Prints the dependency graph of a tensorflow operation *tf_op*, where each new level is indented
by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where each
... | print_tf_op(tf_tensor, indent=" ", max_depth=-1)
Prints the dependency graph of a tensorflow operation *tf_op*, where each new level is indented
by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where each
tensor and each op count as a level. |
def FromDict(cls, obj):
"""Create an IOTileEvent from the result of a previous call to asdict().
Args:
obj (dict): A dictionary produced by a call to IOTileEvent.asdict()
Returns:
IOTileEvent: The converted IOTileEvent object.
"""
timestamp = obj.get('t... | Create an IOTileEvent from the result of a previous call to asdict().
Args:
obj (dict): A dictionary produced by a call to IOTileEvent.asdict()
Returns:
IOTileEvent: The converted IOTileEvent object. |
def add_block_parser(subparsers, parent_parser):
"""Adds arguments parsers for the block list and block show commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object
"""
parser = subparsers.add_parser(
'... | Adds arguments parsers for the block list and block show commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object |
def get_node_mapping(H):
"""Generates mappings between the set of nodes and integer indices (where
every node corresponds to exactly 1 integer index).
:param H: the hypergraph to find the node mapping on.
:returns: dict -- for each integer index, maps the index to the node.
dict -- for ea... | Generates mappings between the set of nodes and integer indices (where
every node corresponds to exactly 1 integer index).
:param H: the hypergraph to find the node mapping on.
:returns: dict -- for each integer index, maps the index to the node.
dict -- for each node, maps the node to the in... |
def add_units(self, units, factor, latexrepr=None):
"""
Add new possible units.
:arg units: units
:type units: :class:`str`
:arg factor: multiplication factor to convert new units into base units
:type factor: :class:`float`
:arg latexr... | Add new possible units.
:arg units: units
:type units: :class:`str`
:arg factor: multiplication factor to convert new units into base units
:type factor: :class:`float`
:arg latexrepr: LaTeX representation of units (if ``None``, use *units)
:ty... |
def draw_label(self, layout_info, ax):
"""
Draw facet label onto the axes.
This function will only draw labels if they are needed.
Parameters
----------
layout_info : dict-like
facet information
ax : axes
Axes to label
"""
... | Draw facet label onto the axes.
This function will only draw labels if they are needed.
Parameters
----------
layout_info : dict-like
facet information
ax : axes
Axes to label |
def buy_margin(self):
"""
[float] 买方向保证金
"""
return sum(position.buy_margin for position in six.itervalues(self._positions)) | [float] 买方向保证金 |
def configure(level=logging.WARNING, handler=None, formatter=None):
"""Configure Logr
@param handler: Logger message handler
@type handler: logging.Handler or None
@param formatter: Logger message Formatter
@type formatter: logging.Formatter or None
"""
if forma... | Configure Logr
@param handler: Logger message handler
@type handler: logging.Handler or None
@param formatter: Logger message Formatter
@type formatter: logging.Formatter or None |
def collect(self):
"""
Collects resources usage of each process defined under the
`process` subsection of the config file
"""
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No process resource metrics retrieved')
retur... | Collects resources usage of each process defined under the
`process` subsection of the config file |
def _serie_format(self, serie, value):
"""Format an independent value for the serie"""
kwargs = {'chart': self, 'serie': serie, 'index': None}
formatter = (serie.formatter or self.formatter or self._value_format)
kwargs = filter_kwargs(formatter, kwargs)
return formatter(value, ... | Format an independent value for the serie |
def _order_as_range(order):
"""Convert a hyphenated string representing order for derivative or
exponential terms into a range object that can be passed as input to the
appropriate expansion function."""
order = order.split('-')
order = [int(o) for o in order]
if len(order) > 1:
order = ... | Convert a hyphenated string representing order for derivative or
exponential terms into a range object that can be passed as input to the
appropriate expansion function. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.