code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def getitem(self, index, context=None):
"""Get an item from this node.
:param index: The node to use as a subscript index.
:type index: Const or Slice
"""
return _container_getitem(self, self.elts, index, context=context) | Get an item from this node.
:param index: The node to use as a subscript index.
:type index: Const or Slice |
def mlp(feature, hparams, name="mlp"):
"""Multi layer perceptron with dropout and relu activation."""
with tf.variable_scope(name, "mlp", values=[feature]):
num_mlp_layers = hparams.num_mlp_layers
mlp_size = hparams.mlp_size
for _ in range(num_mlp_layers):
feature = common_layers.dense(feature, ml... | Multi layer perceptron with dropout and relu activation. |
def colorize(occurence,maxoccurence,minoccurence):
'''A formula for determining colors.'''
if occurence == maxoccurence:
color = (255,0,0)
elif occurence == minoccurence:
color = (0,0,255)
else:
color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence... | A formula for determining colors. |
def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. |
def to_table(self, sort_key="wall_time", stop=None):
"""Return a table (list of lists) with timer data"""
table = [list(AbinitTimerSection.FIELDS), ]
ord_sections = self.order_sections(sort_key)
if stop is not None:
ord_sections = ord_sections[:stop]
for osect in or... | Return a table (list of lists) with timer data |
def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket"""
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) | Set Auth request received from websocket |
def scale(self, new_max_value=1):
"""
Scale R, G and B parameters
:param new_max_value: how much to scale
:return: a new ColorRGB instance
"""
f = new_max_value / self.max
return ColorRGB(self.r * f,
self.g * f,
self... | Scale R, G and B parameters
:param new_max_value: how much to scale
:return: a new ColorRGB instance |
def _front_delta(self):
"""Return the offset of the colored part."""
if self.flags & self.NO_MOVE:
return Separator(0, 0)
if self.clicked and self.hovered: # the mouse is over the button
delta = 2
elif self.hovered and not self.flags & self.NO_HOVER:
... | Return the offset of the colored part. |
def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a ... | Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher... |
def append(self, symbol, metadata, start_time=None):
"""
Update metadata entry for `symbol`
Parameters
----------
symbol : `str`
symbol name for the item
metadata : `dict`
to be persisted
start_time : `datetime.datetime`
when m... | Update metadata entry for `symbol`
Parameters
----------
symbol : `str`
symbol name for the item
metadata : `dict`
to be persisted
start_time : `datetime.datetime`
when metadata becomes effective
Default: datetime.datetime.utcnow() |
def loop_position(self):
"""Return the current sort in the loop"""
for i, v in enumerate(self._sort_loop):
if v == glances_processes.sort_key:
return i
return 0 | Return the current sort in the loop |
def adj_nodes_gcp(gcp_nodes):
"""Adjust details specific to GCP."""
for node in gcp_nodes:
node.cloud = "gcp"
node.cloud_disp = "GCP"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['zone'].name
return... | Adjust details specific to GCP. |
def add_job(self, task, inputdata, debug=False):
"""
Add a job in the queue and returns a submission id.
:param task: Task instance
:type task: inginious.frontend.tasks.WebAppTask
:param inputdata: the input as a dictionary
:type inputdata: dict
:param debug: If ... | Add a job in the queue and returns a submission id.
:param task: Task instance
:type task: inginious.frontend.tasks.WebAppTask
:param inputdata: the input as a dictionary
:type inputdata: dict
:param debug: If debug is true, more debug data will be saved
:type debug: boo... |
def switch_off(self):
"""Turn the switch off."""
success = self.set_status(CONST.STATUS_OFF_INT)
if success:
self._json_state['status'] = CONST.STATUS_OFF
return success | Turn the switch off. |
def alter_old_distutils_request(request: WSGIRequest):
"""Alter the request body for compatibility with older distutils clients
Due to a bug in the Python distutils library, the request post is sent
using \n as a separator instead of the \r\n that the HTTP spec demands.
This breaks the Django form pars... | Alter the request body for compatibility with older distutils clients
Due to a bug in the Python distutils library, the request post is sent
using \n as a separator instead of the \r\n that the HTTP spec demands.
This breaks the Django form parser and therefore we have to write a
custom parser.
Th... |
def get_collection(self, collection, database_name=None, username=None, password=None):
"""
Get a pymongo collection handle.
:param collection: Name of collection
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param ... | Get a pymongo collection handle.
:param collection: Name of collection
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo collection object |
def add(self, *args):
"""Add a path template and handler.
:param name: Optional. If specified, allows reverse path lookup with
:meth:`reverse`.
:param template: A string or :class:`~potpy.template.Template`
instance used to match paths against. Strings will be wrapped in... | Add a path template and handler.
:param name: Optional. If specified, allows reverse path lookup with
:meth:`reverse`.
:param template: A string or :class:`~potpy.template.Template`
instance used to match paths against. Strings will be wrapped in a
Template instance.... |
def rewrap_bytes(data):
'''Rewrap characters to 70 character width.
Intended to rewrap base64 content.
'''
return b'\n'.join(
data[index:index+70] for index in range(0, len(data), 70)
) | Rewrap characters to 70 character width.
Intended to rewrap base64 content. |
def default_is_local(hadoop_conf=None, hadoop_home=None):
"""\
Is Hadoop configured to use the local file system?
By default, it is. A DFS must be explicitly configured.
"""
params = pydoop.hadoop_params(hadoop_conf, hadoop_home)
for k in 'fs.defaultFS', 'fs.default.name':
if not params... | \
Is Hadoop configured to use the local file system?
By default, it is. A DFS must be explicitly configured. |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
try:
return {
'authority': 'birdland.mit.edu',
'namespace': 'coordinate format',
'identifier': name,
... | Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type |
def sync_scheduler(self):
"""Download the scheduler.info file and perform a smart comparison
with what we currently have so that we don't overwrite the
last_run timestamp
To do a smart comparison, we go over each entry in the
server's scheduler file. If a scheduler entry is not ... | Download the scheduler.info file and perform a smart comparison
with what we currently have so that we don't overwrite the
last_run timestamp
To do a smart comparison, we go over each entry in the
server's scheduler file. If a scheduler entry is not present
in the server copy, w... |
def append(self, event):
"""Add an event to the list."""
self._events.append(event)
self._events_by_baseclass[event.baseclass].append(event) | Add an event to the list. |
def _purge(self):
"""
Trim the cache down to max_size by evicting the
least-recently-used entries.
"""
if len(self.cache) <= self.max_size:
return
cache = self.cache
refcount = self.refcount
queue = self.queue
max_size = self.max_size
... | Trim the cache down to max_size by evicting the
least-recently-used entries. |
def eye_plot(x,L,S=0):
"""
Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input da... | Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input data vector/array
L : display len... |
def remove_edge_fun(graph):
"""
Returns a function that removes an edge from the `graph`.
..note:: The out node is removed if this is isolate.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:return:
A function that remove an edge from the `graph`... | Returns a function that removes an edge from the `graph`.
..note:: The out node is removed if this is isolate.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:return:
A function that remove an edge from the `graph`.
:rtype: callable |
def get_branches(aliases):
"""Get unique branch names from an alias dictionary."""
ignore = ['pow', 'log10', 'sqrt', 'max']
branches = []
for k, v in aliases.items():
tokens = re.sub('[\(\)\+\*\/\,\=\<\>\&\!\-\|]', ' ', v).split()
for t in tokens:
if bool(re.search(r'^\d'... | Get unique branch names from an alias dictionary. |
def read_index(self, fh, indexed_fh, rec_iterator=None,
rec_hash_func=None, parse_hash=str, flush=True,
no_reindex=True, verbose=False):
"""
Populate this index from a file. Input format is just a tab-separated file,
one record per line. The last column is the file location... | Populate this index from a file. Input format is just a tab-separated file,
one record per line. The last column is the file location for the record
and all columns before that are collectively considered to be the hash key
for that record (which is probably only 1 column, but this allows us to
permit t... |
def filter_search(self, code=None, name=None, abilities=None,
attributes=None, info=None):
"""
Return a list of codes and names pertaining to cards that have the
given information values stored.
Can take a code integer, name string, abilities dict {phase: ability
... | Return a list of codes and names pertaining to cards that have the
given information values stored.
Can take a code integer, name string, abilities dict {phase: ability
list/"*"}, attributes list, info dict {key, value list/"*"}.
In the above argument examples "*" is a string that may ... |
def perform_oauth(email, master_token, android_id, service, app, client_sig,
device_country='us', operatorCountry='us', lang='en',
sdk_version=17):
"""
Use a master token from master_login to perform OAuth to a specific Google
service.
Return a dict, eg::
{
... | Use a master token from master_login to perform OAuth to a specific Google
service.
Return a dict, eg::
{
'Auth': '...',
'LSID': '...',
'SID': '..',
'issueAdvice': 'auto',
'services': 'hist,mail,googleme,...'
}
To authenticate re... |
def MGMT_ACTIVE_SET(self, sAddr='', xCommissioningSessionId=None, listActiveTimestamp=None, listChannelMask=None, xExtendedPanId=None,
sNetworkName=None, sPSKc=None, listSecurityPolicy=None, xChannel=None, sMeshLocalPrefix=None, xMasterKey=None,
xPanId=None, xTmfPort=None... | send MGMT_ACTIVE_SET command
Returns:
True: successful to send MGMT_ACTIVE_SET
False: fail to send MGMT_ACTIVE_SET |
def daemon_start(self):
"""Start daemon when gtk loaded
"""
if daemon_status() == "SUN not running":
subprocess.call("{0} &".format(self.cmd), shell=True) | Start daemon when gtk loaded |
def geturl(urllib2_resp):
"""
Use instead of urllib.addinfourl.geturl(), which appears to have
some issues with dropping the double slash for certain schemes
(e.g. file://). This implementation is probably over-eager, as it
always restores '://' if it is missing, and it appears some url
schemat... | Use instead of urllib.addinfourl.geturl(), which appears to have
some issues with dropping the double slash for certain schemes
(e.g. file://). This implementation is probably over-eager, as it
always restores '://' if it is missing, and it appears some url
schemata aren't always followed by '//' after... |
def _parse_attribute(
self,
element, # type: ET.Element
attribute, # type: Text
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the primitive value within the XML element's attribute."""
parsed_value = self._default
at... | Parse the primitive value within the XML element's attribute. |
def encode_sid(cls, secret, sid):
"""Computes the HMAC for the given session id."""
secret_bytes = secret.encode("utf-8")
sid_bytes = sid.encode("utf-8")
sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest()
return "%s%s" % (sig, sid) | Computes the HMAC for the given session id. |
def unbind(self, callback):
"""Remove a callback from the list
"""
handlers = self._handlers
if handlers:
filtered_callbacks = [f for f in handlers if f != callback]
removed_count = len(handlers) - len(filtered_callbacks)
if removed_count:
... | Remove a callback from the list |
def keep(self, diff):
""" Mark this diff (or volume) to be kept in path. """
(toUUID, fromUUID) = self.toArg.diff(diff)
self._client.keep(toUUID, fromUUID)
logger.debug("Kept %s", diff) | Mark this diff (or volume) to be kept in path. |
def _split_refextract_authors_str(authors_str):
"""Extract author names out of refextract authors output."""
author_seq = (x.strip() for x in RE_SPLIT_AUTH.split(authors_str) if x)
res = []
current = ''
for author in author_seq:
if not isinstance(author, six.text_type):
author =... | Extract author names out of refextract authors output. |
def get_create_security_group_commands(self, sg_id, sg_rules):
"""Commands for creating ACL"""
cmds = []
in_rules, eg_rules = self._format_rules_for_eos(sg_rules)
cmds.append("ip access-list %s dynamic" %
self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
for i... | Commands for creating ACL |
async def update_server_data(server):
"""
Updates the server info for the given server
Args:
server: The Discord server to update info for
"""
data = datatools.get_data()
# Add the server to server data if it doesn't yet exist
send_welcome_message = False
if server.id not in da... | Updates the server info for the given server
Args:
server: The Discord server to update info for |
def ParseCall(self, parser_mediator, query, row, **unused_kwargs):
"""Parses a call.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row resulti... | Parses a call.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row resulting from query.
query (Optional[str]): query. |
def multigrid(bounds, points_count):
"""
Generates a multidimensional lattice
:param bounds: box constraints
:param points_count: number of points per dimension.
"""
if len(bounds)==1:
return np.linspace(bounds[0][0], bounds[0][1], points_count).reshape(points_count, 1)
x_grid_rows =... | Generates a multidimensional lattice
:param bounds: box constraints
:param points_count: number of points per dimension. |
def _get_ukko_report():
'''Get Ukko's report from the fixed URL.
'''
with urllib.request.urlopen(URL_UKKO_REPORT) as response:
ret = str(response.read())
return ret | Get Ukko's report from the fixed URL. |
def optimal_partitions(sizes, counts, num_part):
"""Compute the optimal partitions given a distribution of set sizes.
Args:
sizes (numpy.array): The complete domain of set sizes in ascending
order.
counts (numpy.array): The frequencies of all set sizes in the same
order ... | Compute the optimal partitions given a distribution of set sizes.
Args:
sizes (numpy.array): The complete domain of set sizes in ascending
order.
counts (numpy.array): The frequencies of all set sizes in the same
order as `sizes`.
num_part (int): The number of partit... |
def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name
"""Helper to determine the shape of Concatenate output."""
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_sha... | Helper to determine the shape of Concatenate output. |
def check_num_slices(num_slices, img_shape=None, num_dims=3):
"""Ensures requested number of slices is valid.
Atleast 1 and atmost the image size, if available
"""
if not isinstance(num_slices, Iterable) or len(num_slices) == 1:
num_slices = np.repeat(num_slices, num_dims)
if img_shape is... | Ensures requested number of slices is valid.
Atleast 1 and atmost the image size, if available |
def loads(cls, s):
"""
Load an instance of this class from YAML.
"""
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | Load an instance of this class from YAML. |
def show_exception_only(self, etype, evalue):
"""Only print the exception type and message, without a traceback.
Parameters
----------
etype : exception type
value : exception value
"""
# This method needs to use __call__ from *this* class, not the one from
... | Only print the exception type and message, without a traceback.
Parameters
----------
etype : exception type
value : exception value |
def sparse_or_dense_matvecmul(sparse_or_dense_matrix,
dense_vector,
validate_args=False,
name=None,
**kwargs):
"""Returns (batched) matmul of a (sparse) matrix with a column vector.
Args:
spa... | Returns (batched) matmul of a (sparse) matrix with a column vector.
Args:
sparse_or_dense_matrix: `SparseTensor` or `Tensor` representing a (batch of)
matrices.
dense_vector: `Tensor` representing a (batch of) vectors, with the same
batch shape as `sparse_or_dense_matrix`. The shape must be compa... |
def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = self._container[key.lower()]
for val in vals[1:]:
yield vals[0], val | Iterate over all header lines, including duplicate ones. |
def static_get_pdb_object(pdb_id, bio_cache = None, cache_dir = None):
'''This method does not necessarily use a BioCache but it seems to fit here.'''
pdb_id = pdb_id.upper()
if bio_cache:
return bio_cache.get_pdb_object(pdb_id)
if cache_dir:
# Check to see whet... | This method does not necessarily use a BioCache but it seems to fit here. |
def call_api(self,
action,
params=None,
method=('API', 'POST', 'application/x-www-form-urlencoded'),
**kwargs):
"""
:param method: methodName
:param action: MethodUrl,
:param params: Dictionary,form params for api.
... | :param method: methodName
:param action: MethodUrl,
:param params: Dictionary,form params for api.
:param timeout: (optional) Float describing the timeout of the request.
:return: |
def scrape_metrics(self, scraper_config):
"""
Poll the data from prometheus and return the metrics as a generator.
"""
response = self.poll(scraper_config)
try:
# no dry run if no label joins
if not scraper_config['label_joins']:
scraper_co... | Poll the data from prometheus and return the metrics as a generator. |
def extract_public_key(args):
""" Load an ECDSA private key and extract the embedded public key as raw binary data. """
sk = _load_ecdsa_signing_key(args)
vk = sk.get_verifying_key()
args.public_keyfile.write(vk.to_string())
print("%s public key extracted to %s" % (args.keyfile.name, args.public_key... | Load an ECDSA private key and extract the embedded public key as raw binary data. |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Do not read certain fields.
Do not expect the server to return the ``content_view_filter``
attribute. This has no practical impact, as the attribute must be
provided when a :class:`nailgun.entities.ContentViewFilterRu... | Do not read certain fields.
Do not expect the server to return the ``content_view_filter``
attribute. This has no practical impact, as the attribute must be
provided when a :class:`nailgun.entities.ContentViewFilterRule` is
instantiated.
Also, ignore any field that is not retur... |
def run(self):
"Get jobs from the queue and perform them as they arrive."
while 1:
# Sleep until there is a job to perform.
job = self.jobs.get()
# Yawn. Time to get some work done.
try:
job.run()
self.jobs.task_done()
... | Get jobs from the queue and perform them as they arrive. |
def register_token(platform, user_id, token, on_error=None, on_success=None):
""" Register a device token for a user.
:param str platform The platform which to register token on. One of either
Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service
(outbound.APNS).
:param str | nu... | Register a device token for a user.
:param str platform The platform which to register token on. One of either
Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service
(outbound.APNS).
:param str | number user_id: the id you use to identify a user. this should
be static for the lif... |
def _scrape_song_lyrics_from_url(self, url):
""" Use BeautifulSoup to scrape song info off of a Genius song URL
:param url: URL for the web page to scrape lyrics from
"""
page = requests.get(url)
if page.status_code == 404:
return None
# Scrape the song lyric... | Use BeautifulSoup to scrape song info off of a Genius song URL
:param url: URL for the web page to scrape lyrics from |
def _send_unsigned_long(self,value):
"""
Convert a numerical value into an integer, then to a bytes object.
Check bounds for unsigned long.
"""
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
... | Convert a numerical value into an integer, then to a bytes object.
Check bounds for unsigned long. |
def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None,
**kwargs):
"""Create a new bot in a particular group.
:param str name: bot name
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL... | Create a new bot in a particular group.
:param str name: bot name
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL for each new message
:param bool dm_notification: whether to POST-back for direct messages?
:return: the new ... |
def dumps_tabledata(value, format_name="rst_grid_table", **kwargs):
"""
:param tabledata.TableData value: Tabular data to dump.
:param str format_name:
Dumped format name of tabular data.
Available formats are described in
:py:meth:`~pytablewriter.TableWriterFactory.create_from_forma... | :param tabledata.TableData value: Tabular data to dump.
:param str format_name:
Dumped format name of tabular data.
Available formats are described in
:py:meth:`~pytablewriter.TableWriterFactory.create_from_format_name`
:Example:
.. code:: python
>>> dumps_tabledata... |
def radius(self):
'''
Radius of the ellipse, Point class.
'''
try:
return self._radius
except AttributeError:
pass
self._radius = Point(1, 1, 0)
return self._radius | Radius of the ellipse, Point class. |
def location_based_search(self, lng, lat, distance, unit="miles", attribute_map=None, page=0, limit=50):
"""Search based on location and other attribute filters
:param long lng: Longitude parameter
:param long lat: Latitude parameter
:param int distance: The radius of the query
... | Search based on location and other attribute filters
:param long lng: Longitude parameter
:param long lat: Latitude parameter
:param int distance: The radius of the query
:param str unit: The unit of measure for the query, defaults to miles
:param dict attribute_map: Additional ... |
def _add_helpingmaterials(config, helping_file, helping_type):
"""Add helping materials to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
... | Add helping materials to a project. |
def ending_long_process(self, message=""):
"""
Clear main window's status bar and restore mouse cursor.
"""
QApplication.restoreOverrideCursor()
self.show_message(message, timeout=2000)
QApplication.processEvents() | Clear main window's status bar and restore mouse cursor. |
def clone(name_a, name_b, **kwargs):
'''
Creates a clone of the given snapshot.
name_a : string
name of snapshot
name_b : string
name of filesystem or volume
create_parent : boolean
creates all the non-existing parent datasets. any property specified on the
command l... | Creates a clone of the given snapshot.
name_a : string
name of snapshot
name_b : string
name of filesystem or volume
create_parent : boolean
creates all the non-existing parent datasets. any property specified on the
command line using the -o option is ignored.
propertie... |
async def keep_alive(self, period=1, margin=.3):
"""
Periodically send a keep alive message to the Arduino.
Frequency of keep alive transmission is calculated as follows:
keep_alive_sent = period - (period * margin)
:param period: Time period between keepalives. Range is 0-10 s... | Periodically send a keep alive message to the Arduino.
Frequency of keep alive transmission is calculated as follows:
keep_alive_sent = period - (period * margin)
:param period: Time period between keepalives. Range is 0-10 seconds.
0 disables the keepalive mechanism.
... |
def run(self, debug=False, reload=None):
"""
Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
... | Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
>>> bot.run() |
def update(self, friendly_name=None, description=None, expiry=None, schema=None):
""" Selectively updates Table information.
Any parameters that are omitted or None are not updated.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
ex... | Selectively updates Table information.
Any parameters that are omitted or None are not updated.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
expiry: if not None, the new expiry time, either as a DateTime or milliseconds since epoch.
... |
def _do_functions(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
"""
Implements @mixin and @function
"""
if name:
funct, params, _ = name.partition('(')
funct = funct.strip()
params = split_p... | Implements @mixin and @function |
def check_work_done(self, grp):
"""
Check for the existence of alignment and result files.
"""
id_ = self.get_id(grp)
concat_file = os.path.join(self.cache_dir, '{}.phy'.format(id_))
result_file = os.path.join(self.cache_dir, '{}.{}.json'.format(id_, self.task_interface.n... | Check for the existence of alignment and result files. |
def detect_encoding(readline):
"""
The detect_encoding() function is used to detect the encoding that should
be used to decode a Python source file. It requires one argment, readline,
in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used... | The detect_encoding() function is used to detect the encoding that should
be used to decode a Python source file. It requires one argment, readline,
in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used
(as a string) and a list of any lines ... |
def write_stilde(self, stilde_dict, group=None):
"""Writes stilde for each IFO to file.
Parameters
-----------
stilde : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to write the strain to. If No... | Writes stilde for each IFO to file.
Parameters
-----------
stilde : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to write the strain to. If None, will write to the top
level. |
def update(self, feedforwardInputI, feedforwardInputE, v, recurrent=True,
envelope=False, iSpeedTuning=False, enforceDale=True):
"""
Do one update of the CAN network, of length self.dt.
:param feedforwardInputI: The feedforward input to inhibitory cells.
:param feedforwardInputR: The feedfo... | Do one update of the CAN network, of length self.dt.
:param feedforwardInputI: The feedforward input to inhibitory cells.
:param feedforwardInputR: The feedforward input to excitatory cells.
:param placeActivity: Activity of the place code.
:param v: The current velocity.
:param recurrent: Whether o... |
def run_script(self,
script,
shutit_pexpect_child=None,
in_shell=True,
echo=None,
note=None,
loglevel=logging.DEBUG):
"""Run the passed-in string as a script on the target's command line.
@param script: String represe... | Run the passed-in string as a script on the target's command line.
@param script: String representing the script. It will be de-indented
and stripped before being run.
@param shutit_pexpect_child: See send()
@param in_shell: Indicate whether we are in a shell or not. (Default: True)
@param note: ... |
def parse(self, data, path=None):
"""
Args:
data (str): Raw specification text.
path (Optional[str]): Path to specification on filesystem. Only
used to tag tokens with the file they originated from.
"""
assert not self.exhausted, 'Must call get_par... | Args:
data (str): Raw specification text.
path (Optional[str]): Path to specification on filesystem. Only
used to tag tokens with the file they originated from. |
def swap_dims(self, dims_dict, inplace=None):
"""Returns a new object with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names. Each value must already be a variable in t... | Returns a new object with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names. Each value must already be a variable in the
dataset.
inplace : bool, optional
... |
def get_record_params(args):
"""Get record parameters from command options.
Argument:
args: arguments object
"""
name, rtype, content, ttl, priority = (
args.name, args.rtype, args.content, args.ttl, args.priority)
return name, rtype, content, ttl, priority | Get record parameters from command options.
Argument:
args: arguments object |
def render_json_response(self, context_dict, status=200):
"""
Limited serialization for shipping plain data. Do not use for models
or other complex or custom objects.
"""
json_context = json.dumps(
context_dict,
cls=DjangoJSONEncoder,
**self.ge... | Limited serialization for shipping plain data. Do not use for models
or other complex or custom objects. |
def do_gen(argdict):
'''Generate the whole site.'''
site = make_site_obj(argdict)
try:
st = time.time()
site.generate()
et = time.time()
print "Generated Site in %f seconds."% (et-st)
except ValueError as e: # pragma: no cover
print "Cannot generate. You are not w... | Generate the whole site. |
def template_substitute(text, **kwargs):
"""
Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:re... | Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:return: Potentially modified text with replaced placeho... |
def copy_from(self,
container: Container,
fn_container: str,
fn_host: str
) -> None:
"""
Copies a given file from the container to a specified location on the
host machine.
"""
logger.debug("Copying file from... | Copies a given file from the container to a specified location on the
host machine. |
def todate(val):
'''Convert val to a datetime.date instance by trying several
conversion algorithm.
If it fails it raise a ValueError exception.
'''
if not val:
raise ValueError("Value not provided")
if isinstance(val, datetime):
return val.date()
elif isinstance(val, date):
... | Convert val to a datetime.date instance by trying several
conversion algorithm.
If it fails it raise a ValueError exception. |
def fetchGroupInfo(self, *group_ids):
"""
Get groups' info from IDs, unordered
:param group_ids: One or more group ID(s) to query
:return: :class:`models.Group` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed
"""
threa... | Get groups' info from IDs, unordered
:param group_ids: One or more group ID(s) to query
:return: :class:`models.Group` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed |
def request(self, path,
args=[], files=[], opts={}, stream=False,
decoder=None, headers={}, data=None):
"""Makes an HTTP request to the IPFS daemon.
This function returns the contents of the HTTP response from the IPFS
daemon.
Raises
------
... | Makes an HTTP request to the IPFS daemon.
This function returns the contents of the HTTP response from the IPFS
daemon.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.excepti... |
def randomSize(cls, widthLimits, heightLimits, origin=None):
'''
:param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle
'''
r = cl... | :param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle |
def load(self, **kwargs):
"""Loads a given resource
Loads a given resource provided a 'name' and an optional 'slot'
parameter. The 'slot' parameter is not a required load parameter
because it is provided as an optional way of constructing the
correct 'name' of the vCMP resource.... | Loads a given resource
Loads a given resource provided a 'name' and an optional 'slot'
parameter. The 'slot' parameter is not a required load parameter
because it is provided as an optional way of constructing the
correct 'name' of the vCMP resource.
:param kwargs:
:ret... |
def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory. |
def parse(self, argv, tokenizer=DefaultTokenizer):
"""
Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer
"""
args = tokenizer.tokenize(argv)
_lang = tokenizer.language_definition()
#
# for param in self.__args:
# if self._is_default_arg(param)... | Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer |
def ready(self):
"""Sets up the application after startup."""
self.log('Got', len(schemastore), 'data and',
len(configschemastore), 'component schemata.', lvl=debug) | Sets up the application after startup. |
def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is... | Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**... |
def is_blocking_notifications(self, notification_period, hosts, services, n_type, t_wished):
# pylint: disable=too-many-return-statements
"""Check if a notification is blocked by the service.
Conditions are ONE of the following::
* enable_notification is False (global)
* not in ... | Check if a notification is blocked by the service.
Conditions are ONE of the following::
* enable_notification is False (global)
* not in a notification_period
* notifications_enable is False (local)
* notification_options is 'n' or matches the state ('UNKNOWN' <=> 'u' ...)
... |
def traverse_tree_recursive(odb, tree_sha, path_prefix):
"""
:return: list of entries of the tree pointed to by the binary tree_sha. An entry
has the following format:
* [0] 20 byte sha
* [1] mode as int
* [2] path relative to the repository
:param path_prefix: prefix to prep... | :return: list of entries of the tree pointed to by the binary tree_sha. An entry
has the following format:
* [0] 20 byte sha
* [1] mode as int
* [2] path relative to the repository
:param path_prefix: prefix to prepend to the front of all returned paths |
def collect(self):
"""Collect number values from db.serverStatus() and db.engineStatus()"""
if pymongo is None:
self.log.error('Unable to import pymongo')
return
# we need this for backwards compatibility
if 'host' in self.config:
self.config['hosts'... | Collect number values from db.serverStatus() and db.engineStatus() |
def _speak_as(
self,
element,
regular_expression,
data_property_value,
operation
):
"""
Execute a operation by regular expression for element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
... | Execute a operation by regular expression for element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param regular_expression: The regular expression.
:type regular_expression: str
:param data_property_value: The value of cust... |
def setDevice(self, device):
"""Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice.
"""
print(self.pre, "setDevice :", device)
if (not device and not self.device): # None can be passed as an argumen... | Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice. |
def uploadFile(self, filename, ispickle=False, athome=False):
"""
Uploads a single file to Redunda.
:param str filename: The name of the file to upload
:param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False.
:returns: returns nothing
... | Uploads a single file to Redunda.
:param str filename: The name of the file to upload
:param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False.
:returns: returns nothing |
def __parse_domain_to_employer_stream(self, stream):
"""Parse domain to employer stream.
Each line of the stream has to contain a domain and a organization,
or employer, separated by tabs. Comment lines start with the hash
character (#)
Example:
# Domains from domains.... | Parse domain to employer stream.
Each line of the stream has to contain a domain and a organization,
or employer, separated by tabs. Comment lines start with the hash
character (#)
Example:
# Domains from domains.txt
example.org Example
example.com ... |
def getargs():
from argparse import ArgumentParser
'''
Return arguments
'''
parser = ArgumentParser(description='Answer yes or no to a question.')
parser.add_argument("question", type=str, help="A question to ask.")
return parser.parse_args() | Return arguments |
def get_commits_since(check_name, target_tag=None):
"""
Get the list of commits from `target_tag` to `HEAD` for the given check
"""
root = get_root()
target_path = os.path.join(root, check_name)
command = 'git log --pretty=%s {}{}'.format('' if target_tag is None else '{}... '.format(target_tag)... | Get the list of commits from `target_tag` to `HEAD` for the given check |
def register(self,flag):
"""Register a new :class:`Flag` instance with the Flags registry."""
super(Flags,self).__setitem__(flag.name,flag) | Register a new :class:`Flag` instance with the Flags registry. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.