text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def config_value(key, app=None, default=None, prefix='hive_'):
"""Get a Flask-Security configuration value.
:param key: The configuration key without the prefix `SECURITY_`
:param app: An optional specific application to inspect. Defaults to
Flask's `current_app`
:param default: An opti... | 0.002141 |
def change_message_visibility(self, queue, receipt_handle,
visibility_timeout, callback=None):
"""
Extends the read lock timeout for the specified message from
the specified queue to the specified value.
:type queue: A :class:`boto.sqs.queue.Queue` obje... | 0.008351 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AssistantContext for this AssistantInstance
:rtype: twilio.rest.autopilot.v1.assistant.AssistantC... | 0.010204 |
def quantify_field_dict(field_dict, precision=None, date_precision=None, cleaner=str.strip):
r"""Convert strings and datetime objects in the values of a dict into float/int/long, if possible
Arguments:
field_dict (dict): The dict to have any values (not keys) that are strings "quantified"
precision... | 0.005737 |
def synchronized(func):
'''Decorator to synchronize function.'''
func.__lock__ = threading.Lock()
def synced_func(*args, **kargs):
with func.__lock__:
return func(*args, **kargs)
return synced_func | 0.032558 |
def _create_markup_plugin(language, model):
"""
Create a new MarkupPlugin class that represents the plugin type.
"""
form = type("{0}MarkupItemForm".format(language.capitalize()), (MarkupItemForm,), {
'default_language': language,
})
classname = "{0}MarkupPlugin".format(language.capital... | 0.004348 |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Terminal Server Client Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.Wi... | 0.00814 |
def response(self, beacon_config, request, client_address):
""" :meth:`.WBeaconMessengerBase.request` method implementation.
see :class:`.WBeaconGouverneurMessenger`
"""
return self._message(beacon_config, invert_hello=self.__invert_hello) | 0.024194 |
def activate_right(self, token):
"""Make a copy of the received token and call `_activate_right`."""
watchers.MATCHER.debug(
"Node <%s> activated right with token %r", self, token)
return self._activate_right(token.copy()) | 0.007752 |
def point_on_screen(self, pos):
"""
Is the point still on the screen?
:param pos: Point
:type pos: tuple
:return: Is it?
:rtype: bool
"""
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:
return True
else:
return F... | 0.006173 |
def cancelAllPendingResults( self ):
"""Cancel all pending results."""
# grab all the pending job ids
jobs = self.pendingResults()
if len(jobs) > 0:
# abort in the cluster
self._abortJobs(jobs)
# cancel in the notebook ... | 0.018373 |
def get_short_name(self):
"""
Returns the short type name of this X.509 extension.
The result is a byte string such as :py:const:`b"basicConstraints"`.
:return: The short type name.
:rtype: :py:data:`bytes`
.. versionadded:: 0.12
"""
obj = _lib.X509_EXT... | 0.004556 |
def _get_dbt_columns_from_bq_table(self, table):
"Translates BQ SchemaField dicts into dbt BigQueryColumn objects"
columns = []
for col in table.schema:
# BigQuery returns type labels that are not valid type specifiers
dtype = self.Column.translate_type(col.field_type)
... | 0.004292 |
def option(*param_decls, **attrs):
"""Attaches an option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged (except ``cls``).
This is equivalent to creating an :class:`Option` instance manually
and attachin... | 0.001385 |
def cmPrecision(cm, average=True):
"""
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
... | 0.003854 |
def extract_followups(task):
"""
Retrieve callbacks and errbacks from provided task instance, disables
tasks callbacks.
"""
callbacks = task.request.callbacks
errbacks = task.request.errbacks
task.request.callbacks = None
return {'link': callbacks, 'link_error': errbacks} | 0.003289 |
def read_default_config(self):
"""Read the default config file.
:raises DefaultConfigValidationError: There was a validation error with
the *default* file.
"""
if self.validate:
self.default_config = ConfigObj(configspec=self.def... | 0.00163 |
def saveXml( self, xparent, item ):
"""
Saves the information from the tree item to xml.
:param xparent | <xml.etree.ElementTree.Element>
item | <QTreeWidgetItem>
"""
key = nativestring(unwrapVariant(item.data(0, Qt.UserRole)))
... | 0.01423 |
def new(self, br, ino, sector_count, load_seg, media_name, system_type,
platform_id, bootable):
# type: (headervd.BootRecord, inode.Inode, int, int, str, int, int, bool) -> None
'''
A method to create a new El Torito Boot Catalog.
Parameters:
br - The boot record th... | 0.005727 |
def wilcoxont(x, y):
"""
Calculates the Wilcoxon T-test for related samples and returns the
result. A non-parametric T-test.
Usage: lwilcoxont(x,y)
Returns: a t-statistic, two-tail probability estimate
"""
if len(x) != len(y):
raise ValueError('Unequal N in wilcoxont. Aborting.')
d = []
for... | 0.001109 |
def residuals(self,Y):
""" Creates the model residuals
Parameters
----------
Y : np.array
The dependent variables Y
Returns
----------
The model residuals
"""
return (Y-np.dot(self._create_B(Y),self._create_Z(Y))) | 0.016181 |
def _watcher_thread(self):
"""
Periodically attempt to upload the crash reports. If any upload method is successful, delete the saved reports.
"""
while 1:
time.sleep(self.check_interval)
if not self._watcher_running:
break
self.logger.... | 0.006309 |
def token_network_connect(
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
funds: TokenAmount,
initial_channel_target: int = 3,
joinable_funds_target: float = 0.4,
) -> None:
""" Automatically maintain channels op... | 0.005276 |
def get_script(name=None): # noqa: E501
"""Retrieve the contents of a script
Retrieve the contents of a script # noqa: E501
:param name: The script name.
:type name: str
:rtype: Response
"""
if(not hasAccess()):
return redirectUnauthorized()
driver = LoadedDrivers.getDefaul... | 0.002532 |
def l2traceroute_result_input_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute_result = ET.Element("l2traceroute_result")
config = l2traceroute_result
input = ET.SubElement(l2traceroute_result, "input")
session_id =... | 0.004024 |
def create_send_message(self, string_message, controller, zone=None, parameter=None):
""" Creates a message from a string, substituting the necessary parameters,
that is ready to send to the socket """
cc = hex(int(controller) - 1).replace('0x', '') # RNET requires controller value to be zero ... | 0.009182 |
def child_level(self):
"""Return the child level given handled levels."""
HANDLED_LEVELS = current_app.config.get('HANDLED_LEVELS')
try:
return HANDLED_LEVELS[HANDLED_LEVELS.index(self.level) - 1]
except (IndexError, ValueError):
return None | 0.006734 |
def assets2s3():
""" Upload assets files to S3 """
import flask_s3
header("Assets2S3...")
print("")
print("Building assets files..." )
print("")
build_assets(application.app)
print("")
print("Uploading assets files to S3 ...")
flask_s3.create_all(application.app)
print("") | 0.006289 |
def read_latoolscfg():
"""
Reads configuration, returns a ConfigParser object.
Distinct from read_configuration, which returns a dict.
"""
config_file = pkgrs.resource_filename('latools', 'latools.cfg')
cf = configparser.ConfigParser()
cf.read(config_file)
return config_file, cf | 0.003205 |
def preprocess(*_unused, **processors):
"""
Decorator that applies pre-processors to the arguments of a function before
calling the function.
Parameters
----------
**processors : dict
Map from argument name -> processor function.
A processor function takes three arguments: (fun... | 0.000394 |
def get_ref_annotation_at_time(self, tier, time):
"""Give the ref annotations at the given time of the form
``[(start, end, value, refvalue)]``
:param str tier: Name of the tier.
:param int time: Time of the annotation of the parent.
:returns: List of annotations at that time.
... | 0.002639 |
def subtree(self, event, create = False):
'''
Find a subtree from an event
'''
current = self
for i in range(self.depth, len(event.indices)):
if not hasattr(current, 'index'):
return current
ind = event.indices[i]
if create:
... | 0.008264 |
def _init_map(self):
"""stub"""
super(TextAnswerFormRecord, self)._init_map()
self.my_osid_object_form._my_map['minStringLength'] = \
self._min_string_length_metadata['default_cardinal_values'][0]
self.my_osid_object_form._my_map['maxStringLength'] = \
self._max_s... | 0.005391 |
async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters):
"""
This function resolves a given object in the remote backend services
"""
try:
# check if an object with that name has been registered
registered = [model ... | 0.003703 |
def manage_work_queue(queue_name):
"""Page for viewing the contents of a work queue."""
modify_form = forms.ModifyWorkQueueTaskForm()
if modify_form.validate_on_submit():
primary_key = (modify_form.task_id.data, queue_name)
task = work_queue.WorkQueue.query.get(primary_key)
if task:
... | 0.000577 |
def _cmd(self, command, data=None, params=None, api_version=1):
"""
Invokes a command on the resource. Commands are expected to be under the
"commands/" sub-resource.
"""
return self._post("commands/" + command, ApiCommand,
data=data, params=params, api_version=api_version) | 0.006623 |
def geis2mef(sciname, convert_dq=True):
"""
Converts a GEIS science file and its corresponding
data quality file (if present) to MEF format
Writes out both files to disk.
Returns the new name of the science image.
"""
clobber = True
mode = 'update'
memmap = True
# Input was speci... | 0.001408 |
def _getPhysicalName(self):
"""Get name in HDL """
if hasattr(self, "_boundedEntityPort"):
return self._boundedEntityPort.name
else:
return self._getFullName().replace('.', self._NAME_SEPARATOR) | 0.008264 |
def map_overlay_obs(self):
"""Returns capabilities data for observation map overlays."""
return json.loads(self._query(LAYER, OBSERVATIONS, ALL, CAPABILITIES, "").decode(errors="replace")) | 0.014706 |
def copy_meta_data_from_state_m(self, source_state_m):
"""Dismiss current meta data and copy meta data from given state model
In addition to the state model method, also the meta data of container states is copied. Then, the meta data
of child states are recursively copied.
:param sour... | 0.004598 |
def printFields(self, f, d):
"""
Prints out table rows based on the size of the data in columns
"""
for field in self.fields:
fstr = field["title"]
dstr = field["description"]
flen = f - len(fstr)
dlen = d - len(dstr)
print("|{0... | 0.005305 |
def actionAngle_physical_input(method):
"""Decorator to convert inputs to actionAngle functions from physical
to internal coordinates"""
@wraps(method)
def wrapper(*args,**kwargs):
if len(args) < 3: # orbit input
return method(*args,**kwargs)
ro= kwargs.get('ro',None)
... | 0.017823 |
def undo_nested_group(self):
"""
Performs the last group opened, or the top group on the undo stack.
Creates a redo group with the same name.
"""
if self._undoing or self._redoing:
raise RuntimeError
if self._open:
group = self._open.pop()
... | 0.003257 |
def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... | 0.002172 |
def _full_keys(keys, ndim):
"""
Given keys such as those passed to ``__getitem__`` for an
array of ndim, return a fully expanded tuple of keys.
In all instances, the result of this operation should follow:
array[keys] == array[_full_keys(keys, array.ndim)]
"""
if not isinstance(keys, ... | 0.000616 |
def add_term(self,term_obj):
"""
Adds a term to the term layer
@type term_obj: L{Cterm}
@param term_obj: the term object
"""
if self.term_layer is None:
self.term_layer = Cterms(type=self.type)
self.root.append(self.term_layer.get_node())
s... | 0.008499 |
def view_edit(name=None):
"""Edit or creates a new page.
.. note:: this is a bottle view
if no page name is given, creates a new page.
Keyword Arguments:
:name: (str) -- name of the page (OPTIONAL)
Returns:
bottle response object
"""
response.set_header('Cache-control', '... | 0.000715 |
def update_state(self):
"""
Update state with latest info from Wink API.
"""
response = self.api_interface.get_device_state(self, type_override="button")
return self._update_state_from_response(response) | 0.012346 |
def wind_speed(u, v):
r"""Compute the wind speed from u and v-components.
Parameters
----------
u : array_like
Wind component in the X (East-West) direction
v : array_like
Wind component in the Y (North-South) direction
Returns
-------
wind speed: array_like
The... | 0.002242 |
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
context['poster'] = self.poster
return context | 0.009009 |
def authorization_required(self):
"""
.. versionadded:: 1.3.0
This is a decorator for a view function. If the current user does not
have an OAuth token, then they will be redirected to the
:meth:`~flask_dance.consumer.oauth1.OAuth1ConsumerBlueprint.login`
view to obtain ... | 0.002755 |
def _epd_function(coeffs, fluxes, xcc, ycc, bgv, bge):
'''This is the EPD function to fit.
Parameters
----------
coeffs : array-like of floats
Contains the EPD coefficients that will be used to generate the EPD fit
function.
fluxes : array-like
The flux measurement array b... | 0.000911 |
def list_columns(self,table=None,verbose=None):
"""
Returns the list of columns in the table.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:returns: list of col... | 0.019305 |
def delete_segment_allocation_range(context, sa_id):
"""Delete a segment_allocation_range.
: param context: neutron api request context
: param id: UUID representing the segment_allocation_range to delete.
"""
LOG.info("delete_segment_allocation_range %s for tenant %s" %
(sa_id, contex... | 0.001368 |
def addSource(self,
path,
name,
location,
copyLib=False,
copyGroups=False,
copyInfo=False,
copyFeatures=False,
muteKerning=False,
muteInfo=False,
mutedGlyphNames=None,
familyName=None,
... | 0.006389 |
def verify(self):
"""
Verifies that the request timestamp is not beyond our allowable
timestamp mismatch and that the request signature matches our
expectations.
"""
try:
if self.timestamp_mismatch is not None:
m = _iso8601_timestamp_regex.matc... | 0.001585 |
def create_layer_2_socket():
"""create_layer_2_socket"""
# create a socket for recording layer 2, 3 and 4 frames
s = None
try:
log.info("Creating l234 socket")
s = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.ntohs(0x0003))
... | 0.002212 |
def format_from_extension(fname):
""" Tries to infer a protocol from the file extension."""
_base, ext = os.path.splitext(fname)
if not ext:
return None
try:
format = known_extensions[ext.replace('.', '')]
except KeyError:
format = None
return format | 0.003356 |
def add_member(self, login):
"""Add ``login`` to this team.
:returns: bool
"""
warnings.warn(
'This is no longer supported by the GitHub API, see '
'https://developer.github.com/changes/2014-09-23-one-more-week'
'-before-the-add-team-member-api-breaki... | 0.004107 |
def update_parent_directory_number(self, parent_dir_num):
# type: (int) -> None
'''
A method to update the parent directory number for this Path Table
Record from the directory record.
Parameters:
parent_dir_num - The new parent directory number to assign to this PTR.
... | 0.009141 |
def getParameter(self, name, index=-1):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
"""
if name == "patternCount":
return self._knn._numPatterns
elif name == "patternMatrix":
return self._getPatternMatrix()
elif name == "k":
return self._knn.k
... | 0.014637 |
def river_erosion(self, river, world):
""" Simulate erosion in heightmap based on river path.
* current location must be equal to or less than previous location
* riverbed is carved out by % of volume/flow
* sides of river are also eroded to slope into riverbed.
"""
... | 0.001871 |
def client_list_entries(client, to_delete): # pylint: disable=unused-argument
"""List entries via client."""
# [START client_list_entries_default]
for entry in client.list_entries(): # API call(s)
do_something_with(entry)
# [END client_list_entries_default]
# [START client_list_entries_f... | 0.000947 |
def set_access_credentials(self, _retry=0):
"""
Set the token on the Reddit Object again
"""
if _retry >= 5:
raise ConnectionAbortedError('Reddit is not accessible right now, cannot refresh OAuth2 tokens.')
self._check_token_present()
try:
self.r.set_access_credentials(self._get_value(CONFIGKEY_SCOP... | 0.032832 |
def get_submit_args(args):
"""Gets arguments for the `submit_and_verify` method."""
submit_args = dict(
testrun_id=args.testrun_id,
user=args.user,
password=args.password,
no_verify=args.no_verify,
verify_timeout=args.verify_timeout,
log_file=args.job_log,
... | 0.002062 |
def send_up(self, count):
"""
Sends the given number of up key presses.
"""
for i in range(count):
self.interface.send_key(Key.UP) | 0.016484 |
def get_auth_from_url(url):
"""Given a url with authentication components, extract them into a tuple of
username,password.
:rtype: (str,str)
"""
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth ... | 0.002882 |
def save_grid_data(self):
"""
Save grid data in the data object
"""
if not self.grid.changes:
print('-I- No changes to save')
return
if self.grid_type == 'age':
age_data_type = self.er_magic.age_type
self.er_magic.write_ages = True... | 0.005323 |
def save(self, filename, format='auto'):
"""
Save the SGraph to disk. If the graph is saved in binary format, the
graph can be re-loaded using the :py:func:`load_sgraph` method.
Alternatively, the SGraph can be saved in JSON format for a
human-readable and portable representation... | 0.00122 |
def can_edit(self, user=None, request=None):
"""
Define if a user can edit or not the instance, according to his account
or the request.
"""
can = False
if request and not self.owner:
if (getattr(settings, "UMAP_ALLOW_ANONYMOUS", False)
and... | 0.00292 |
def _delete_fw(self, tenant_id, data):
"""Internal routine called when a FW is deleted. """
LOG.debug("In Delete fw data is %s", data)
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, o... | 0.00152 |
def showHostDivision(self, headless):
"""Show the worker distribution over the hosts."""
scoop.logger.info('Worker d--istribution: ')
for worker, number in self.worker_hosts:
first_worker = (worker == self.worker_hosts[0][0])
scoop.logger.info(' {0}:\t{1} {2}'.format(
... | 0.003914 |
def p_class_constant(p):
'''class_constant : class_name DOUBLE_COLON STRING
| variable_class_name DOUBLE_COLON STRING'''
p[0] = ast.StaticProperty(p[1], p[3], lineno=p.lineno(2)) | 0.004808 |
def jsonget(self, name, *args):
"""
Get the object stored as a JSON value at key ``name``
``args`` is zero or more paths, and defaults to root path
"""
pieces = [name]
if len(args) == 0:
pieces.append(Path.rootPath())
else:
for p in args:
... | 0.004808 |
def dump(self, human=False):
"""将自身内容打印成字符串
:param bool human: 若值为 True ,则打印成易读格式。
"""
txt = str(self)
if human:
txt = txt.replace(", '", ",\n'")
txt = txt.replace("{", "{\n")
txt = txt.replace("}", "\n}")
txt = txt.replace("[", "... | 0.005181 |
def ParseSMS(self, parser_mediator, query, row, **unused_kwargs):
"""Parses an SMS.
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 resultin... | 0.005112 |
def add_nodes(self, node_name_list, dataframe=False):
"""
Add new nodes to the network
:param node_name_list: list of node names, e.g. ['a', 'b', 'c']
:param dataframe: If True, return a pandas dataframe instead of a dict.
:return: A dict mapping names to SUIDs for the newly-cre... | 0.004525 |
def has_permission(
permission,
context=None,
):
"""Decorator that restricts access only for authorized users
with correct permissions.
If user is not authorized - raises HTTPUnauthorized,
if user is authorized and does not have permission -
raises HTTPForbidden.
"""
def wrapper(fn)... | 0.001013 |
def already_downloaded(filename):
"""
Verify that the file has not already been downloaded.
"""
cur_file = os.path.join(c.bview_dir, filename)
old_file = os.path.join(c.bview_dir, 'old', filename)
if not os.path.exists(cur_file) and not os.path.exists(old_file):
return False
retu... | 0.003058 |
def expr_match(line, expr):
'''
Checks whether or not the passed value matches the specified expression.
Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries
to match expr as a regular expression. Originally designed to match minion
IDs for whitelists/blacklists.
Note tha... | 0.001129 |
def start(self, n):
"""Start engines by profile or profile_dir.
`n` is ignored, and the `engines` config property is used instead.
"""
dlist = []
for host, n in self.engines.iteritems():
if isinstance(n, (tuple, list)):
n, args = n
else:
... | 0.008876 |
def initialize_check_thread(self, check_func):
# type: (_MultiprocessOffload, function) -> None
"""Initialize the multiprocess done queue check thread
:param Downloader self: this
:param function check_func: check function
"""
self._check_thread = threading.Thread(target=... | 0.008197 |
def get_gae_labels(self):
"""Return the labels for GAE app.
If the trace ID can be detected, it will be included as a label.
Currently, no other labels are included.
:rtype: dict
:returns: Labels for GAE app.
"""
gae_labels = {}
trace_id = get_trace_id(... | 0.00463 |
def download_wiki():
"""Download WikiPedia pages of ambiguous units."""
ambiguous = [i for i in l.UNITS.items() if len(i[1]) > 1]
ambiguous += [i for i in l.DERIVED_ENT.items() if len(i[1]) > 1]
pages = set([(j.name, j.uri) for i in ambiguous for j in i[1]])
print
objs = []
for num, page in... | 0.001136 |
def date2juldate(val):
'''Convert from a python date/datetime to a Julian date & time'''
f = 12*val.year + val.month - 22803
fq = f // 12
fr = f % 12
dt = (fr*153 + 302)//5 + val.day + fq*1461//4
if isinstance(val, datetime):
return dt + (val.hour + (val.minute + (
val.second... | 0.002564 |
def get_exchange(connection, name, create=False):
"""
Get a Kombu Exchange object using the passed in name.
Can create an Exchange but this is typically not wanted in production-like
environments and only useful for testing.
"""
exchange = Exchange(name, type="topic", passive=not create)
#... | 0.00165 |
def get_trend_graph_url(start, end):
""" Total trend graph for machine category. """
filename = get_trend_graph_filename(start, end)
urls = {
'graph_url': urlparse.urljoin(GRAPH_URL, filename + ".png"),
'data_url': urlparse.urljoin(GRAPH_URL, filename + ".csv"),
}
return urls | 0.003185 |
def get_users(self, full_name=None, email=None, username=None):
"""
Send GET request to /users for users with optional full_name, email, and/or username filtering.
:param full_name: str name of the user we are searching for
:param email: str: optional email to filter by
:param us... | 0.004292 |
def get_default_config(self):
"""
Returns default collector settings.
"""
config = super(UPSCollector, self).get_default_config()
config.update({
'path': 'ups',
'ups_name': 'cyberpower',
'bin': '/bin/upsc',
... | 0.004577 |
def clear(self):
"Remove all rows and reset internal structures"
## list has no clear ... remove items in reverse order
for i in range(len(self)-1, -1, -1):
del self[i]
self._key = 0
if hasattr(self._grid_view, "wx_obj"):
self._grid_view.wx_obj.Clea... | 0.009174 |
def macro_def(self, macro_ref, frame):
"""Dump the macro definition for the def created by macro_body."""
arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args)
name = getattr(macro_ref.node, 'name', None)
if len(macro_ref.node.args) == 1:
arg_tuple += ','
s... | 0.003497 |
def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]],
gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]:
"""
Takes a predicted answer and a gold answer (that are both either a string or a list of
strings), and returns exact match and the DROP F1 metric for the... | 0.007617 |
def tune(self):
"""XML node representing tune."""
if self._node.get('activities'):
tune = self._node['activities'].get('tune')
if type(tune) is collections.OrderedDict:
return tune
elif type(tune) is list:
return tune[0]
ret... | 0.005747 |
def next(self, match, predicate=None, index=None):
"""
Retrieves the nearest next matches.
:param match:
:type match:
:param predicate:
:type predicate:
:param index:
:type index: int
:return:
:rtype:
"""
current = match.sta... | 0.0033 |
def bundlestate_to_str(state):
"""
Converts a bundle state integer to a string
"""
states = {
pelix.Bundle.INSTALLED: "INSTALLED",
pelix.Bundle.ACTIVE: "ACTIVE",
pelix.Bundle.RESOLVED: "RESOLVED",
pelix.Bundle.STARTING: "STARTING",
... | 0.004065 |
def create_reserved_ip_address(self, name, label=None, location=None):
'''
Reserves an IPv4 address for the specified subscription.
name:
Required. Specifies the name for the reserved IP address.
label:
Optional. Specifies a label for the reserved IP address. The... | 0.002033 |
def _create_regex(self, line, intent_name):
""" Create regex and return. If error occurs returns None. """
try:
return re.compile(self._create_intent_pattern(line, intent_name),
re.IGNORECASE)
except sre_constants.error as e:
LOG.warning('Fai... | 0.00463 |
def invcdf(x):
"""Inverse of normal cumulative density function."""
x_flat = np.ravel(x)
x_trans = np.array([flib.ppnd16(y, 1) for y in x_flat])
return np.reshape(x_trans, np.shape(x)) | 0.005 |
def domain(self, default):
"""
Get the domain for this pipeline.
- If an explicit domain was provided at construction time, use it.
- Otherwise, infer a domain from the registered columns.
- If no domain can be inferred, return ``default``.
Parameters
----------... | 0.001211 |
def is_archive_file(name):
# type: (str) -> bool
"""Return True if `name` is a considered as an archive file."""
ext = splitext(name)[1].lower()
if ext in ARCHIVE_EXTENSIONS:
return True
return False | 0.004405 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.