positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def write_pa11y_results(item, pa11y_results, data_dir):
"""
Write the output from pa11y into a data file.
"""
data = dict(item)
data['pa11y'] = pa11y_results
# it would be nice to use the URL as the filename,
# but that gets complicated (long URLs, special characters, etc)
# so we'll ma... | Write the output from pa11y into a data file. |
def _replace_none(self, aDict):
""" Replace all None values in a dict with 'none' """
for k, v in aDict.items():
if v is None:
aDict[k] = 'none' | Replace all None values in a dict with 'none' |
def CrearAjusteBase(self,
pto_emision=1, nro_orden=None, # unificado, contrato, papel
coe_ajustado=None, # unificado
nro_contrato=None, # contrato
tipo_formulario=None, # papel
nro_formul... | Inicializa internamente los datos de una liquidación para ajustar |
def set_timestamp(cls, filename: str, response: HTTPResponse):
'''Set the Last-Modified timestamp onto the given file.
Args:
filename: The path of the file
response: Response
'''
last_modified = response.fields.get('Last-Modified')
if not last_modified:
... | Set the Last-Modified timestamp onto the given file.
Args:
filename: The path of the file
response: Response |
def _Open(self, path_spec=None, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like... | Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSError: if the ... |
def unmarshal(self, value, bind_client=None):
"""
Cast the specified value to the entity type.
"""
#self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value))
if not isinstance(value, self.type):
o = self.type()
if bind_client is not None and hasattr(o.... | Cast the specified value to the entity type. |
def parse_record(raw_record, is_training, dtype):
"""Parses a record containing a training example of an image.
The input record is parsed into a label and image, and the image is passed
through preprocessing steps (cropping, flipping, and so on).
Args:
raw_record: scalar Tensor tf.string containing a ser... | Parses a record containing a training example of an image.
The input record is parsed into a label and image, and the image is passed
through preprocessing steps (cropping, flipping, and so on).
Args:
raw_record: scalar Tensor tf.string containing a serialized
Example protocol buffer.
is_training:... |
def slistStr(slist):
""" Converts signed list to angle string. """
slist = _fixSlist(slist)
string = ':'.join(['%02d' % x for x in slist[1:]])
return slist[0] + string | Converts signed list to angle string. |
def _add_conversation(self, conversation):
"""
Add the conversation and fire the :meth:`on_conversation_added` event.
:param conversation: The conversation object to add.
:type conversation: :class:`~.AbstractConversation`
The conversation is added to the internal list of conve... | Add the conversation and fire the :meth:`on_conversation_added` event.
:param conversation: The conversation object to add.
:type conversation: :class:`~.AbstractConversation`
The conversation is added to the internal list of conversations which
can be queried at :attr:`conversations`.... |
def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a string field."""
local_DecodeVarint = _DecodeVarint
local_unicode = six.text_type
def _ConvertToUnicode(byte_str):
try:
return local_unicode(byte_str, 'utf-8')
except UnicodeDecodeError as e:
... | Returns a decoder for a string field. |
def validate(element, reference=None, report_file=None):
"""
Checks if the :class:`Element <hl7apy.core.Element>` is a valid HL7 message according to the reference
specified. If the reference is not specified, it will be used the official HL7 structures for the
elements.
In parti... | Checks if the :class:`Element <hl7apy.core.Element>` is a valid HL7 message according to the reference
specified. If the reference is not specified, it will be used the official HL7 structures for the
elements.
In particular it checks:
* the maximum and minimum number of occurrences for... |
def worksheets(self):
"""Returns a list of all :class:`worksheets <gsperad.models.Worksheet>`
in a spreadsheet.
"""
sheet_data = self.fetch_sheet_metadata()
return [Worksheet(self, x['properties']) for x in sheet_data['sheets']] | Returns a list of all :class:`worksheets <gsperad.models.Worksheet>`
in a spreadsheet. |
def _computeStatus(self, dfile, service):
"""Computes status for file, basically this means if
more than one service handles the file, it will place
a 'C' (for complicated) otherwise if status matches
between all services, will place that status"""
# If only one service request... | Computes status for file, basically this means if
more than one service handles the file, it will place
a 'C' (for complicated) otherwise if status matches
between all services, will place that status |
def validate(self):
"""Validate / fix up the current config"""
if not self.get('api_key'):
raise ValueError("api_key not found in config. Please see documentation.")
host = self.get('host') or DEFAULT_CLOUD_HOST
if host:
# remove extraneous slashes and force to by... | Validate / fix up the current config |
def is_Union(tp):
"""Python version independent check if a type is typing.Union.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
if tp is Union:
return True
try:
# Python 3.6
return tp.__origin__ is Union
except AttributeError:
try:
return isin... | Python version independent check if a type is typing.Union.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. |
def load(self, config_template, config_file=None):
"""Read the config file if it exists, else read the default config.
Creates the user config file if it doesn't exist using the template.
:type config_template: str
:param config_template: The config template file name.
:type c... | Read the config file if it exists, else read the default config.
Creates the user config file if it doesn't exist using the template.
:type config_template: str
:param config_template: The config template file name.
:type config_file: str
:param config_file: (Optional) The con... |
def gps_velocity_old(GPS_RAW_INT):
'''return GPS velocity vector'''
return Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)),
GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)), 0) | return GPS velocity vector |
def from_mat_file(cls, matfilename):
"""Load gyro data from .mat file
The MAT file should contain the following two arrays
gyro : (3, N) float ndarray
The angular velocity measurements.
timestamps : (N, ) float ndarray
Timestamps of the m... | Load gyro data from .mat file
The MAT file should contain the following two arrays
gyro : (3, N) float ndarray
The angular velocity measurements.
timestamps : (N, ) float ndarray
Timestamps of the measurements.
Parameters... |
def subnode(self, node):
"""Make `node` receiver's child."""
self.children.append(node)
node.parent = self
node.adjust_interleave(node.interleave) | Make `node` receiver's child. |
def insert(self):
"""persist the field values of this orm"""
ret = True
schema = self.schema
fields = self.depopulate(False)
q = self.query
q.set_fields(fields)
pk = q.insert()
if pk:
fields = q.fields
fields[schema.pk.name] = pk
... | persist the field values of this orm |
def takeChild(self, index):
"""
Removes the child at the given index from this item.
:param index | <int>
"""
item = super(XGanttWidgetItem, self).takeChild(index)
if item:
item.removeFromScene()
return it... | Removes the child at the given index from this item.
:param index | <int> |
def subset_bed_by_chrom(in_file, chrom, data, out_dir=None):
"""Subset a BED file to only have items from the specified chromosome.
"""
if out_dir is None:
out_dir = os.path.dirname(in_file)
base, ext = os.path.splitext(os.path.basename(in_file))
out_file = os.path.join(out_dir, "%s-%s%s" % ... | Subset a BED file to only have items from the specified chromosome. |
def format(self, member_info: bool = False):
"""
:param member_info: If True, adds also chat member info. Please, note that this additional info requires
to make ONE api call.
"""
user = self.api_object
self.__format_user(user)
if member_info and self.chat.typ... | :param member_info: If True, adds also chat member info. Please, note that this additional info requires
to make ONE api call. |
def namespace_uri(self):
"""
Finds and returns first applied URI of this node that has a namespace.
:return str: uri
"""
try:
return next(
iter(filter(lambda uri: URI(uri).namespace, self._uri))
)
except StopIteration:
... | Finds and returns first applied URI of this node that has a namespace.
:return str: uri |
def exhaust_stream(f):
"""Helper decorator for methods that exhausts the stream on return."""
def wrapper(self, stream, *args, **kwargs):
try:
return f(self, stream, *args, **kwargs)
finally:
exhaust = getattr(stream, "exhaust", None)
if exhaust is not None:
... | Helper decorator for methods that exhausts the stream on return. |
def lookup(self, key):
"""
Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
... | Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
>>> rdd.lookup(42) # slow
[42]
... |
def _search_type_in_type_comment(self, code):
""" For more info see:
https://www.python.org/dev/peps/pep-0484/#type-comments
>>> AssignmentProvider()._search_type_in_type_comment('type: int')
['int']
"""
for p in self.PEP0484_TYPE_COMMENT_PATTERNS:
match = p.... | For more info see:
https://www.python.org/dev/peps/pep-0484/#type-comments
>>> AssignmentProvider()._search_type_in_type_comment('type: int')
['int'] |
def jacobi(a, b):
'''Calculates the value of the Jacobi symbol (a/b) where both a and b are
positive integers, and b is odd
:returns: -1, 0 or 1
'''
assert a > 0
assert b > 0
if a == 0:
return 0
result = 1
while a > 1:
if a & 1:
if ((a-1)*(b-1) >> 2) & ... | Calculates the value of the Jacobi symbol (a/b) where both a and b are
positive integers, and b is odd
:returns: -1, 0 or 1 |
def validipaddr(address):
"""
Returns True if `address` is a valid IPv4 address.
>>> validipaddr('192.168.1.1')
True
>>> validipaddr('192.168.1.800')
False
>>> validipaddr('192.168.1')
False
"""
try:
octets = address.split('.')
if len(... | Returns True if `address` is a valid IPv4 address.
>>> validipaddr('192.168.1.1')
True
>>> validipaddr('192.168.1.800')
False
>>> validipaddr('192.168.1')
False |
def remove_triple(
self,
subj: URIRef,
pred: URIRef,
obj: Union[URIRef, Literal]
) -> None:
""" Removes triple from rdflib Graph
You must input the triple in its URIRef or Literal form for each node exactly the way it
was inputed or it wil... | Removes triple from rdflib Graph
You must input the triple in its URIRef or Literal form for each node exactly the way it
was inputed or it will not delete the triple.
Args:
subj: Entity subject to be removed it its the only node with this subject; else this is
just... |
def indent(self, text, n_indents=1, skipping=False):
"""
Indent text with single spaces.
Parameters
----------
:param text : string
The text which get a specific indentation.
:param n_indents : int, default: 1
The number of indentations.
:... | Indent text with single spaces.
Parameters
----------
:param text : string
The text which get a specific indentation.
:param n_indents : int, default: 1
The number of indentations.
:param skipping : boolean, default: False
Whether to skip the ... |
def display(self, image):
"""
Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the OLED
display.
:param image: Image to display.
:type image: :py:mod:`PIL.Image`
"""
assert(image.mode == self.mode)
assert(image.size == self.size)
image = self.pr... | Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the OLED
display.
:param image: Image to display.
:type image: :py:mod:`PIL.Image` |
def load_lexer_from_file(filename, lexername="CustomLexer", **options):
"""Load a lexer from a file.
This method expects a file located relative to the current working
directory, which contains a Lexer class. By default, it expects the
Lexer to be name CustomLexer; you can specify your own class name
... | Load a lexer from a file.
This method expects a file located relative to the current working
directory, which contains a Lexer class. By default, it expects the
Lexer to be name CustomLexer; you can specify your own class name
as the second argument to this function.
Users should be very careful w... |
def short_form_one_format(jupytext_format):
"""Represent one jupytext format as a string"""
if not isinstance(jupytext_format, dict):
return jupytext_format
fmt = jupytext_format['extension']
if 'suffix' in jupytext_format:
fmt = jupytext_format['suffix'] + fmt
elif fmt.startswith('.... | Represent one jupytext format as a string |
def trigger_keyphrases(
text = None, # input text to parse
keyphrases = None, # keyphrases for parsing input text
response = None, # optional text response on trigger
function = None, # optional function on trigger... | Parse input text for keyphrases. If any keyphrases are found, respond with
text or by seeking confirmation or by engaging a function with optional
keyword arguments. Return text or True if triggered and return False if not
triggered. If confirmation is required, a confirmation object is returned,
encaps... |
def batch_remove_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11):
""" Batch Remove Absolute (retrain)
xlabel = "Fraction of features removed"
ylabel = "1 - R^2"
transform = "one_minus"
sort_order = 13
"""
return __run_batch_abs_metric(measures.batch_remove_retrain, X... | Batch Remove Absolute (retrain)
xlabel = "Fraction of features removed"
ylabel = "1 - R^2"
transform = "one_minus"
sort_order = 13 |
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
... | Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar. |
def get_handler_fp(logger):
"""
Get handler_fp.
This method is integrated to LoggerFactory Object in the future.
:param logging.Logger logger: Python logging.Logger. logger instance.
:rtype: logging.Logger.handlers.BaseRotatingHandler
:return: Handler or Handler's stream. We call it `handler_fp`... | Get handler_fp.
This method is integrated to LoggerFactory Object in the future.
:param logging.Logger logger: Python logging.Logger. logger instance.
:rtype: logging.Logger.handlers.BaseRotatingHandler
:return: Handler or Handler's stream. We call it `handler_fp`. |
def fromstring(cls, s, *args, **kwargs):
""" Returns a new Pattern from the given string.
Constraints are separated by a space.
If a constraint contains a space, it must be wrapped in [].
"""
s = s.replace("\(", "&lparen;")
s = s.replace("\)", "&rparen;")
... | Returns a new Pattern from the given string.
Constraints are separated by a space.
If a constraint contains a space, it must be wrapped in []. |
def present(self, name, *args):
"""Require that an owner name (and optionally an rdata type,
or specific rdataset) exists as a prerequisite to the
execution of the update. The first argument is always a name.
The other arguments can be:
- rdataset...
- ... | Require that an owner name (and optionally an rdata type,
or specific rdataset) exists as a prerequisite to the
execution of the update. The first argument is always a name.
The other arguments can be:
- rdataset...
- rdata...
- rdtype, string.... |
def complete(self, match, subject_graph):
"""Check the completeness of the ring match"""
if not CustomPattern.complete(self, match, subject_graph):
return False
if self.strong:
# If the ring is not strong, return False
if self.size % 2 == 0:
# ... | Check the completeness of the ring match |
def get_types(obj, **kwargs):
"""Get the types of an iterable."""
max_iterable_length = kwargs.get('max_iterable_length', 100000)
it, = itertools.tee(obj, 1)
s = set()
too_big = False
for i, v in enumerate(it):
if i <= max_iterable_length:
s.add(type(v))
else:
... | Get the types of an iterable. |
def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
document = self._get_document(id)
if document:
session_json = document["session"]
return json_loads(session_json)
return {} | 根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 |
def OnFind(self, event):
"""Find functionality, called from toolbar, returns find position"""
# Search starts in next cell after the current one
gridpos = list(self.grid.actions.cursor)
text, flags = event.text, event.flags
findpos = self.grid.actions.find(gridpos, text, flags)
... | Find functionality, called from toolbar, returns find position |
def paste_from_clipboard(self):
"""
Pastes files from clipboard.
"""
to = self.get_current_path()
if os.path.isfile(to):
to = os.path.abspath(os.path.join(to, os.pardir))
mime = QtWidgets.QApplication.clipboard().mimeData()
paste_operation = None
... | Pastes files from clipboard. |
def DOM_setOuterHTML(self, nodeId, outerHTML):
"""
Function path: DOM.setOuterHTML
Domain: DOM
Method name: setOuterHTML
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the node to set markup for.
'outerHTML' (type: string) -> Outer HTML markup to set.
No return value.
... | Function path: DOM.setOuterHTML
Domain: DOM
Method name: setOuterHTML
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the node to set markup for.
'outerHTML' (type: string) -> Outer HTML markup to set.
No return value.
Description: Sets node HTML markup, returns new n... |
def initial_state(self) -> StateTensor:
'''Returns the initial state tensor.'''
s0 = []
for fluent in self._compiler.compile_initial_state(self._batch_size):
s0.append(self._output_size(fluent))
s0 = tuple(s0)
return s0 | Returns the initial state tensor. |
def set_level(self, position, channel=None):
"""Seek a specific value by specifying a float() from 0.0 to 1.0."""
try:
position = float(position)
except Exception as err:
LOG.debug("HelperLevel.set_level: Exception %s" % (err,))
return False
self.writ... | Seek a specific value by specifying a float() from 0.0 to 1.0. |
def upload_directory_contents(input_dict, environment_dict):
"""This function serves to upload every file in a user-supplied
source directory to all of the vessels in the current target group.
It essentially calls seash's `upload` function repeatedly, each
time with a file name taken from the source directory... | This function serves to upload every file in a user-supplied
source directory to all of the vessels in the current target group.
It essentially calls seash's `upload` function repeatedly, each
time with a file name taken from the source directory.
A note on the input_dict argument:
`input_dict` contains ou... |
def randomize(vm,
length=(10,10),
ints=(0,999),
strs=(1,10),
chars=(32,126),
instruction_ratio=0.5,
number_string_ratio=0.8,
exclude=map(crianza.instructions.lookup, [".", "exit", "read", "write", "str"]),
restrict_to=None):
"""Replaces existing code ... | Replaces existing code with completely random instructions. Does not
optimize code after generating it.
Args:
length: Tuple of minimum and maximum code lengths. Code length will
be a random number between these two, inclusive values.
ints: Integers in the code will be selected at rando... |
def remove_unnecessary_whitespace(css):
"""Remove unnecessary whitespace characters."""
def pseudoclasscolon(css):
"""
Prevents 'p :link' from becoming 'p:link'.
Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is
translated back again later.
"""
... | Remove unnecessary whitespace characters. |
def prepare(path, name): # type: (str, str) -> None
"""Prepare a Python script (or module) to be imported as a module.
If the script does not contain a setup.py file, it creates a minimal setup.
Args:
path (str): path to directory with the script or module.
name (str): name of the script or... | Prepare a Python script (or module) to be imported as a module.
If the script does not contain a setup.py file, it creates a minimal setup.
Args:
path (str): path to directory with the script or module.
name (str): name of the script or module. |
def hasFeature(self, prop, check_softs=False):
"""Return if there is a property with that name."""
return prop in self.props or (check_softs and
any([fs.hasFeature(prop) for fs in self.props.get(SoftFeatures.SOFT, [])])) | Return if there is a property with that name. |
def rm(filename, recursive=False, force=False):
"""Removes a file or directory tree."""
return auto(remove_file, filename, recursive, force) | Removes a file or directory tree. |
def _get_map_from_user_by_id(self, user, map_id):
""" Get a mapfile owned by a user from the database by
map_id. """
req = Session.query(Map).select_from(join(Map, User))
try:
return req.filter(and_(User.login==user, Map.id==map_id)).one()
except Exception, e:
... | Get a mapfile owned by a user from the database by
map_id. |
def named_module(name):
"""Returns a module given its name."""
module = __import__(name)
packages = name.split(".")[1:]
m = module
for p in packages:
m = getattr(m, p)
return m | Returns a module given its name. |
async def on_isupport_maxbans(self, value):
""" Maximum entries in ban list. Replaced by MAXLIST. """
if 'MAXLIST' not in self._isupport:
if not self._list_limits:
self._list_limits = {}
self._list_limits['b'] = int(value) | Maximum entries in ban list. Replaced by MAXLIST. |
def rshares_to_steem (self, rshares):
''' Gets the reward pool balances
then calculates rshares to steem
'''
self.reward_pool_balances()
return round(
rshares
* self.reward_balance
/ self.recent_claims
* self.base, 4) | Gets the reward pool balances
then calculates rshares to steem |
def update(self):
"""
The function to draw a new frame for the particle system.
"""
# Spawn new particles if required
if self.time_left > 0:
self.time_left -= 1
for _ in range(self._count):
new_particle = self._new_particle()
... | The function to draw a new frame for the particle system. |
def gevent_worker(self):
"""
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
"""
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
... | Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. |
def getresource(self, schemacls, name):
"""Get a resource from a builder name.
:param type schemacls: waited schema class.
:param str name: builder name to use.
:return: resource returned by the right builder.getresource(schema).
"""
return _SCHEMAFACTORY.getresource(schemacls=schemacls, name=n... | Get a resource from a builder name.
:param type schemacls: waited schema class.
:param str name: builder name to use.
:return: resource returned by the right builder.getresource(schema). |
def data_from_cli(opts):
"""Loads the data needed for a model from the given
command-line options. Gates specifed on the command line are also applied.
Parameters
----------
opts : ArgumentParser parsed args
Argument options parsed from a command line string (the sort of thing
retur... | Loads the data needed for a model from the given
command-line options. Gates specifed on the command line are also applied.
Parameters
----------
opts : ArgumentParser parsed args
Argument options parsed from a command line string (the sort of thing
returned by `parser.parse_args`).
... |
def get_installed_extjs_apps():
"""
Get all installed extjs apps.
:return: List of ``(appdir, module, appname)``.
"""
installed_apps = []
checked = set()
for app in settings.INSTALLED_APPS:
if not app.startswith('django.') and not app in checked:
checked.add(app)
... | Get all installed extjs apps.
:return: List of ``(appdir, module, appname)``. |
def parse_date(date, default=None):
""" Parse a valid date """
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H... | Parse a valid date |
def predict_cumulative_hazard(self, X, times=None, ancillary_X=None):
"""
Return the cumulative hazard rate of subjects in X at time points.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
... | Return the cumulative hazard rate of subjects in X at time points.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order a... |
def get_art(cache_dir, size, client):
"""Get the album art."""
song = client.currentsong()
if len(song) < 2:
print("album: Nothing currently playing.")
return
file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "")
file_name = cache_dir / file_name
if file_... | Get the album art. |
def get_interface(interface):
"""Support Centos standard physical interface,
such as eth0.
"""
# Supported CentOS Version
supported_dists = ['7.0', '6.5']
def format_centos_7_0(inf):
pattern = r'<([A-Z]+)'
state = re.search(pattern, stdout[0]).groups()[0]
state = 'UP'... | Support Centos standard physical interface,
such as eth0. |
def crunch_dir(name, n=50):
"""Puts "..." in the middle of a directory name if lengh > n."""
if len(name) > n + 3:
name = "..." + name[-n:]
return name | Puts "..." in the middle of a directory name if lengh > n. |
def alias_function(function, class_name):
"""Create a RedditContentObject function mapped to a BaseReddit function.
The BaseReddit classes define the majority of the API's functions. The
first argument for many of these functions is the RedditContentObject that
they operate on. This factory returns fun... | Create a RedditContentObject function mapped to a BaseReddit function.
The BaseReddit classes define the majority of the API's functions. The
first argument for many of these functions is the RedditContentObject that
they operate on. This factory returns functions appropriate to be called on
a RedditCo... |
def fo_pct_by_zone(self):
"""
Get the by team face-off win % by zone. Format is
:returns: dict ``{ 'home/away': { 'off/def/neut': % } }``
"""
bz = self.by_zone
return {
t: {
z: bz[t][z]['won']/(1.0*bz[t][z]['total']) if bz[t][z]['t... | Get the by team face-off win % by zone. Format is
:returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` |
def update_member_profile(self, brief_details, profile_details):
''' a method to update user profile details on meetup
:param brief_details: dictionary with member brief details with updated values
:param profile_details: dictionary with member profile details with updated values
... | a method to update user profile details on meetup
:param brief_details: dictionary with member brief details with updated values
:param profile_details: dictionary with member profile details with updated values
:return: dictionary with partial profile details inside [json] key |
def present(name, properties=None, filesystem_properties=None, layout=None, config=None):
'''
ensure storage pool is present on the system
name : string
name of storage pool
properties : dict
optional set of properties to set for the storage pool
filesystem_properties : dict
... | ensure storage pool is present on the system
name : string
name of storage pool
properties : dict
optional set of properties to set for the storage pool
filesystem_properties : dict
optional set of filesystem properties to set for the storage pool (creation only)
layout: dict
... |
def sigma_cached(self, psd):
""" Cache sigma calculate for use in tandem with the FilterBank class
"""
if not hasattr(self, '_sigmasq'):
from pycbc.opt import LimitedSizeDict
self._sigmasq = LimitedSizeDict(size_limit=2**5)
key = id(psd)
if not hasattr(psd, '_sigma_cached_key'):
... | Cache sigma calculate for use in tandem with the FilterBank class |
def get(self, section, option, default=NoDefault):
"""
Get an option
section=None: attribute a default section name
default: default value (if not specified, an exception
will be raised if option doesn't exist)
"""
section = self._check_section_option(secti... | Get an option
section=None: attribute a default section name
default: default value (if not specified, an exception
will be raised if option doesn't exist) |
def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is av... | Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it. |
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the lea... | Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary |
def _async_recv(self):
"""No raw bytes should escape from this, all byte encoding and
decoding should be handling inside this function"""
logging.info("Receive loop started")
recbuffer = b""
while not self._stop_event.is_set():
time.sleep(0.01)
try:
... | No raw bytes should escape from this, all byte encoding and
decoding should be handling inside this function |
def get_static_parent(raml_resource, method=None):
""" Get static parent resource of :raml_resource: with HTTP
method :method:.
:param raml_resource:Instance of ramlfications.raml.ResourceNode.
:param method: HTTP method name which matching static resource
must have.
"""
parent = raml_r... | Get static parent resource of :raml_resource: with HTTP
method :method:.
:param raml_resource:Instance of ramlfications.raml.ResourceNode.
:param method: HTTP method name which matching static resource
must have. |
def _sync_binary_dep_links(self, target, gopath, lib_binary_map):
"""Syncs symlinks under gopath to the library binaries of target's transitive dependencies.
:param Target target: Target whose transitive dependencies must be linked.
:param str gopath: $GOPATH of target whose "pkg/" directory must be popula... | Syncs symlinks under gopath to the library binaries of target's transitive dependencies.
:param Target target: Target whose transitive dependencies must be linked.
:param str gopath: $GOPATH of target whose "pkg/" directory must be populated with links
to library binaries.
:param dic... |
def canonical_interface_name(interface, addl_name_map=None):
"""Function to return an interface's canonical name (fully expanded name).
Use of explicit matches used to indicate a clear understanding on any potential
match. Regex and other looser matching methods were not implmented to avoid false
posit... | Function to return an interface's canonical name (fully expanded name).
Use of explicit matches used to indicate a clear understanding on any potential
match. Regex and other looser matching methods were not implmented to avoid false
positive matches. As an example, it would make sense to do "[P|p][O|o]" w... |
def convert_clip(node, **kwargs):
"""Map MXNet's Clip operator attributes to onnx's Clip operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
a_min = np.float(attrs.get('a_min', -np.inf))
a_max = np.float(attrs.get('a_max', np.inf))
clip_node = onnx... | Map MXNet's Clip operator attributes to onnx's Clip operator
and return the created node. |
def on_down(self, host):
"""
Called by the parent Cluster instance when a node is marked down.
Only intended for internal use.
"""
future = self.remove_pool(host)
if future:
future.add_done_callback(lambda f: self.update_created_pools()) | Called by the parent Cluster instance when a node is marked down.
Only intended for internal use. |
def _get_pages(page_size, total_records):
"""
Given a page size (records per page) and a total number of
records, return the page numbers to be retrieved.
"""
pages = total_records/page_size+bool(total_records%page_size)
return range(1, pages+1) | Given a page size (records per page) and a total number of
records, return the page numbers to be retrieved. |
def parse_xml_data(content, raincontent, latitude=52.091579,
longitude=5.119734, timeframe=60):
"""Parse the raw data and return as data dictionary."""
result = {SUCCESS: False, MESSAGE: None, DATA: None}
if timeframe < 5 or timeframe > 120:
raise ValueError("Timeframe must be >=... | Parse the raw data and return as data dictionary. |
def data(offset, bytes):
"""Return Data record. This constructs the full record, including
the length information, the record type (0x00), the
checksum, and the offset.
@param offset load offset of first byte.
@param bytes list of byte values to pack into record.
@... | Return Data record. This constructs the full record, including
the length information, the record type (0x00), the
checksum, and the offset.
@param offset load offset of first byte.
@param bytes list of byte values to pack into record.
@return String representation... |
def store_extra_info(self, key: str, value: Any) -> None:
"""
Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None
"""
self.extra_keys[key] = value | Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None |
def validate_attrs(resource_attr_ids, scenario_id, template_id=None):
"""
Check that multiple resource attribute satisfy the requirements of the types of resources to
which the they are attached.
"""
multi_rs = db.DBSession.query(ResourceScenario).\
filter(Resourc... | Check that multiple resource attribute satisfy the requirements of the types of resources to
which the they are attached. |
def instance(self, id=None, application=None, name=None, revision=None, environment=None, parameters=None, submodules=None, destroyInterval=None):
""" Smart method. It does everything, to return Instance with given parameters within the application.
If instance found running and given parameters are act... | Smart method. It does everything, to return Instance with given parameters within the application.
If instance found running and given parameters are actual: return it.
If instance found, but parameters differs - reconfigure instance with new parameters.
If instance not found: launch instance wi... |
def _open_generic_http(self, connection_factory, url, data):
"""Make an HTTP connection using connection_class.
This is an internal method that should be called from
open_http() or open_https().
Arguments:
- connection_factory should take a host name and return an
HTT... | Make an HTTP connection using connection_class.
This is an internal method that should be called from
open_http() or open_https().
Arguments:
- connection_factory should take a host name and return an
HTTPConnection instance.
- url is the url to retrieval or a host, r... |
def hicpro_capture_chart (self):
""" Generate Capture Hi-C plot"""
keys = OrderedDict()
keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' }
keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interac... | Generate Capture Hi-C plot |
def dispatch_request(self, req):
"""
Dispatch a request object.
"""
log.debug("Dispatching request: {}".format(str(req)))
# make sure it's valid
res = None
try:
req.validate()
except MissingFieldError as e:
res = APIMissingFieldErr... | Dispatch a request object. |
def list_gebouwen_adapter(obj, request):
"""
Adapter for rendering a list of
:class:`crabpy.gateway.crab.Gebouw` to json.
"""
return {
'id': obj.id,
'aard': {
'id': obj.aard.id,
'naam': obj.aard.naam,
'definitie': obj.aard.definitie
},
... | Adapter for rendering a list of
:class:`crabpy.gateway.crab.Gebouw` to json. |
def pfeedback(self, msg: str) -> None:
"""For printing nonessential feedback. Can be silenced with `quiet`.
Inclusion in redirected output is controlled by `feedback_to_output`."""
if not self.quiet:
if self.feedback_to_output:
self.poutput(msg)
else:
... | For printing nonessential feedback. Can be silenced with `quiet`.
Inclusion in redirected output is controlled by `feedback_to_output`. |
def load_data():
data_dir = "/Users/annaho/Data/AAOmega"
out_dir = "%s/%s" %(data_dir, "Run_13_July")
""" Use all the above functions to set data up for The Cannon """
ff, wl, tr_flux, tr_ivar = load_ref_spectra()
""" pick one that doesn't have extra dead pixels """
skylines = tr_ivar[4,:] # s... | Use all the above functions to set data up for The Cannon |
def configure(access_key=None, secret_key=None, logger=None):
'''
Configures s3cmd prior to first use.
If no arguments are provided, you will be prompted to enter
the access key and secret key interactively.
Args:
access_key (str): AWS access key
secret_key (str): AWS secret key
... | Configures s3cmd prior to first use.
If no arguments are provided, you will be prompted to enter
the access key and secret key interactively.
Args:
access_key (str): AWS access key
secret_key (str): AWS secret key |
def get_sources_headers_for_target(self, target):
"""Return a list of file arguments to provide to the compiler.
NB: result list will contain both header and source files!
:raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources.
"""
# Get source paths relativ... | Return a list of file arguments to provide to the compiler.
NB: result list will contain both header and source files!
:raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources. |
def defrag(plist):
"""defrag(plist) -> ([not fragmented], [defragmented],
[ [bad fragments], [bad fragments], ... ])"""
frags = defaultdict(PacketList)
nofrag = PacketList()
for p in plist:
ip = p[IP]
if IP not in p:
nofrag.append(p)
continue
... | defrag(plist) -> ([not fragmented], [defragmented],
[ [bad fragments], [bad fragments], ... ]) |
def _invoke_hook(hook_name, target):
"""
Generic hook invocation.
"""
try:
for value in getattr(target, hook_name):
func, args, kwargs = value
func(target, *args, **kwargs)
except AttributeError:
# no hook defined
pass
except (TypeError, ValueErro... | Generic hook invocation. |
def mavlink_packet(self, m):
'''trigger sends from ATTITUDE packets'''
if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3:
gen_settings.home_lat = m.lat * 1.0e-7
gen_settings.home_lon = m.lon * 1.0e-7
self.have_home = True
if self.... | trigger sends from ATTITUDE packets |
def create(self, timeout=values.unset, priority=values.unset,
task_channel=values.unset, workflow_sid=values.unset,
attributes=values.unset):
"""
Create a new TaskInstance
:param unicode timeout: The amount of time in seconds the task is allowed to live up to a max... | Create a new TaskInstance
:param unicode timeout: The amount of time in seconds the task is allowed to live up to a maximum of 2 weeks.
:param unicode priority: Override priority for the Task.
:param unicode task_channel: When MultiTasking is enabled specify the type of the task by passing eith... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.