code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def broadcast(*sinks_):
"""The |broadcast| decorator creates a |push| object that receives a
message by ``yield`` and then sends this message on to all the given sinks.
.. |broadcast| replace:: :py:func:`broadcast`
"""
@push
def bc():
sinks = [s() for s in sinks_]
while True:
... | The |broadcast| decorator creates a |push| object that receives a
message by ``yield`` and then sends this message on to all the given sinks.
.. |broadcast| replace:: :py:func:`broadcast` |
def _sb_decoder(self):
"""
Figures out what to do with a received sub-negotiation block.
"""
#print "at decoder"
bloc = self.telnet_sb_buffer
if len(bloc) > 2:
if bloc[0] == TTYPE and bloc[1] == IS:
self.terminal_type = bloc[2:]
... | Figures out what to do with a received sub-negotiation block. |
def set_calibrated_weights(self):
"""
Modify the weights to use the calibrated weights
"""
period = self.period
survey_scenario = self.survey_scenario
assert survey_scenario.simulation is not None
for simulation in [survey_scenario.simulation, survey_scenario.... | Modify the weights to use the calibrated weights |
async def states(self, country: str) -> list:
"""Return a list of supported states in a country."""
data = await self._request(
'get', 'states', params={'country': country})
return [d['state'] for d in data['data']] | Return a list of supported states in a country. |
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chu... | Find all of the listen routines and call the associated mod_watch runs |
def form_valid(self, post_form, attachment_formset, **kwargs):
""" Processes valid forms.
Called if all forms are valid. Creates a Post instance along with associated attachments if
required and then redirects to a success page.
"""
save_attachment_formset = attachment_formset ... | Processes valid forms.
Called if all forms are valid. Creates a Post instance along with associated attachments if
required and then redirects to a success page. |
def is_action_available(self, action):
"""Determines whether action is available.
That is, executing it would change the state.
"""
temp_state = np.rot90(self._state, action)
return self._is_action_available_left(temp_state) | Determines whether action is available.
That is, executing it would change the state. |
def _AddStopTimeObjectUnordered(self, stoptime, schedule):
"""Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later."""
stop_time_class = self.GetGtfsFactory().StopTime
cursor = schedule._connection.cursor()
insert_query = "INSERT ... | Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later. |
def ls(args):
"""
List sites
----------
Show list of installed sites.
::
usage: makesite ls [-h] [-v] [-p PATH]
Show list of installed sites.
optional arguments:
-p PATH, --path PATH path to makesite sites instalation dir. you can set it
... | List sites
----------
Show list of installed sites.
::
usage: makesite ls [-h] [-v] [-p PATH]
Show list of installed sites.
optional arguments:
-p PATH, --path PATH path to makesite sites instalation dir. you can set it
in $makesite_home ... |
def declare_queue(self, queue_name='', passive=False, durable=False,
exclusive=False, auto_delete=False, arguments=None):
"""
ε£°ζδΈδΈͺιε
:param queue_name: ιεε
:param passive:
:param durable:
:param exclusive:
:param auto_delete:
:param a... | ε£°ζδΈδΈͺιε
:param queue_name: ιεε
:param passive:
:param durable:
:param exclusive:
:param auto_delete:
:param arguments:
:return: pika ζ‘ζΆηζηιζΊεθ°ιεε |
def _expand_slice(self, indices):
"""
Expands slices containing steps into a list.
"""
keys = list(self.data.keys())
expanded = []
for idx, ind in enumerate(indices):
if isinstance(ind, slice) and ind.step is not None:
dim_ind = slice(ind.start... | Expands slices containing steps into a list. |
def get_grid_points_by_rotations(address_orig,
reciprocal_rotations,
mesh,
is_shift=None,
is_dense=False):
"""Returns grid points obtained after rotating input grid address
Parame... | Returns grid points obtained after rotating input grid address
Parameters
----------
address_orig : array_like
Grid point address to be rotated.
dtype='intc', shape=(3,)
reciprocal_rotations : array_like
Rotation matrices {R} with respect to reciprocal basis vectors.
Def... |
def add_task(self, task_id, backend, category, backend_args,
archive_args=None, sched_args=None):
"""Add and schedule a task.
:param task_id: id of the task
:param backend: name of the backend
:param category: category of the items to fecth
:param backend_args: ... | Add and schedule a task.
:param task_id: id of the task
:param backend: name of the backend
:param category: category of the items to fecth
:param backend_args: args needed to initialize the backend
:param archive_args: args needed to initialize the archive
:param sched_... |
def kmodels(wordlen: int, k: int, input=None, output=None):
"""Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Ch... | Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Chakraborty, Supratik, et al. "From Weighted to Unweighted Model
... |
def arguments_to_lists(function):
"""
Decorator for a function that converts all arguments to lists.
:param function: target function
:return: target function with only lists as parameters
"""
def l_function(*args, **kwargs):
l_args = [_to_list(arg) for arg in args]
l_kw... | Decorator for a function that converts all arguments to lists.
:param function: target function
:return: target function with only lists as parameters |
def find_by_id(self, story, params={}, **options):
"""Returns the full record for a single story.
Parameters
----------
story : {Id} Globally unique identifier for the story.
[params] : {Object} Parameters for the request
"""
path = "/stories/%s" % (story)
... | Returns the full record for a single story.
Parameters
----------
story : {Id} Globally unique identifier for the story.
[params] : {Object} Parameters for the request |
def delete_doc_by_id(self, collection, doc_id, **kwargs):
"""
:param str collection: The name of the collection for the request
:param str id: ID of the document to be deleted. Can specify '*' to delete everything.
Deletes items from Solr based on the ID. ::
>>> solr.delete... | :param str collection: The name of the collection for the request
:param str id: ID of the document to be deleted. Can specify '*' to delete everything.
Deletes items from Solr based on the ID. ::
>>> solr.delete_doc_by_id('SolrClient_unittest','changeme') |
def bel_process_belrdf():
"""Process BEL RDF and return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
belrdf = body.get('belrdf')
bp = bel.process_belrdf(belrdf)
return _stmts_from_proc(bp) | Process BEL RDF and return INDRA Statements. |
def version():
"""Display full version information."""
# Print out the current version of Tower CLI.
click.echo('Tower CLI %s' % __version__)
# Print out the current API version of the current code base.
click.echo('API %s' % CUR_API_VERSION)
# Attempt to connect to the Ansible Tower server.
... | Display full version information. |
def _set_link_local_route_oif_type(self, v, load=False):
"""
Setter method for link_local_route_oif_type, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/ipv6/route/link_local_static_route_nh/link_local_route_oif_type (enumeration)
If this variable is read-only (config: false) in the
... | Setter method for link_local_route_oif_type, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/ipv6/route/link_local_static_route_nh/link_local_route_oif_type (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_local_route_oif_type is considere... |
def number_to_dp(number: Optional[float],
dp: int,
default: Optional[str] = "",
en_dash_for_minus: bool = True) -> str:
"""
Format number to ``dp`` decimal places, optionally using a UTF-8 en dash
for minus signs.
"""
if number is None:
retu... | Format number to ``dp`` decimal places, optionally using a UTF-8 en dash
for minus signs. |
def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the properties of this API Root.
This invokes the ``Get API Root Information`` endpoint.
"""
response = self.__raw = self._conn.get(self.url,
headers={"Accept": accept})
... | Update the properties of this API Root.
This invokes the ``Get API Root Information`` endpoint. |
def _wr_ver_n_key(self, fout_txt, verbose):
"""Write GO DAG version and key indicating presence of GO ID in a list."""
with open(fout_txt, 'w') as prt:
self._prt_ver_n_key(prt, verbose)
print(' WROTE: {TXT}'.format(TXT=fout_txt)) | Write GO DAG version and key indicating presence of GO ID in a list. |
def pad_chunk_columns(chunk):
"""Given a set of items to be inserted, make sure they all have the
same columns by padding columns with None if they are missing."""
columns = set()
for record in chunk:
columns.update(record.keys())
for record in chunk:
for column in columns:
... | Given a set of items to be inserted, make sure they all have the
same columns by padding columns with None if they are missing. |
def inheritsFrom(self, target_name):
''' Return true if this target inherits from the named target (directly
or indirectly. Also returns true if this target is the named
target. Otherwise return false.
'''
for t in self.hierarchy:
if t and t.getName() == targe... | Return true if this target inherits from the named target (directly
or indirectly. Also returns true if this target is the named
target. Otherwise return false. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'results') and self.results is not None:
_dict['results'] = [x._to_dict() for x in self.results]
if hasattr(self, 'count') and self.count is not None:
_dict['co... | Return a json dictionary representing this model. |
def IsAllSpent(self):
"""
Flag indicating if all balance is spend.
Returns:
bool:
"""
for item in self.Items:
if item == CoinState.Confirmed:
return False
return True | Flag indicating if all balance is spend.
Returns:
bool: |
def _parse_kexgss_continue(self, m):
"""
Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message
"""
if not self.transport.server_mode:
srv_token = m.get_string()
m = Message()
... | Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message |
def db(self):
"""Return the correct KV store for this execution."""
if self._db is None:
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
from .tcex_redis import TcExRedis
self._db = TcExRedis(
self.tcex.default_args.tc_playbook_d... | Return the correct KV store for this execution. |
def group_membership_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership"
api_path = "/api/v2/group_memberships/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership |
def relabel(self, column_label, new_label):
"""Changes the label(s) of column(s) specified by ``column_label`` to
labels in ``new_label``.
Args:
``column_label`` -- (single str or array of str) The label(s) of
columns to be changed to ``new_label``.
``ne... | Changes the label(s) of column(s) specified by ``column_label`` to
labels in ``new_label``.
Args:
``column_label`` -- (single str or array of str) The label(s) of
columns to be changed to ``new_label``.
``new_label`` -- (single str or array of str): The label na... |
def get_events(self):
"""Return a set of events.
Which have been occured since the last call of this method.
This method should be called regulary to get all occuring
Events. There are three different Event types/classes
which can be returned:
- DeviceStateChangedEvent... | Return a set of events.
Which have been occured since the last call of this method.
This method should be called regulary to get all occuring
Events. There are three different Event types/classes
which can be returned:
- DeviceStateChangedEvent, if any device changed it's stat... |
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
... | Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`. |
def _dict_to_object(desired_type: Type[T], contents_dict: Dict[str, Any], logger: Logger,
options: Dict[str, Dict[str, Any]], conversion_finder: ConversionFinder = None,
is_dict_of_dicts: bool = False) -> T:
"""
Utility method to create an object from a dictionary of cons... | Utility method to create an object from a dictionary of constructor arguments. Constructor arguments that dont have
the correct type are intelligently converted if possible
:param desired_type:
:param contents_dict:
:param logger:
:param options:
:param conversion_finder:
:param is_dict_of_... |
def set_trace(context):
"""
Start a pdb set_trace inside of the template with the context available as
'context'. Uses ipdb if available.
"""
try:
import ipdb as pdb
except ImportError:
import pdb
print("For best results, pip install ipdb.")
print("Variables that are ... | Start a pdb set_trace inside of the template with the context available as
'context'. Uses ipdb if available. |
def fix_version(context):
"""Fix the version in metadata.txt
Relevant context dict item for both prerelease and postrelease:
``new_version``.
"""
if not prerequisites_ok():
return
lines = codecs.open('metadata.txt', 'rU', 'utf-8').readlines()
for index, line in enumerate(lines):
... | Fix the version in metadata.txt
Relevant context dict item for both prerelease and postrelease:
``new_version``. |
def _remove(self, obj):
"""Python 2.4 compatibility."""
for idx, item in enumerate(self._queue):
if item == obj:
del self._queue[idx]
break | Python 2.4 compatibility. |
def conditionally_create_profile(role_name, service_type):
"""
Check that there is a 1:1 correspondence with an InstanceProfile having the same name
as the role, and that the role is contained in it. Create InstanceProfile and attach to role if needed.
"""
# make instance profile if this service_type gets an ... | Check that there is a 1:1 correspondence with an InstanceProfile having the same name
as the role, and that the role is contained in it. Create InstanceProfile and attach to role if needed. |
def build_dated_queryset(self):
"""
Build pages for all years in the queryset.
"""
qs = self.get_dated_queryset()
years = self.get_date_list(qs)
[self.build_year(dt) for dt in years] | Build pages for all years in the queryset. |
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_p... | Create configuration for the root logger. |
def basicConfig(level=logging.WARNING, transient_level=logging.NOTSET):
"""Shortcut for setting up transient logging
I am a replica of ``logging.basicConfig`` which installs a
transient logging handler to stderr.
"""
fmt = "%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] %(message)s"
logging.... | Shortcut for setting up transient logging
I am a replica of ``logging.basicConfig`` which installs a
transient logging handler to stderr. |
def create(self, user_id, name, department=None, position=None,
mobile=None, gender=0, tel=None, email=None,
weixin_id=None, extattr=None):
"""
εε»Ίζε
https://work.weixin.qq.com/api/doc#90000/90135/90195
"""
user_data = optionaldict()
user_dat... | εε»Ίζε
https://work.weixin.qq.com/api/doc#90000/90135/90195 |
def get_api_versions(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Get a resource type api versions
'''
if kwargs is None:
kwargs = {}
if 'resource_provider' not in kwargs:
raise SaltCloudSystemExit(
'A resource_provider must be specified'
)
... | Get a resource type api versions |
def get_transfer_role(chain_state: ChainState, secrethash: SecretHash) -> Optional[str]:
"""
Returns 'initiator', 'mediator' or 'target' to signify the role the node has
in a transfer. If a transfer task is not found for the secrethash then the
function returns None
"""
task = chain_state.paymen... | Returns 'initiator', 'mediator' or 'target' to signify the role the node has
in a transfer. If a transfer task is not found for the secrethash then the
function returns None |
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
... | Return just the highstate or the errors |
def eeg_microstates_plot(method, path="", extension=".png", show_sensors_position=False, show_sensors_name=False, plot=True, save=True, dpi=150, contours=0, colorbar=False, separate=False):
"""
Plot the microstates.
"""
# Generate and store figures
figures = []
names = []
# Check if microst... | Plot the microstates. |
def analytic_file(self, new_status, old_status=None):
"""
Generate :code:`Analytic/*` files based on the given old and
new statuses.
:param new_status: The new status of the domain.
:type new_status: str
:param old_status: The old status of the domain.
:type old... | Generate :code:`Analytic/*` files based on the given old and
new statuses.
:param new_status: The new status of the domain.
:type new_status: str
:param old_status: The old status of the domain.
:type old_status: str |
def com_daltonmaag_check_ufolint(font):
"""Run ufolint on UFO source directory."""
import subprocess
ufolint_cmd = ["ufolint", font]
try:
subprocess.check_output(ufolint_cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
yield FAIL, ("ufolint failed the UFO source. Output follo... | Run ufolint on UFO source directory. |
def calculate_query_times(**kwargs):
"""
Calculates aggregate query times from all iteration times
Kwargs:
total_times(list): List of total time calculations
execution_times(list): List of execution_time calculations
results_iter_times(list): List of results_iter_time calculatio... | Calculates aggregate query times from all iteration times
Kwargs:
total_times(list): List of total time calculations
execution_times(list): List of execution_time calculations
results_iter_times(list): List of results_iter_time calculations
connect_times(list): List of connect_tim... |
def intersection_update(self, other):
"""Update the set, removing any elements from other which are not
in both sets.
@param other: the collection of items with which to update the set
@type other: Set object
"""
if not isinstance(other, Set):
raise ValueError... | Update the set, removing any elements from other which are not
in both sets.
@param other: the collection of items with which to update the set
@type other: Set object |
def parents( self, node ):
"""Retrieve/calculate the set of parents for the given node"""
if 'index' in node:
index = node['index']()
parents = list(meliaeloader.children( node, index, 'parents' ))
return parents
return [] | Retrieve/calculate the set of parents for the given node |
def init_db(drop_all=False, bind=engine):
"""Initialize the database, optionally dropping existing tables."""
try:
if drop_all:
Base.metadata.drop_all(bind=bind)
Base.metadata.create_all(bind=bind)
except OperationalError as err:
msg = 'password authentication failed for ... | Initialize the database, optionally dropping existing tables. |
def choose_database_name(metadata, config):
"""
Choose the database name to use.
As a default, databases should be named after the service that uses them. In addition,
database names should be different between unit testing and runtime so that there is
no chance of a unit test dropping a real datab... | Choose the database name to use.
As a default, databases should be named after the service that uses them. In addition,
database names should be different between unit testing and runtime so that there is
no chance of a unit test dropping a real database by accident. |
def hashable_to_uuid(hashable_):
"""
TODO: ensure that python2 and python3 agree on hashes of the same
information
Args:
hashable_ (hashable): hashables are bytes-like objects
An object that supports the Buffer Protocol, like bytes, bytearray
or memoryview. Bytes-like obje... | TODO: ensure that python2 and python3 agree on hashes of the same
information
Args:
hashable_ (hashable): hashables are bytes-like objects
An object that supports the Buffer Protocol, like bytes, bytearray
or memoryview. Bytes-like objects can be used for various operations
... |
def number_observer(t=None, targets=None):
"""
Return a number observer. If t is None, return NumberObserver. If t is a number,
return FixedIntervalNumberObserver. If t is an iterable (a list of numbers), return
TimingNumberObserver.
Parameters
----------
t : float, list or tuple, optional.... | Return a number observer. If t is None, return NumberObserver. If t is a number,
return FixedIntervalNumberObserver. If t is an iterable (a list of numbers), return
TimingNumberObserver.
Parameters
----------
t : float, list or tuple, optional. default None
A timing of the observation. See ... |
def save(self, *args, **kwargs):
"""
**uid**: :code:`electiontype:{name}`
"""
self.uid = 'electiontype:{}'.format(self.slug)
super(ElectionType, self).save(*args, **kwargs) | **uid**: :code:`electiontype:{name}` |
def gen_salt_and_hash(val=None):
""" Generate a salt & hash
If no string is provided then a random string will be
used to hash & referred to as `val`.
The salt will always be randomly generated & the hash
will be a sha256 hex value of the `val` & the salt as
a concatenated string. It follows t... | Generate a salt & hash
If no string is provided then a random string will be
used to hash & referred to as `val`.
The salt will always be randomly generated & the hash
will be a sha256 hex value of the `val` & the salt as
a concatenated string. It follows the guidance here:
crackstation.n... |
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0):
"""Compute longslit_model coefficients for RectWaveCoeff object.
Parameters
----------
rectwv_coeff : RectWaveCoeff instance
Rectification and wavelength calibration coefficients for a
particular CSU configuration... | Compute longslit_model coefficients for RectWaveCoeff object.
Parameters
----------
rectwv_coeff : RectWaveCoeff instance
Rectification and wavelength calibration coefficients for a
particular CSU configuration corresponding to a longslit
observation.
geometry : TBD
debugplo... |
def mark_quality(self, start_time, length, qual_name):
"""Mark signal quality, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
qual_name ... | Mark signal quality, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
qual_name : str
one of the stages defined in global stages. |
def to_representation(self, instance):
"""
Serialize the EnterpriseCustomerCatalog object.
Arguments:
instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.
Returns:
dict: The EnterpriseCustomerCatalog converted to a dict.
"""
... | Serialize the EnterpriseCustomerCatalog object.
Arguments:
instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.
Returns:
dict: The EnterpriseCustomerCatalog converted to a dict. |
def base_taskname(taskname, packagename=None):
"""
Extract the base name of the task.
Many tasks in the `drizzlepac` have "compound" names such as
'drizzlepac.sky'. This function will search for the presence of a dot
in the input `taskname` and if found, it will return the string
to the right o... | Extract the base name of the task.
Many tasks in the `drizzlepac` have "compound" names such as
'drizzlepac.sky'. This function will search for the presence of a dot
in the input `taskname` and if found, it will return the string
to the right of the right-most dot. If a dot is not found, it will return... |
def __get_query_filters(cls, filters={}, inverse=False):
"""
Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filte... | Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filters to be applied
:param inverse: if True include all the inverse filt... |
def blit(self, surface, pos=(0, 0)):
"""
Blits a surface on the screen at pos
:param surface: Surface to blit
:param pos: Top left corner to start blitting
:type surface: Surface
:type pos: tuple
"""
for x in range(surface.width):
for y in ran... | Blits a surface on the screen at pos
:param surface: Surface to blit
:param pos: Top left corner to start blitting
:type surface: Surface
:type pos: tuple |
def disable_metrics_collection(self, as_group, metrics=None):
"""
Disables monitoring of group metrics for the Auto Scaling group
specified in AutoScalingGroupName. You can specify the list of affected
metrics with the Metrics parameter.
"""
params = {'AutoScalingGroupNam... | Disables monitoring of group metrics for the Auto Scaling group
specified in AutoScalingGroupName. You can specify the list of affected
metrics with the Metrics parameter. |
def router_main(self):
'''
Main method for router; we stay in a loop in this method, receiving
packets until the end of time.
'''
while True:
gotpkt = True
try:
timestamp,dev,pkt = self.net.recv_packet(timeout=1.0)
except No... | Main method for router; we stay in a loop in this method, receiving
packets until the end of time. |
def _validate_pending_children(self):
"""
Validate the content of the pending_children set. Assert if an
internal error is found.
This function is used strictly for debugging the taskmaster by
checking that no invariants are violated. It is not used in
normal operation.
... | Validate the content of the pending_children set. Assert if an
internal error is found.
This function is used strictly for debugging the taskmaster by
checking that no invariants are violated. It is not used in
normal operation.
The pending_children set is used to detect cycles... |
def import_locations(self, cells_file):
"""Parse OpenCellID.org data files.
``import_locations()`` returns a dictionary with keys containing the
OpenCellID.org_ database identifier, and values consisting of
a ``Cell`` objects.
It expects cell files in the following format::
... | Parse OpenCellID.org data files.
``import_locations()`` returns a dictionary with keys containing the
OpenCellID.org_ database identifier, and values consisting of
a ``Cell`` objects.
It expects cell files in the following format::
22747,52.0438995361328,-0.2246370017529,2... |
def doesnt_have(self, relation, boolean='and', extra=None):
"""
Add a relationship count to the query.
:param relation: The relation to count
:type relation: str
:param boolean: The boolean value
:type boolean: str
:param extra: The extra query
:type ex... | Add a relationship count to the query.
:param relation: The relation to count
:type relation: str
:param boolean: The boolean value
:type boolean: str
:param extra: The extra query
:type extra: Builder or callable
:rtype: Builder |
def entity(self, entity_id, get_files=False, channel=None,
include_stats=True, includes=None):
'''Get the default data for any entity (e.g. bundle or charm).
@param entity_id The entity's id either as a reference or a string
@param get_files Whether to fetch the files for the cha... | Get the default data for any entity (e.g. bundle or charm).
@param entity_id The entity's id either as a reference or a string
@param get_files Whether to fetch the files for the charm or not.
@param channel Optional channel name.
@param include_stats Optionally disable stats collection... |
def to_even_columns(data, headers=None):
"""
Nicely format the 2-dimensional list into evenly spaced columns
"""
result = ''
col_width = max(len(word) for row in data for word in row) + 2 # padding
if headers:
header_width = max(len(word) for row in headers for word in row) + 2
... | Nicely format the 2-dimensional list into evenly spaced columns |
def _argument_adapter(callback):
"""Returns a function that when invoked runs ``callback`` with one arg.
If the function returned by this function is called with exactly
one argument, that argument is passed to ``callback``. Otherwise
the args tuple and kwargs dict are wrapped in an `Arguments` object... | Returns a function that when invoked runs ``callback`` with one arg.
If the function returned by this function is called with exactly
one argument, that argument is passed to ``callback``. Otherwise
the args tuple and kwargs dict are wrapped in an `Arguments` object. |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None
"""
if self.parent.step_kw_purpose.\
selected_purpose() == layer_purpose_hazard:
new_step = sel... | Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None |
def get_two_parameters(self, regex_exp, parameters):
"""
Get two parameters from a given regex expression
Raise an exception if more than two were found
:param regex_exp:
:param parameters:
:return:
"""
Rx, Ry, other = self.get_parameters(regex_exp, param... | Get two parameters from a given regex expression
Raise an exception if more than two were found
:param regex_exp:
:param parameters:
:return: |
def _unescape(self, msg):
"""
Removes double quotes that were used to escape double quotes. Expects
a string without its delimiting quotes, or a number. Returns a new
unescaped string.
"""
if isinstance(msg, (int, float, long)):
return msg
unescaped =... | Removes double quotes that were used to escape double quotes. Expects
a string without its delimiting quotes, or a number. Returns a new
unescaped string. |
def _ensure_unicode_string(string):
"""Returns a unicode string for string.
:param string:
The input string.
:type string:
`basestring`
:returns:
A unicode string.
:rtype:
`unicode`
"""
if not isinstance(string, si... | Returns a unicode string for string.
:param string:
The input string.
:type string:
`basestring`
:returns:
A unicode string.
:rtype:
`unicode` |
def from_secrets_file(client_secrets, storage=None, flags=None,
storage_path=None, api_version="v3", readonly=False,
http_client=None, ga_hook=None):
"""Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
... | Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
client_secrets: str, path to the client secrets file (downloadable from
Google API Console)
storage: oauth2client.client.Storage, a Storage implementation to store
... |
def shutdown(self):
"""
Send the shutdown message to the Connection.
:return: True if the shutdown completed successfully (i.e. both sides
have sent closure alerts), False otherwise (in which case you
call :meth:`recv` or :meth:`send` when the connection become... | Send the shutdown message to the Connection.
:return: True if the shutdown completed successfully (i.e. both sides
have sent closure alerts), False otherwise (in which case you
call :meth:`recv` or :meth:`send` when the connection becomes
readable/writeable). |
def _evalTimeStr(self, datetimeString, sourceTime):
"""
Evaluate text passed by L{_partialParseTimeStr()}
"""
s = datetimeString.strip()
sourceTime = self._evalDT(datetimeString, sourceTime)
if s in self.ptc.re_values['now']:
self.currentContext.updateAccurac... | Evaluate text passed by L{_partialParseTimeStr()} |
def diffusionAddCountsFromSource(grph, source, target, nodeType = 'citations', extraType = None, diffusionLabel = 'DiffusionCount', extraKeys = None, countsDict = None, extraMapping = None):
"""Does a diffusion using [diffusionCount()](#metaknowledge.diffusion.diffusionCount) and updates _grph_ with it, using the n... | Does a diffusion using [diffusionCount()](#metaknowledge.diffusion.diffusionCount) and updates _grph_ with it, using the nodes in the graph as keys in the diffusion, i.e. the source. The name of the attribute the counts are added to is given by _diffusionLabel_. If the graph is not composed of citations from the source... |
def get_library(self, username, status=None):
"""Fetches a users library.
:param str username: The user to get the library from.
:param str status: only return the items with the supplied status.
Can be one of `currently-watching`, `plan-to-watch`, `completed`,
`on-hold`... | Fetches a users library.
:param str username: The user to get the library from.
:param str status: only return the items with the supplied status.
Can be one of `currently-watching`, `plan-to-watch`, `completed`,
`on-hold` or `dropped`.
:returns: List of Library objects... |
def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST:
"""Return a Python AST Node for a `let*` expression."""
assert node.op == NodeOp.LET
with ctx.new_symbol_table("let"):
let_body_ast: List[ast.AST] = []
for binding in node.bindings:
init_node = binding.init
... | Return a Python AST Node for a `let*` expression. |
def show(self, index):
"""
This class overrides this method
"""
if self.menu and self.menu.parent:
self.text = "Return to %s menu" % self.menu.parent.title
else:
self.text = "Exit"
return super(ExitItem, self).show(index) | This class overrides this method |
def get_meta(self, key=None):
"""Get metadata value for collection."""
if self.is_fake:
return {}
if key == "tag":
return self.tag
elif key is None:
ret = {}
for key in self.journal.info.keys():
ret[key] = self.meta_mapping... | Get metadata value for collection. |
def parse_template(input_filename, output_filename=''):
""" Parses a template file
Replaces all occurences of @@problem_id@@ by the value
of the 'problem_id' key in data dictionary
input_filename: file to parse
output_filename: if not specified, overwrite input file
"""
... | Parses a template file
Replaces all occurences of @@problem_id@@ by the value
of the 'problem_id' key in data dictionary
input_filename: file to parse
output_filename: if not specified, overwrite input file |
def _validate_arguments(self):
"""method to sanitize model parameters
Parameters
---------
None
Returns
-------
None
"""
super(SplineTerm, self)._validate_arguments()
if self.basis not in self._bases:
raise ValueError("basis ... | method to sanitize model parameters
Parameters
---------
None
Returns
-------
None |
def _getScalesRand(self):
"""
Internal function for parameter initialization
Return a vector of random scales
"""
if self.P>1:
scales = []
for term_i in range(self.n_randEffs):
_scales = sp.randn(self.diag[term_i].shape[0])
... | Internal function for parameter initialization
Return a vector of random scales |
def get_process_by_id(self, process_id):
"""GetProcessById.
[Preview API] Get a process by ID.
:param str process_id: ID for a process.
:rtype: :class:`<Process> <azure.devops.v5_1.core.models.Process>`
"""
route_values = {}
if process_id is not None:
... | GetProcessById.
[Preview API] Get a process by ID.
:param str process_id: ID for a process.
:rtype: :class:`<Process> <azure.devops.v5_1.core.models.Process>` |
def get_hashhash(self, username):
"""
Generate a digest of the htpasswd hash
"""
return hashlib.sha256(
self.users.get_hash(username)
).hexdigest() | Generate a digest of the htpasswd hash |
def do_stack(self, arg):
"""
[~thread] k - show the stack trace
[~thread] stack - show the stack trace
"""
if arg: # XXX TODO add depth parameter
raise CmdError("too many arguments")
pid, tid = self.get_process_and_thread_ids_from_prefix()
p... | [~thread] k - show the stack trace
[~thread] stack - show the stack trace |
def _get_healthmgr_cmd(self):
''' get the command to start the topology health manager processes '''
healthmgr_main_class = 'org.apache.heron.healthmgr.HealthManager'
healthmgr_cmd = [os.path.join(self.heron_java_home, 'bin/java'),
# We could not rely on the default -Xmx setting, which... | get the command to start the topology health manager processes |
def to_eaf(self, skipempty=True, pointlength=0.1):
"""Convert the object to an pympi.Elan.Eaf object
:param int pointlength: Length of respective interval from points in
seconds
:param bool skipempty: Skip the empty annotations
:returns: :class:`pympi.Ela... | Convert the object to an pympi.Elan.Eaf object
:param int pointlength: Length of respective interval from points in
seconds
:param bool skipempty: Skip the empty annotations
:returns: :class:`pympi.Elan.Eaf` object
:raises ImportError: If the Eaf module c... |
def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] | Get the hostname that this connection is associated with |
def _expand_formula_(formula_string):
"""
Accounts for the many ways a user may write a formula string, and returns an expanded chemical formula string.
Assumptions:
-The Chemical Formula string it is supplied is well-written, and has no hanging parethneses
-The number of repeats occurs after the el... | Accounts for the many ways a user may write a formula string, and returns an expanded chemical formula string.
Assumptions:
-The Chemical Formula string it is supplied is well-written, and has no hanging parethneses
-The number of repeats occurs after the elemental symbol or ) ] character EXCEPT in the case... |
def _ffn_layer_multi_inputs(inputs_list,
hparams,
ffn_layer_type="dense",
name="ffn",
kernel_initializer=None,
bias_initializer=None,
activation=None,
... | Implements a Feed-forward layer with multiple inputs, pad-removing, etc.
Args:
inputs_list: list of input tensors
hparams: hyper-parameters
ffn_layer_type: dense / dense_dropconnect/ dense_relu_dense
name: name
kernel_initializer: kernel initializer
bias_initializer: bias initializer
acti... |
def remove_exit(self):
"""
Remove the exit item if necessary. Used to make sure we only remove the exit item, not something else.
Returns:
bool: True if item needed to be removed, False otherwise.
"""
if self.items:
if self.items[-1] is self.exit_item:
... | Remove the exit item if necessary. Used to make sure we only remove the exit item, not something else.
Returns:
bool: True if item needed to be removed, False otherwise. |
def to_yaml(template, clean_up=False, long_form=False):
"""
Assume the input is JSON and convert to YAML
"""
data = load_json(template)
if clean_up:
data = clean(data)
return dump_yaml(data, clean_up, long_form) | Assume the input is JSON and convert to YAML |
def recent_comments(context):
"""
Dashboard widget for displaying recent comments.
"""
latest = context["settings"].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related("user")
context["comments"] = comments.order_by("-id")[:latest]
return context | Dashboard widget for displaying recent comments. |
def write(self, frames):
"""
Write the frames to the target HDF5 file, using the format used by
``pd.Panel.to_hdf``
Parameters
----------
frames : iter[(int, DataFrame)] or dict[int -> DataFrame]
An iterable or other mapping of sid to the corresponding OHLCV
... | Write the frames to the target HDF5 file, using the format used by
``pd.Panel.to_hdf``
Parameters
----------
frames : iter[(int, DataFrame)] or dict[int -> DataFrame]
An iterable or other mapping of sid to the corresponding OHLCV
pricing data. |
def _refresh_html_home(self):
"""
Function to refresh the self._parent.html['home'] object
which provides the status if zones are scheduled to
start automatically (program_toggle).
"""
req = self._parent.client.get(HOME_ENDPOINT)
if req.status_code == 403:
... | Function to refresh the self._parent.html['home'] object
which provides the status if zones are scheduled to
start automatically (program_toggle). |
def handle_message_registered(self, msg_data, host):
"""Processes messages that have been delivered by a registered client.
Args:
msg (string): The raw packet data delivered from the listener. This
data will be unserialized and then processed based on the packet's
meth... | Processes messages that have been delivered by a registered client.
Args:
msg (string): The raw packet data delivered from the listener. This
data will be unserialized and then processed based on the packet's
method.
host (tuple): The (address, host) tuple of the sou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.