code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
self.when = options.browser_closer_when | Configure plugin. Plugin is enabled by default. |
def update_container(self, container, metadata, **kwargs):
"""Update container metadata
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param metadata(dict): additional metadata to include in the request.
:param **kwargs(di... | Update container metadata
:param container: container name (Container is equivalent to
Bucket term in Amazon).
:param metadata(dict): additional metadata to include in the request.
:param **kwargs(dict): extend args for specific driver. |
def _update_config_tags(self,directory,files=None):
"""
Loads tags information from file and updates on flickr,
only reads first line. Format is comma separated eg.
travel, 2010, South Africa, Pretoria
If files is None, will update all files in DB, otherwise
will only up... | Loads tags information from file and updates on flickr,
only reads first line. Format is comma separated eg.
travel, 2010, South Africa, Pretoria
If files is None, will update all files in DB, otherwise
will only update files that are in the flickr DB and files list |
def loader():
"""Load image from URL, and preprocess for Resnet."""
url = request.args.get('url') # read image URL as a request URL param
response = requests.get(url) # make request to static image file
return response.content | Load image from URL, and preprocess for Resnet. |
def hostedzone_from_element(zone):
"""
Construct a L{HostedZone} instance from a I{HostedZone} XML element.
"""
return HostedZone(
name=maybe_bytes_to_unicode(zone.find("Name").text).encode("ascii").decode("idna"),
identifier=maybe_bytes_to_unicode(zone.find("Id").text).replace(u"/hosted... | Construct a L{HostedZone} instance from a I{HostedZone} XML element. |
def maybe_convert_platform(values):
""" try to do platform conversion, allow ndarray or list here """
if isinstance(values, (list, tuple)):
values = construct_1d_object_array_from_listlike(list(values))
if getattr(values, 'dtype', None) == np.object_:
if hasattr(values, '_values'):
... | try to do platform conversion, allow ndarray or list here |
def disable_constant(parameterized):
"""
Temporarily set parameters on Parameterized object to
constant=False.
"""
params = parameterized.params().values()
constants = [p.constant for p in params]
for p in params:
p.constant = False
try:
yield
except:
raise
... | Temporarily set parameters on Parameterized object to
constant=False. |
def str2dn(dn, flags=0):
"""
This function takes a DN as string as parameter and returns
a decomposed DN. It's the inverse to dn2str().
flags describes the format of the dn
See also the OpenLDAP man-page ldap_str2dn(3)
"""
# if python2, we need unicode string
if not isinstance(dn, six... | This function takes a DN as string as parameter and returns
a decomposed DN. It's the inverse to dn2str().
flags describes the format of the dn
See also the OpenLDAP man-page ldap_str2dn(3) |
def make_coord_dict(subs, subscript_dict, terse=True):
"""
This is for assisting with the lookup of a particular element, such that the output
of this function would take the place of %s in this expression
`variable.loc[%s]`
Parameters
----------
subs: list of strings
coordinates, ... | This is for assisting with the lookup of a particular element, such that the output
of this function would take the place of %s in this expression
`variable.loc[%s]`
Parameters
----------
subs: list of strings
coordinates, either as names of dimensions, or positions within a dimension
... |
def identityRequest():
"""IDENTITY REQUEST Section 9.2.10"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x8) # 00001000
c = IdentityTypeAndSpareHalfOctets()
packet = a / b / c
return packet | IDENTITY REQUEST Section 9.2.10 |
def clean_folder_path(path, expected=None):
'''
:param path: A folder path to sanitize and parse
:type path: string
:param expected: Whether a folder ("folder"), a data object ("entity"), or either (None) is expected
:type expected: string or None
:returns: *folderpath*, *name*
Unescape and... | :param path: A folder path to sanitize and parse
:type path: string
:param expected: Whether a folder ("folder"), a data object ("entity"), or either (None) is expected
:type expected: string or None
:returns: *folderpath*, *name*
Unescape and parse *path* as a folder path to possibly an entity
... |
def get(feature, obj, **kwargs):
'''Obtain a feature from a set of morphology objects
Parameters:
feature(string): feature to extract
obj: a neuron, population or neurite tree
**kwargs: parameters to forward to underlying worker functions
Returns:
features as a 1D or 2D num... | Obtain a feature from a set of morphology objects
Parameters:
feature(string): feature to extract
obj: a neuron, population or neurite tree
**kwargs: parameters to forward to underlying worker functions
Returns:
features as a 1D or 2D numpy array. |
def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an estimator.
Arguments:
features: The input features for the estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionar... | Builds the model function for use in an estimator.
Arguments:
features: The input features for the estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionary.
config: The RunConfig, unused here.
Returns:
... |
def assertDateTimesBefore(self, sequence, target, strict=True, msg=None):
'''Fail if any elements in ``sequence`` are not before
``target``.
If ``target`` is iterable, it must have the same length as
``sequence``
If ``strict=True``, fail unless all elements in ``sequence``
... | Fail if any elements in ``sequence`` are not before
``target``.
If ``target`` is iterable, it must have the same length as
``sequence``
If ``strict=True``, fail unless all elements in ``sequence``
are strictly less than ``target``. If ``strict=False``, fail
unless all e... |
def create_defaults_for(session, user, only_for=None, detail_values=None):
""" Create a sizable amount of defaults for a new user. """
detail_values = detail_values or {}
if not user.openid.endswith('.fedoraproject.org'):
log.warn("New user not from fedoraproject.org. No defaults set.")
r... | Create a sizable amount of defaults for a new user. |
def equilibrium_transition_matrix(Xi, omega, sigma, reversible=True, return_lcc=True):
"""
Compute equilibrium transition matrix from OOM components:
Parameters
----------
Xi : ndarray(M, N, M)
matrix of set-observable operators
omega: ndarray(M,)
information state vector of OOM... | Compute equilibrium transition matrix from OOM components:
Parameters
----------
Xi : ndarray(M, N, M)
matrix of set-observable operators
omega: ndarray(M,)
information state vector of OOM
sigma : ndarray(M,)
evaluator of OOM
reversible : bool, optional, default=True
... |
def toggle_sensor(request, sensorname):
"""
This is used only if websocket fails
"""
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sens... | This is used only if websocket fails |
def KL_divergence(P,Q):
'''
Compute the KL divergence between distributions P and Q
P and Q should be dictionaries linking symbols to probabilities.
the keys to P and Q should be the same.
'''
assert(P.keys()==Q.keys())
distance = 0
for k in P.keys():
distance += P[k] *... | Compute the KL divergence between distributions P and Q
P and Q should be dictionaries linking symbols to probabilities.
the keys to P and Q should be the same. |
def database_path(self):
"""
Full database path. Includes the default location + the database filename.
"""
filename = self.database_filename
db_path = ":memory:" if filename == ":memory:" else (
path.abspath(path.join(__file__, "../..", "..", "data", filename)))
... | Full database path. Includes the default location + the database filename. |
def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True):
"""The slicenet model, main step used for training."""
with tf.variable_scope("slicenet"):
# Project to hidden size if necessary
if inputs.get_shape().as_list()[-1] != hparams.hidden_size:
inputs = common_layers.conv_bloc... | The slicenet model, main step used for training. |
def element_wise_op(array, other, op, ty):
"""
Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+... | Operation of series and other, element-wise (binary operator add)
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second Input array
op (str): Op string used to compute element-wise operation (+ / *)
ty (WeldType): Type of each element in th... |
def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path | Retrieves the Python library directory path. |
def update_name(self):
"""
Update the name of the Plan in Stripe and in the db.
Assumes the object being called has the name attribute already
reset, but has not been saved.
Stripe does not allow for update of any other Plan attributes besides name.
"""
p = self.api_retrieve()
p.name = self.name
p.... | Update the name of the Plan in Stripe and in the db.
Assumes the object being called has the name attribute already
reset, but has not been saved.
Stripe does not allow for update of any other Plan attributes besides name. |
def insert_paths(self):
"""Inserts a base path into the sys.path list if one is specified in
the configuration.
"""
if self.args.path:
sys.path.insert(0, self.args.path)
if hasattr(self.config.application, config.PATHS):
if hasattr(self.config.applicatio... | Inserts a base path into the sys.path list if one is specified in
the configuration. |
async def power(source, exponent):
"""Raise the elements of an asynchronous sequence to the given power."""
async with streamcontext(source) as streamer:
async for item in streamer:
yield item ** exponent | Raise the elements of an asynchronous sequence to the given power. |
def set_fluxinfo(self):
""" Uses list of known flux calibrators (with models in CASA) to find full name given in scan.
"""
knowncals = ['3C286', '3C48', '3C147', '3C138']
# find scans with knowncals in the name
sourcenames = [self.sources[source]['source'] for source in self.so... | Uses list of known flux calibrators (with models in CASA) to find full name given in scan. |
def create(cls, **kw):
"""
Create an instance of this class, first cleaning up the keyword
arguments so they will fill in any required values.
@return: an instance of C{cls}
"""
for k, v in kw.items():
attr = getattr(cls, k, None)
if isinstance(at... | Create an instance of this class, first cleaning up the keyword
arguments so they will fill in any required values.
@return: an instance of C{cls} |
def _get_populate_values(self, instance) -> Tuple[str, str]:
"""Gets all values (for each language) from the
specified's instance's `populate_from` field.
Arguments:
instance:
The instance to get the values from.
Returns:
A list of (lang_code, va... | Gets all values (for each language) from the
specified's instance's `populate_from` field.
Arguments:
instance:
The instance to get the values from.
Returns:
A list of (lang_code, value) tuples. |
def _import_model(models, crumbs):
"""
Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata
"""
logger_jsons.info("enter import_model".format(crumbs))
_models = OrderedDict()
... | Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata |
def UpdateWorkerStatus(
self, identifier, status, pid, used_memory, display_name,
number_of_consumed_sources, number_of_produced_sources,
number_of_consumed_events, number_of_produced_events,
number_of_consumed_event_tags, number_of_produced_event_tags,
number_of_consumed_reports, number_o... | Updates the status of a worker.
Args:
identifier (str): worker identifier.
status (str): human readable status of the worker e.g. 'Idle'.
pid (int): process identifier (PID).
used_memory (int): size of used memory in bytes.
display_name (str): human readable of the file entry currentl... |
def write_branch_data(self, file, padding=" "):
""" Writes branch data in Graphviz DOT language.
"""
attrs = ['%s="%s"' % (k,v) for k,v in self.branch_attr.iteritems()]
attr_str = ", ".join(attrs)
for br in self.case.branches:
file.write("%s%s -> %s [%s];\n" % \
... | Writes branch data in Graphviz DOT language. |
def _AbortJoin(self, timeout=None):
"""Aborts all registered processes by joining with the parent process.
Args:
timeout (int): number of seconds to wait for processes to join, where
None represents no timeout.
"""
for pid, process in iter(self._processes_per_pid.items()):
logger.... | Aborts all registered processes by joining with the parent process.
Args:
timeout (int): number of seconds to wait for processes to join, where
None represents no timeout. |
def serve_doc(app, url):
"""
Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at
"""
@app.route(url, doc=False)
def index(env, req):
ret = ''
for d in env['doc']:
ret += ... | Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at |
def get_output(self, idx=-1):
"""
Return an additional output of the instruction
:rtype: string
"""
buff = ""
data = self.get_data()
buff += repr(data) + " | "
for i in range(0, len(data)):
buff += "\\x%02x" % data[i]
return... | Return an additional output of the instruction
:rtype: string |
def find_file(self, path, saltenv, back=None):
'''
Find the path and return the fnd structure, this structure is passed
to other backend interfaces.
'''
path = salt.utils.stringutils.to_unicode(path)
saltenv = salt.utils.stringutils.to_unicode(saltenv)
back = self... | Find the path and return the fnd structure, this structure is passed
to other backend interfaces. |
def makeAggShkHist(self):
'''
Make simulated histories of aggregate transitory and permanent shocks. Histories are of
length self.act_T, for use in the general equilibrium simulation. This replicates the same
method for CobbDouglasEconomy; future version should create parent class.
... | Make simulated histories of aggregate transitory and permanent shocks. Histories are of
length self.act_T, for use in the general equilibrium simulation. This replicates the same
method for CobbDouglasEconomy; future version should create parent class.
Parameters
----------
Non... |
def log_message(self, format, *args):
"""
overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnin... | overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnings, 5XX as errors and everything else as INFO level. |
def get_pb_ids(self) -> List[str]:
"""Return the list of PB ids associated with the SBI.
Returns:
list, Processing block ids
"""
values = DB.get_hash_value(self._key, 'processing_block_ids')
return ast.literal_eval(values) | Return the list of PB ids associated with the SBI.
Returns:
list, Processing block ids |
def find_extensions_in(path: typing.Union[str, pathlib.Path]) -> list:
"""
Tries to find things that look like bot extensions in a directory.
"""
if not isinstance(path, pathlib.Path):
path = pathlib.Path(path)
if not path.is_dir():
return []
extension_names = []
# Find e... | Tries to find things that look like bot extensions in a directory. |
async def dispatch(self, request, view=None, **kwargs):
"""Process request."""
# Authorization endpoint
self.auth = await self.authorize(request, **kwargs) # noqa
# Load collection
self.collection = await self.get_many(request, **kwargs)
if request.method == 'POST' and... | Process request. |
def checkCytoscapeVersion(host=cytoscape_host,port=cytoscape_port):
"""
Checks cytoscape version
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
:returns: cytoscape and api version
"""
URL="http://"+str(host)+":"+str(port)+... | Checks cytoscape version
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
:returns: cytoscape and api version |
def render(self, *args, **kwargs):
"""This function accepts either a dict or some keyword arguments which
will then be the context the template is evaluated in. The return
value will be the rendered template.
:param context: the function accepts the same arguments as the
... | This function accepts either a dict or some keyword arguments which
will then be the context the template is evaluated in. The return
value will be the rendered template.
:param context: the function accepts the same arguments as the
:class:`dict` constructor.
:... |
def swap(self, kaxes, vaxes, size="150"):
"""
Swap axes from keys to values.
This is the core operation underlying shape manipulation
on the Spark bolt array. It exchanges an arbitrary set of axes
between the keys and the valeus. If either is None, will only
move axes in... | Swap axes from keys to values.
This is the core operation underlying shape manipulation
on the Spark bolt array. It exchanges an arbitrary set of axes
between the keys and the valeus. If either is None, will only
move axes in one direction (from keys to values, or values to keys).
... |
def hint_width(self):
"""Width of a column segment."""
return sum((len(self.style.delimiter),
self.wide,
len(self.style.delimiter),
len(u' '),
UCS_PRINTLEN + 2,
len(u' '),
self.style.n... | Width of a column segment. |
def _split_indices(self, concat_inds):
"""Take indices in 'concatenated space' and return as pairs
of (traj_i, frame_i)
"""
clengths = np.append([0], np.cumsum(self.__lengths))
mapping = np.zeros((clengths[-1], 2), dtype=int)
for traj_i, (start, end) in enumerate(zip(clen... | Take indices in 'concatenated space' and return as pairs
of (traj_i, frame_i) |
def unacknowledge_problem(self):
"""
Remove the acknowledge, reset the flag. The comment is deleted
:return: None
"""
if self.problem_has_been_acknowledged:
logger.debug("[item::%s] deleting acknowledge of %s",
self.get_name(),
... | Remove the acknowledge, reset the flag. The comment is deleted
:return: None |
def pickle_matpower_cases(case_paths, case_format=2):
""" Parses the MATPOWER case files at the given paths and pickles the
resulting Case objects to the same directory.
"""
import pylon.io
if isinstance(case_paths, basestring):
case_paths = [case_paths]
for case_path in case_paths... | Parses the MATPOWER case files at the given paths and pickles the
resulting Case objects to the same directory. |
def draw_tree(node, child_iter=lambda n: n.children, text_str=lambda n: str(n)):
"""
Args:
node: the root of the tree to be drawn,
child_iter: function that when called with a node, returns an iterable over all its children
text_str: turns a node into the text to be displayed in the tree... | Args:
node: the root of the tree to be drawn,
child_iter: function that when called with a node, returns an iterable over all its children
text_str: turns a node into the text to be displayed in the tree.
The default implementations of these two arguments retrieve the children by accessing ... |
def transfer_project(self, to_project_id, **kwargs):
"""Transfer a project to this group.
Args:
to_project_id (int): ID of the project to transfer
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication ... | Transfer a project to this group.
Args:
to_project_id (int): ID of the project to transfer
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTransferProjectError: If the pr... |
def project_ecef_vector_onto_sc(inst, x_label, y_label, z_label,
new_x_label, new_y_label, new_z_label,
meta=None):
"""Express input vector using s/c attitude directions
x - ram pointing
y - generally southward
z - generally nadir
... | Express input vector using s/c attitude directions
x - ram pointing
y - generally southward
z - generally nadir
Parameters
----------
x_label : string
Label used to get ECEF-X component of vector to be projected
y_label : string
Label used to get ECEF-Y component of... |
def namedb_get_num_blockstack_ops_at( db, block_id ):
"""
Get the number of name/namespace/token operations that occurred at a particular block.
"""
cur = db.cursor()
# preorders at this block
preorder_count_rows_query = "SELECT COUNT(*) FROM preorders WHERE block_number = ?;"
preorder_coun... | Get the number of name/namespace/token operations that occurred at a particular block. |
def remove_tweet(self, id):
"""
Delete a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise
"""
try:
self._client.destroy_status(id=id)
return True
except TweepError as e:
if e.api_code in [... | Delete a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise |
def read_trigger_parameters(filename):
"""Read the trigger parameters into trigger_parameter classes.
:type filename: str
:param filename: Parameter file
:returns: List of :class:`eqcorrscan.utils.trigger.TriggerParameters`
:rtype: list
.. rubric:: Example
>>> from eqcorrscan.utils.trigg... | Read the trigger parameters into trigger_parameter classes.
:type filename: str
:param filename: Parameter file
:returns: List of :class:`eqcorrscan.utils.trigger.TriggerParameters`
:rtype: list
.. rubric:: Example
>>> from eqcorrscan.utils.trigger import read_trigger_parameters
>>> para... |
def _wait_for_machine_booted(name, suffictinet_texts=None):
"""
Internal method
wait until machine is ready, in common case means there is running systemd-logind
:param name: str with machine name
:param suffictinet_texts: alternative text to check in output
:return: Tru... | Internal method
wait until machine is ready, in common case means there is running systemd-logind
:param name: str with machine name
:param suffictinet_texts: alternative text to check in output
:return: True or exception |
def create(name, *effects, **kwargs):
"""
Annotate a non-idempotent create action to the model being defined.
Should really be::
create(name, *effects, value=None, params=None, label=None, desc=None)
but it is not supported by python < 3.
@param name: item name unique for the model being defi... | Annotate a non-idempotent create action to the model being defined.
Should really be::
create(name, *effects, value=None, params=None, label=None, desc=None)
but it is not supported by python < 3.
@param name: item name unique for the model being defined.
@type name: str or unicode
@param eff... |
def get_empty_dtype_and_na(join_units):
"""
Return dtype and N/A values to use when concatenating specified units.
Returned N/A value may be None which means there was no casting involved.
Returns
-------
dtype
na
"""
if len(join_units) == 1:
blk = join_units[0].block
... | Return dtype and N/A values to use when concatenating specified units.
Returned N/A value may be None which means there was no casting involved.
Returns
-------
dtype
na |
def time_from_match(match_object):
"""Create a time object from a regular expression match.
The regular expression match is expected to be from RE_TIME or RE_DATETIME.
@param match_object: The regular expression match.
@type value: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetim... | Create a time object from a regular expression match.
The regular expression match is expected to be from RE_TIME or RE_DATETIME.
@param match_object: The regular expression match.
@type value: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{time} |
def _normalize_name(name):
"""Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type'
"""
try:
return HTTPHeaders._normalized_headers[name]
except KeyError:
if HTTPHeaders._NORMALIZED_HEADER_RE.match(nam... | Converts a name to Http-Header-Case.
>>> HTTPHeaders._normalize_name("coNtent-TYPE")
'Content-Type' |
def _general_multithread(func):
""" return the general multithreading function using func """
def multithread(templates, stream, *args, **kwargs):
with pool_boy(ThreadPool, len(stream), **kwargs) as pool:
return _pool_normxcorr(templates, stream, pool=pool, func=func)
return multithrea... | return the general multithreading function using func |
def remove(self, username=None):
"""Remove User instance based on supplied user name."""
self._user_list = [user for user in self._user_list if user.name != username] | Remove User instance based on supplied user name. |
def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int:
""" Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. """
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self._game_info.te... | Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. |
def batch_commit(self, message):
"""
Instead of committing a lot of small commits you can batch it together using this controller.
Example:
with git.batch_commit('BATCHED'):
git.commit_file('my commit 1', 'path/to/file', 'content from file')
git.commit_json_file... | Instead of committing a lot of small commits you can batch it together using this controller.
Example:
with git.batch_commit('BATCHED'):
git.commit_file('my commit 1', 'path/to/file', 'content from file')
git.commit_json_file('[1, 2, 3]', 'path/to/file2', 'json array')
... |
def create_context(self, message_queue, task_id):
"""
Create values to be used by create_small_file function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly
"""
... | Create values to be used by create_small_file function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly |
def get_defaults(self):
"""Use argparse to determine and return dict of defaults."""
# dont need 'required' to determine the default
options = [copy.copy(opt) for opt in self._options]
for opt in options:
try:
del opt.kwargs['required']
except KeyE... | Use argparse to determine and return dict of defaults. |
def log_print_response(logger, response):
"""
Log an HTTP response data
:param logger: logger to use
:param response: HTTP response ('Requests' lib)
:return: None
"""
log_msg = '<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\n'
log_msg += '\t< Response code: {}\n'.format(str(respons... | Log an HTTP response data
:param logger: logger to use
:param response: HTTP response ('Requests' lib)
:return: None |
def get_data_generator_by_id(hardware_source_id, sync=True):
"""
Return a generator for data.
:param bool sync: whether to wait for current frame to finish then collect next frame
NOTE: a new ndarray is created for each call.
"""
hardware_source = HardwareSourceManager().get_hardwa... | Return a generator for data.
:param bool sync: whether to wait for current frame to finish then collect next frame
NOTE: a new ndarray is created for each call. |
def index_documents(self, fresh_docs, model):
"""
Update fresh index with new documents (potentially replacing old ones with
the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc)
that maps document_id->document.
"""
docids = fresh_docs.key... | Update fresh index with new documents (potentially replacing old ones with
the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc)
that maps document_id->document. |
def map_across_full_axis(self, axis, map_func):
"""Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - column... | Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - columns).
map_func: The function to apply.
R... |
def read_i2c_block_data(self, address, register, length):
"""
I2C block transactions do not limit the number of bytes transferred
but the SMBus layer places a limit of 32 bytes.
I2C Block Read: i2c_smbus_read_i2c_block_data()
================================================
... | I2C block transactions do not limit the number of bytes transferred
but the SMBus layer places a limit of 32 bytes.
I2C Block Read: i2c_smbus_read_i2c_block_data()
================================================
This command reads a block of bytes from a device, from a
design... |
def get_logger(name):
"""Return logger with null handler added if needed."""
if not hasattr(logging.Logger, 'trace'):
logging.addLevelName(TRACE_LEVEL, 'TRACE')
def trace(self, message, *args, **kwargs):
if self.isEnabledFor(TRACE_LEVEL):
# Yes, logger takes its '*ar... | Return logger with null handler added if needed. |
def update_objective(self, objective_form):
"""Updates an existing objective.
arg: objective_form (osid.learning.ObjectiveForm): the form
containing the elements to be updated
raise: IllegalState - ``objective_form`` already used in an
update transaction
... | Updates an existing objective.
arg: objective_form (osid.learning.ObjectiveForm): the form
containing the elements to be updated
raise: IllegalState - ``objective_form`` already used in an
update transaction
raise: InvalidArgument - the form contains an inva... |
def setFont(self, font):
"""
Assigns the font to this widget and all of its children.
:param font | <QtGui.QFont>
"""
super(XTimeEdit, self).setFont(font)
# update the fonts for the time combos
self._hourCombo.setFont(font)
self._minuteCom... | Assigns the font to this widget and all of its children.
:param font | <QtGui.QFont> |
def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
dmdxs = []
... | Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples. |
def isdir(self, relpath, rsc=None):
"""
Returns whether or not the resource is a directory.
:return <bool>
"""
filepath = self.find(relpath, rsc)
if filepath.startswith(':'):
resource = QtCore.QResource(filepath)
return not re... | Returns whether or not the resource is a directory.
:return <bool> |
def queryset(self, request, queryset):
"""Filter queryset using params from the form."""
if self.form.is_valid():
# get no null params
filter_params = dict(
filter(lambda x: bool(x[1]), self.form.cleaned_data.items())
)
return queryset.filt... | Filter queryset using params from the form. |
def _on_drawing(self, object, name, old, new):
""" Handles the containers of drawing components being set.
"""
attrs = [ "drawing", "arrowhead_drawing" ]
others = [getattr(self, a) for a in attrs \
if (a != name) and (getattr(self, a) is not None)]
x, y = self.compo... | Handles the containers of drawing components being set. |
def to_array(self):
"""
Serializes this Animation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Animation, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array[... | Serializes this Animation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def proxy(self):
"""Retrieve the upstream content and build an HttpResponse."""
headers = self.request.headers.filter(self.ignored_request_headers)
qs = self.request.query_string if self.pass_query_string else ''
# Fix for django 1.10.0 bug https://code.djangoproject.com/ticket/27005
... | Retrieve the upstream content and build an HttpResponse. |
def _process_mappings(self, limit=None):
"""
This function imports linkage mappings of various entities
to genetic locations in cM or cR.
Entities include sequence variants, BAC ends, cDNA, ESTs, genes,
PAC ends, RAPDs, SNPs, SSLPs, and STSs.
Status: NEEDS REVIEW
... | This function imports linkage mappings of various entities
to genetic locations in cM or cR.
Entities include sequence variants, BAC ends, cDNA, ESTs, genes,
PAC ends, RAPDs, SNPs, SSLPs, and STSs.
Status: NEEDS REVIEW
:param limit:
:return: |
def Mean(self):
"""Computes the mean of a PMF.
Returns:
float mean
"""
mu = 0.0
for x, p in self.d.iteritems():
mu += p * x
return mu | Computes the mean of a PMF.
Returns:
float mean |
def accuracy(self, outputs):
'''Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
representing the outputs of a computat... | Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
representing the outputs of a computation graph.
Returns
----... |
def acquire(self, timeout=None):
"""Acquires the lock if in the unlocked state otherwise switch
back to the parent coroutine.
"""
green = getcurrent()
parent = green.parent
if parent is None:
raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet')
... | Acquires the lock if in the unlocked state otherwise switch
back to the parent coroutine. |
def similar(self):
"""
iterator over similar artists as :class:`Artist` objects
"""
if self._similar is None:
self._similar = [
Artist(artist['ArtistID'], artist['Name'], self._connection)
for artist in self._connection.request(
... | iterator over similar artists as :class:`Artist` objects |
def read(self, sensors):
"""Read a set of keys."""
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}
if self.sma_sid is None:
yield from self.new_session()
if self.sma_sid is None:
return False
body = yield from self._fetch_jso... | Read a set of keys. |
def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and makes a copy of it for later
use/inspection.
:param image: Image to display.
:type image: PIL.Image.Image
"""
assert(image.size == self.size)
self.image = self.preprocess(image).copy() | Takes a :py:mod:`PIL.Image` and makes a copy of it for later
use/inspection.
:param image: Image to display.
:type image: PIL.Image.Image |
def _analyze(self):
'''Run-once function to generate analysis over all series, considering both full and partial data.
Initializes the self.analysis dict which maps:
(non-reference) column/series -> 'full' and/or 'partial' -> stats dict returned by get_xy_dataset_statistics
'''... | Run-once function to generate analysis over all series, considering both full and partial data.
Initializes the self.analysis dict which maps:
(non-reference) column/series -> 'full' and/or 'partial' -> stats dict returned by get_xy_dataset_statistics |
def getTreeWalker(treeType, implementation=None, **kwargs):
"""Get a TreeWalker class for various types of tree with built-in support
treeType - the name of the tree type required (case-insensitive). Supported
values are:
"dom" - The xml.dom.minidom DOM implementation
... | Get a TreeWalker class for various types of tree with built-in support
treeType - the name of the tree type required (case-insensitive). Supported
values are:
"dom" - The xml.dom.minidom DOM implementation
"pulldom" - The xml.dom.pulldom event stream
... |
def notifyAppend(self, queue, force):
'''
Internal notify for sub-queues
:returns: If the append is blocked by parent, an EventMatcher is returned, None else.
'''
if not force and not self.canAppend():
self.isWaited = True
return self._matcher
... | Internal notify for sub-queues
:returns: If the append is blocked by parent, an EventMatcher is returned, None else. |
def build_penalties(self):
"""
builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_diag[lam0 * P0, lam1 * ... | builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_diag[lam0 * P0, lam1 * P1, lam2 * P2, ... , lamm * Pm]
Param... |
def _patch_distribution_metadata_write_pkg_info():
"""
Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local
encoding to save the pkg_info. Monkey-patch its write_pkg_info method to
correct this undesirable behavior.
"""
environment_local = (3,) <= sys.version_info[:3] < (3, ... | Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local
encoding to save the pkg_info. Monkey-patch its write_pkg_info method to
correct this undesirable behavior. |
def render_compressed(self, package, package_name, package_type):
"""Render HTML for the package.
If ``PIPELINE_ENABLED`` is ``True``, this will render the package's
output file (using :py:meth:`render_compressed_output`). Otherwise,
this will render the package's source files (using
... | Render HTML for the package.
If ``PIPELINE_ENABLED`` is ``True``, this will render the package's
output file (using :py:meth:`render_compressed_output`). Otherwise,
this will render the package's source files (using
:py:meth:`render_compressed_sources`).
Subclasses can override... |
def parse_iso_utc(s):
"""
Parses an ISO time with a hard-coded Z for zulu-time (UTC) at the end. Other timezones are
not supported.
:param str s: the ISO-formatted time
:rtype: datetime.datetime
:return: an timezone-naive datetime object
>>> parse_iso_utc('2016-04-27T00:28:04.000Z')
... | Parses an ISO time with a hard-coded Z for zulu-time (UTC) at the end. Other timezones are
not supported.
:param str s: the ISO-formatted time
:rtype: datetime.datetime
:return: an timezone-naive datetime object
>>> parse_iso_utc('2016-04-27T00:28:04.000Z')
datetime.datetime(2016, 4, 27, 0, ... |
def ensure_exists(self):
"""
Make sure the local repository exists.
:raises: :exc:`~exceptions.ValueError` when the
local repository doesn't exist yet.
"""
if not self.exists:
msg = "The local %s repository %s doesn't exist!"
raise ValueE... | Make sure the local repository exists.
:raises: :exc:`~exceptions.ValueError` when the
local repository doesn't exist yet. |
def get_file_relative_path_by_id(self, id):
"""
Given an id, get the corresponding file info relative path joined with file name.
Parameters:
#. id (string): The file unique id string.
:Returns:
#. relativePath (string): The file relative path joined with file n... | Given an id, get the corresponding file info relative path joined with file name.
Parameters:
#. id (string): The file unique id string.
:Returns:
#. relativePath (string): The file relative path joined with file name.
If None, it means file was not found. |
def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd):
"""
just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return:
"""
return gen_toy(f, nsample * ntoy, bo... | just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return: |
def sign_out(entry, time_out=None, forgot=False):
"""Sign out of an existing entry in the timesheet. If the user
forgot to sign out, flag the entry.
:param entry: `models.Entry` object. The entry to sign out.
:param time_out: (optional) `datetime.time` object. Specify the sign out time.
:param forg... | Sign out of an existing entry in the timesheet. If the user
forgot to sign out, flag the entry.
:param entry: `models.Entry` object. The entry to sign out.
:param time_out: (optional) `datetime.time` object. Specify the sign out time.
:param forgot: (optional) If true, user forgot to sign out. Entry wi... |
def get_rollup_caps(self, id=None, params=None):
"""
`<>`_
:arg id: The ID of the index to check rollup capabilities on, or left
blank for all jobs
"""
return self.transport.perform_request(
"GET", _make_path("_rollup", "data", id), params=params
... | `<>`_
:arg id: The ID of the index to check rollup capabilities on, or left
blank for all jobs |
def A_array(l1,l2,PA,PB,CP,g):
"""
THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0]
"""
Imax = l1+l2+1
A = [0]*Imax
for i in range(Imax):
for r in range(int(floor(i/2)+1)):
... | THO eq. 2.18 and 3.1
>>> A_array(0,0,0,0,0,1)
[1.0]
>>> A_array(0,1,1,1,1,1)
[1.0, -1.0]
>>> A_array(1,1,1,1,1,1)
[1.5, -2.5, 1.0] |
def get_file_url(self, fid, public=None):
"""
Get url for the file
:param string fid: File ID
:param boolean public: public or internal url
:rtype: string
"""
try:
volume_id, rest = fid.strip().split(",")
except ValueError:
raise B... | Get url for the file
:param string fid: File ID
:param boolean public: public or internal url
:rtype: string |
def _calibrate_vis(radiance, k):
"""Convert VIS radiance to reflectance
Note: Angle of incident radiation and annual variation of the
earth-sun distance is not taken into account. A value of 100%
corresponds to the radiance of a perfectly reflecting diffuse surface
illuminated a... | Convert VIS radiance to reflectance
Note: Angle of incident radiation and annual variation of the
earth-sun distance is not taken into account. A value of 100%
corresponds to the radiance of a perfectly reflecting diffuse surface
illuminated at normal incidence when the sun is at its an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.