_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q242000 | Versioned.get_remote | train | def get_remote(self, remote='origin'):
"""Get a git remote object for this instance."""
repo = self.get_repo()
if repo is not None:
remotes = {r.name: r for r in repo.remotes}
r = repo.remotes[0] if remote not in remotes else remotes[remote]
else:
r = ... | python | {
"resource": ""
} |
q242001 | Versioned.get_remote_url | train | def get_remote_url(self, remote='origin', cached=True):
"""Get a git remote URL for this instance."""
if hasattr(self.__class__, '_remote_url') and cached:
url = self.__class__._remote_url
else:
r = self.get_remote(remote)
try:
url = list(r.url... | python | {
"resource": ""
} |
q242002 | ObservationValidator._validate_iterable | train | def _validate_iterable(self, is_iterable, key, value):
"""Validate fields with `iterable` key in schema set to True"""
if is_iterable:
try:
iter(value)
except TypeError:
self._error(key, "Must be iterable (e.g. a list or array)") | python | {
"resource": ""
} |
q242003 | ObservationValidator._validate_units | train | def _validate_units(self, has_units, key, value):
"""Validate fields with `units` key in schema set to True.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if has_units:
if isinstance(self.test.units, dict):
required_u... | python | {
"resource": ""
} |
q242004 | ParametersValidator.validate_quantity | train | def validate_quantity(self, value):
"""Validate that the value is of the `Quantity` type."""
if not isinstance(value, pq.quantity.Quantity):
self._error('%s' % value, "Must be a Python quantity.") | python | {
"resource": ""
} |
q242005 | ZScore.compute | train | def compute(cls, observation, prediction):
"""Compute a z-score from an observation and a prediction."""
assert isinstance(observation, dict)
try:
p_value = prediction['mean'] # Use the prediction's mean.
except (TypeError, KeyError, IndexError): # If there isn't one...
... | python | {
"resource": ""
} |
q242006 | ZScore.norm_score | train | def norm_score(self):
"""Return the normalized score.
Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive
or negative values.
"""
cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0
return 1 - 2*math.fabs(0.5 - cdf) | python | {
"resource": ""
} |
q242007 | CohenDScore.compute | train | def compute(cls, observation, prediction):
"""Compute a Cohen's D from an observation and a prediction."""
assert isinstance(observation, dict)
assert isinstance(prediction, dict)
p_mean = prediction['mean'] # Use the prediction's mean.
p_std = prediction['std']
o_mean =... | python | {
"resource": ""
} |
q242008 | RatioScore.compute | train | def compute(cls, observation, prediction, key=None):
"""Compute a ratio from an observation and a prediction."""
assert isinstance(observation, (dict, float, int, pq.Quantity))
assert isinstance(prediction, (dict, float, int, pq.Quantity))
obs, pred = cls.extract_means_or_values(observa... | python | {
"resource": ""
} |
q242009 | FloatScore.compute_ssd | train | def compute_ssd(cls, observation, prediction):
"""Compute sum-squared diff between observation and prediction."""
# The sum of the squared differences.
value = ((observation - prediction)**2).sum()
score = FloatScore(value)
return score | python | {
"resource": ""
} |
q242010 | read_requirements | train | def read_requirements():
'''parses requirements from requirements.txt'''
reqs_path = os.path.join('.', 'requirements.txt')
install_reqs = parse_requirements(reqs_path, session=PipSession())
reqs = [str(ir.req) for ir in install_reqs]
return reqs | python | {
"resource": ""
} |
q242011 | register_backends | train | def register_backends(vars):
"""Register backends for use with models.
`vars` should be a dictionary of variables obtained from e.g. `locals()`,
at least some of which are Backend classes, e.g. from imports.
"""
new_backends = {x.replace('Backend', ''): cls
for x, cls in vars.it... | python | {
"resource": ""
} |
q242012 | Backend.init_backend | train | def init_backend(self, *args, **kwargs):
"""Initialize the backend."""
self.model.attrs = {}
self.use_memory_cache = kwargs.get('use_memory_cache', True)
if self.use_memory_cache:
self.init_memory_cache()
self.use_disk_cache = kwargs.get('use_disk_cache', False)
... | python | {
"resource": ""
} |
q242013 | Backend.init_disk_cache | train | def init_disk_cache(self):
"""Initialize the on-disk version of the cache."""
try:
# Cleanup old disk cache files
path = self.disk_cache_location
os.remove(path)
except Exception:
pass
self.disk_cache_location = os.path.join(tempfile.mkdtem... | python | {
"resource": ""
} |
q242014 | Backend.get_memory_cache | train | def get_memory_cache(self, key=None):
"""Return result in memory cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
self._results = self.memory_cache.get(key)
return self._results | python | {
"resource": ""
} |
q242015 | Backend.get_disk_cache | train | def get_disk_cache(self, key=None):
"""Return result in disk cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location... | python | {
"resource": ""
} |
q242016 | Backend.set_memory_cache | train | def set_memory_cache(self, results, key=None):
"""Store result in memory cache with key matching model state."""
key = self.model.hash if key is None else key
self.memory_cache[key] = results | python | {
"resource": ""
} |
q242017 | Backend.set_disk_cache | train | def set_disk_cache(self, results, key=None):
"""Store result in disk cache with key matching model state."""
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location)
key = self.model.hash if key is None else... | python | {
"resource": ""
} |
q242018 | Backend.backend_run | train | def backend_run(self):
"""Check for cached results; then run the model if needed."""
key = self.model.hash
if self.use_memory_cache and self.get_memory_cache(key):
return self._results
if self.use_disk_cache and self.get_disk_cache(key):
return self._results
... | python | {
"resource": ""
} |
q242019 | Backend.save_results | train | def save_results(self, path='.'):
"""Save results on disk."""
with open(path, 'wb') as f:
pickle.dump(self.results, f) | python | {
"resource": ""
} |
q242020 | Capability.check | train | def check(cls, model, require_extra=False):
"""Check whether the provided model has this capability.
By default, uses isinstance. If `require_extra`, also requires that an
instance check be present in `model.extra_capability_checks`.
"""
class_capable = isinstance(model, cls)
... | python | {
"resource": ""
} |
q242021 | RunnableModel.set_backend | train | def set_backend(self, backend):
"""Set the simulation backend."""
if isinstance(backend, str):
name = backend
args = []
kwargs = {}
elif isinstance(backend, (tuple, list)):
name = ''
args = []
kwargs = {}
for i i... | python | {
"resource": ""
} |
q242022 | Score.color | train | def color(self, value=None):
"""Turn the score intp an RGB color tuple of three 8-bit integers."""
if value is None:
value = self.norm_score
rgb = Score.value_color(value)
return rgb | python | {
"resource": ""
} |
q242023 | Score.extract_means_or_values | train | def extract_means_or_values(cls, observation, prediction, key=None):
"""Extracts the mean, value, or user-provided key from the observation
and prediction dictionaries.
"""
obs_mv = cls.extract_mean_or_value(observation, key)
pred_mv = cls.extract_mean_or_value(prediction, key)
... | python | {
"resource": ""
} |
q242024 | Score.extract_mean_or_value | train | def extract_mean_or_value(cls, obs_or_pred, key=None):
"""Extracts the mean, value, or user-provided key from an observation
or prediction dictionary.
"""
result = None
if not isinstance(obs_or_pred, dict):
result = obs_or_pred
else:
keys = ([key]... | python | {
"resource": ""
} |
q242025 | ErrorScore.summary | train | def summary(self):
"""Summarize the performance of a model on a test."""
return "== Model %s did not complete test %s due to error '%s'. ==" %\
(str(self.model), str(self.test), str(self.score)) | python | {
"resource": ""
} |
q242026 | ImageCanvas.load | train | def load(self, draw_bbox = False, **kwargs):
''' Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts '''
im = Image.new('RGBA', self.img_size)
draw = None
if draw_bbox:
... | python | {
"resource": ""
} |
q242027 | match_window | train | def match_window(in_data, offset):
'''Find the longest match for the string starting at offset in the preceeding data
'''
window_start = max(offset - WINDOW_MASK, 0)
for n in range(MAX_LEN, THRESHOLD-1, -1):
window_end = min(offset + n, len(in_data))
# we've not got enough data left for... | python | {
"resource": ""
} |
q242028 | _merge_args_opts | train | def _merge_args_opts(args_opts_dict, **kwargs):
"""Merge options with their corresponding arguments.
Iterates over the dictionary holding arguments (keys) and options (values). Merges each
options string with its corresponding argument.
:param dict args_opts_dict: a dictionary of arguments and options... | python | {
"resource": ""
} |
q242029 | FFmpeg.run | train | def run(self, input_data=None, stdout=None, stderr=None):
"""Execute FFmpeg command line.
``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input.
``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the
process. By default... | python | {
"resource": ""
} |
q242030 | _get_usage | train | def _get_usage(ctx):
"""Alternative, non-prefixed version of 'get_usage'."""
formatter = ctx.make_formatter()
pieces = ctx.command.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='')
return formatter.getvalue().rstrip('\n') | python | {
"resource": ""
} |
q242031 | _get_help_record | train | def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-... | python | {
"resource": ""
} |
q242032 | _format_description | train | def _format_description(ctx):
"""Format the description for a given `click.Command`.
We parse this as reStructuredText, allowing users to embed rich
information in their help messages if they so choose.
"""
help_string = ctx.command.help or ctx.command.short_help
if not help_string:
ret... | python | {
"resource": ""
} |
q242033 | _format_option | train | def _format_option(opt):
"""Format the output for a `click.Option`."""
opt = _get_help_record(opt)
yield '.. option:: {}'.format(opt[0])
if opt[1]:
yield ''
for line in statemachine.string2lines(
opt[1], tab_width=4, convert_whitespace=True):
yield _indent(li... | python | {
"resource": ""
} |
q242034 | _format_options | train | def _format_options(ctx):
"""Format all `click.Option` for a `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
params = [
x for x in ctx.command.params
if isinstance(x, click.Option) and not getattr(x, 'hidden', False)
]
for param in params:
... | python | {
"resource": ""
} |
q242035 | _format_argument | train | def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format(
'Required' if arg.required else 'Optional',
'(s)' if arg.nargs != 1 else '')) | python | {
"resource": ""
} |
q242036 | _format_arguments | train | def _format_arguments(ctx):
"""Format all `click.Argument` for a `click.Command`."""
params = [x for x in ctx.command.params if isinstance(x, click.Argument)]
for param in params:
for line in _format_argument(param):
yield line
yield '' | python | {
"resource": ""
} |
q242037 | _format_envvar | train | def _format_envvar(param):
"""Format the envvars of a `click.Option` or `click.Argument`."""
yield '.. envvar:: {}'.format(param.envvar)
yield ' :noindex:'
yield ''
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
# if a user has defined an opt ... | python | {
"resource": ""
} |
q242038 | _format_envvars | train | def _format_envvars(ctx):
"""Format all envvars for a `click.Command`."""
params = [x for x in ctx.command.params if getattr(x, 'envvar')]
for param in params:
yield '.. _{command_name}-{param_name}-{envvar}:'.format(
command_name=ctx.command_path.replace(' ', '-'),
param_na... | python | {
"resource": ""
} |
q242039 | _format_subcommand | train | def _format_subcommand(command):
"""Format a sub-command of a `click.Command` or `click.Group`."""
yield '.. object:: {}'.format(command.name)
# click 7.0 stopped setting short_help by default
if CLICK_VERSION < (7, 0):
short_help = command.short_help
else:
short_help = command.get_... | python | {
"resource": ""
} |
q242040 | _filter_commands | train | def _filter_commands(ctx, commands=None):
"""Return list of used commands."""
lookup = getattr(ctx.command, 'commands', {})
if not lookup and isinstance(ctx.command, click.MultiCommand):
lookup = _get_lazyload_commands(ctx.command)
if commands is None:
return sorted(lookup.values(), key... | python | {
"resource": ""
} |
q242041 | _format_command | train | def _format_command(ctx, show_nested, commands=None):
"""Format the output of `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
if getattr(ctx.command, 'hidden', False):
return
# description
for line in _format_description(ctx):
yield line
... | python | {
"resource": ""
} |
q242042 | ClickDirective._load_module | train | def _load_module(self, module_path):
"""Load the module."""
# __import__ will fail on unicode,
# so we ensure module path is a string here.
module_path = str(module_path)
try:
module_name, attr_name = module_path.split(':', 1)
except ValueError: # noqa
... | python | {
"resource": ""
} |
q242043 | DataCursor._show_annotation_box | train | def _show_annotation_box(self, event):
"""Update an existing box or create an annotation box for an event."""
ax = event.artist.axes
# Get the pre-created annotation box for the axes or create a new one.
if self.display != 'multiple':
annotation = self.annotations[ax]
... | python | {
"resource": ""
} |
q242044 | DataCursor.event_info | train | def event_info(self, event):
"""Get a dict of info for the artist selected by "event"."""
def default_func(event):
return {}
registry = {
AxesImage : [pick_info.image_props],
PathCollection : [pick_info.scatter_props, self._contour_info,
... | python | {
"resource": ""
} |
q242045 | DataCursor._formatter | train | def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs):
"""
Default formatter function, if no `formatter` kwarg is specified. Takes
information about the pick event as a series of kwargs and returns the
string to be displayed.
"""
def is_date(axis):
... | python | {
"resource": ""
} |
q242046 | DataCursor._format_coord | train | def _format_coord(self, x, limits):
"""
Handles display-range-specific formatting for the x and y coords.
Parameters
----------
x : number
The number to be formatted
limits : 2-item sequence
The min and max of the current display limits for the ax... | python | {
"resource": ""
} |
q242047 | DataCursor._hide_box | train | def _hide_box(self, annotation):
"""Remove a specific annotation box."""
annotation.set_visible(False)
if self.display == 'multiple':
annotation.axes.figure.texts.remove(annotation)
# Remove the annotation from self.annotations.
lookup = dict((self.annotation... | python | {
"resource": ""
} |
q242048 | DataCursor.enable | train | def enable(self):
"""Connects callbacks and makes artists pickable. If the datacursor has
already been enabled, this function has no effect."""
def connect(fig):
if self.hover:
event = 'motion_notify_event'
else:
event = 'button_press_event... | python | {
"resource": ""
} |
q242049 | DataCursor._increment_index | train | def _increment_index(self, di=1):
"""
Move the most recently displayed annotation to the next item in the
series, if possible. If ``di`` is -1, move it to the previous item.
"""
if self._last_event is None:
return
if not hasattr(self._last_event, 'ind'):
... | python | {
"resource": ""
} |
q242050 | HighlightingDataCursor.show_highlight | train | def show_highlight(self, artist):
"""Show or create a highlight for a givent artist."""
# This is a separate method to make subclassing easier.
if artist in self.highlights:
self.highlights[artist].set_visible(True)
else:
self.highlights[artist] = self.create_high... | python | {
"resource": ""
} |
q242051 | HighlightingDataCursor.create_highlight | train | def create_highlight(self, artist):
"""Create a new highlight for the given artist."""
highlight = copy.copy(artist)
highlight.set(color=self.highlight_color, mec=self.highlight_color,
lw=self.highlight_width, mew=self.highlight_width)
artist.axes.add_artist(highlig... | python | {
"resource": ""
} |
q242052 | _coords2index | train | def _coords2index(im, x, y, inverted=False):
"""
Converts data coordinates to index coordinates of the array.
Parameters
-----------
im : An AxesImage instance
The image artist to operation on
x : number
The x-coordinate in data coordinates.
y : number
The y-coordina... | python | {
"resource": ""
} |
q242053 | _interleave | train | def _interleave(a, b):
"""Interleave arrays a and b; b may have multiple columns and must be
shorter by 1.
"""
b = np.column_stack([b]) # Turn b into a column array.
nx, ny = b.shape
c = np.zeros((nx + 1, ny + 1))
c[:, 0] = a
c[:-1, 1:] = b
return c.ravel()[:-(c.shape[1] - 1)] | python | {
"resource": ""
} |
q242054 | three_dim_props | train | def three_dim_props(event):
"""
Get information for a pick event on a 3D artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`x`: The estimated x-value of the click on the artist
`y`: The estimated y-valu... | python | {
"resource": ""
} |
q242055 | rectangle_props | train | def rectangle_props(event):
"""
Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
`height` : The height of... | python | {
"resource": ""
} |
q242056 | get_xy | train | def get_xy(artist):
"""
Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections.
"""
xy = None
if hasattr(artist, 'get_offsets'):
xy = artist.get_offsets().T
el... | python | {
"resource": ""
} |
q242057 | datacursor | train | def datacursor(artists=None, axes=None, **kwargs):
"""
Create an interactive data cursor for the specified artists or specified
axes. The data cursor displays information about a selected artist in a
"popup" annotation box.
If a specific sequence of artists is given, only the specified artists will... | python | {
"resource": ""
} |
q242058 | wrap_exception | train | def wrap_exception(func: Callable) -> Callable:
"""Decorator to wrap pygatt exceptions into BluetoothBackendException."""
try:
# only do the wrapping if pygatt is installed.
# otherwise it's pointless anyway
from pygatt.backends.bgapi.exceptions import BGAPIError
from pygatt.exce... | python | {
"resource": ""
} |
q242059 | PygattBackend.write_handle | train | def write_handle(self, handle: int, value: bytes):
"""Write a handle to the device."""
if not self.is_connected():
raise BluetoothBackendException('Not connected to device!')
self._device.char_write_handle(handle, value, True)
return True | python | {
"resource": ""
} |
q242060 | wrap_exception | train | def wrap_exception(func: Callable) -> Callable:
"""Decorator to wrap BTLEExceptions into BluetoothBackendException."""
try:
# only do the wrapping if bluepy is installed.
# otherwise it's pointless anyway
from bluepy.btle import BTLEException
except ImportError:
return func
... | python | {
"resource": ""
} |
q242061 | BluepyBackend.write_handle | train | def write_handle(self, handle: int, value: bytes):
"""Write a handle from the device.
You must be connected to do this.
"""
if self._peripheral is None:
raise BluetoothBackendException('not connected to backend')
return self._peripheral.writeCharacteristic(handle, va... | python | {
"resource": ""
} |
q242062 | BluepyBackend.check_backend | train | def check_backend() -> bool:
"""Check if the backend is available."""
try:
import bluepy.btle # noqa: F401 #pylint: disable=unused-import
return True
except ImportError as importerror:
_LOGGER.error('bluepy not found: %s', str(importerror))
return Fal... | python | {
"resource": ""
} |
q242063 | BluepyBackend.scan_for_devices | train | def scan_for_devices(timeout: float) -> List[Tuple[str, str]]:
"""Scan for bluetooth low energy devices.
Note this must be run as root!"""
from bluepy.btle import Scanner
scanner = Scanner()
result = []
for device in scanner.scan(timeout):
result.append((dev... | python | {
"resource": ""
} |
q242064 | wrap_exception | train | def wrap_exception(func: Callable) -> Callable:
"""Wrap all IOErrors to BluetoothBackendException"""
def _func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except IOError as exception:
raise BluetoothBackendException() from exception
return _func_wrapp... | python | {
"resource": ""
} |
q242065 | GatttoolBackend.write_handle | train | def write_handle(self, handle: int, value: bytes):
# noqa: C901
# pylint: disable=arguments-differ
"""Read from a BLE address.
@param: mac - MAC address in format XX:XX:XX:XX:XX:XX
@param: handle - BLE characteristics handle in format 0xXX
@param: value - value to write... | python | {
"resource": ""
} |
q242066 | GatttoolBackend.wait_for_notification | train | def wait_for_notification(self, handle: int, delegate, notification_timeout: float):
"""Listen for characteristics changes from a BLE address.
@param: mac - MAC address in format XX:XX:XX:XX:XX:XX
@param: handle - BLE characteristics handle in format 0xXX
a value of 0x0... | python | {
"resource": ""
} |
q242067 | GatttoolBackend.check_backend | train | def check_backend() -> bool:
"""Check if gatttool is available on the system."""
try:
call('gatttool', stdout=PIPE, stderr=PIPE)
return True
except OSError as os_err:
msg = 'gatttool not found: {}'.format(str(os_err))
_LOGGER.error(msg)
ret... | python | {
"resource": ""
} |
q242068 | GatttoolBackend.bytes_to_string | train | def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str:
"""Convert a byte array to a hex string."""
prefix_string = ''
if prefix:
prefix_string = '0x'
suffix = ''.join([format(c, "02x") for c in raw_data])
return prefix_string + suffix.upper() | python | {
"resource": ""
} |
q242069 | decode_ast | train | def decode_ast(registry, ast_json):
"""JSON decoder for BaseNodes"""
if ast_json.get("@type"):
subclass = registry.get_cls(ast_json["@type"], tuple(ast_json["@fields"]))
return subclass(
ast_json["children"],
ast_json["field_references"],
ast_json["label_refer... | python | {
"resource": ""
} |
q242070 | simplify_tree | train | def simplify_tree(tree, unpack_lists=True, in_list=False):
"""Recursively unpack single-item lists and objects where fields and labels only reference a single child
:param tree: the tree to simplify (mutating!)
:param unpack_lists: whether single-item lists should be replaced by that item
:param in_lis... | python | {
"resource": ""
} |
q242071 | get_field | train | def get_field(ctx, field):
"""Helper to get the value of a field"""
# field can be a string or a node attribute
if isinstance(field, str):
field = getattr(ctx, field, None)
# when not alias needs to be called
if callable(field):
field = field()
# when alias set on token, need to ... | python | {
"resource": ""
} |
q242072 | get_field_names | train | def get_field_names(ctx):
"""Get fields defined in an ANTLR context for a parser rule"""
# this does not include labels and literals, only rule names and token names
# TODO: check ANTLR parser template for full exclusion list
fields = [
field
for field in type(ctx).__dict__
if no... | python | {
"resource": ""
} |
q242073 | get_label_names | train | def get_label_names(ctx):
"""Get labels defined in an ANTLR context for a parser rule"""
labels = [
label
for label in ctx.__dict__
if not label.startswith("_")
and label
not in [
"children",
"exception",
"invokingState",
"p... | python | {
"resource": ""
} |
q242074 | Speaker.get_info | train | def get_info(node_cfg):
"""Return a tuple with the verbal name of a node, and a dict of field names."""
node_cfg = node_cfg if isinstance(node_cfg, dict) else {"name": node_cfg}
return node_cfg.get("name"), node_cfg.get("fields", {}) | python | {
"resource": ""
} |
q242075 | BaseNodeRegistry.isinstance | train | def isinstance(self, instance, class_name):
"""Check if a BaseNode is an instance of a registered dynamic class"""
if isinstance(instance, BaseNode):
klass = self.dynamic_node_classes.get(class_name, None)
if klass:
return isinstance(instance, klass)
#... | python | {
"resource": ""
} |
q242076 | AliasNode.get_transformer | train | def get_transformer(cls, method_name):
"""Get method to bind to visitor"""
transform_function = getattr(cls, method_name)
assert callable(transform_function)
def transformer_method(self, node):
kwargs = {}
if inspect.signature(transform_function).parameters.get("... | python | {
"resource": ""
} |
q242077 | BaseAstVisitor.visitTerminal | train | def visitTerminal(self, ctx):
"""Converts case insensitive keywords and identifiers to lowercase"""
text = ctx.getText()
return Terminal.from_text(text, ctx) | python | {
"resource": ""
} |
q242078 | Blacklist.run | train | def run(self, *args):
"""List, add or delete entries from the blacklist.
By default, it prints the list of entries available on
the blacklist.
"""
params = self.parser.parse_args(args)
entry = params.entry
if params.add:
code = self.add(entry)
... | python | {
"resource": ""
} |
q242079 | Blacklist.add | train | def add(self, entry):
"""Add entries to the blacklist.
This method adds the given 'entry' to the blacklist.
:param entry: entry to add to the blacklist
"""
# Empty or None values for organizations are not allowed
if not entry:
return CMD_SUCCESS
try... | python | {
"resource": ""
} |
q242080 | Blacklist.delete | train | def delete(self, entry):
"""Remove entries from the blacklist.
The method removes the given 'entry' from the blacklist.
:param entry: entry to remove from the blacklist
"""
if not entry:
return CMD_SUCCESS
try:
api.delete_from_matching_blacklist... | python | {
"resource": ""
} |
q242081 | Blacklist.blacklist | train | def blacklist(self, term=None):
"""List blacklisted entries.
When no term is given, the method will list the entries that
exist in the blacklist. If 'term' is set, the method will list
only those entries that match with that term.
:param term: term to match
"""
... | python | {
"resource": ""
} |
q242082 | Config.run | train | def run(self, *args):
"""Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
"""
params = self.parser.parse_args(args)
conf... | python | {
"resource": ""
} |
q242083 | Config.get | train | def get(self, key, filepath):
"""Get configuration parameter.
Reads 'key' configuration parameter from the configuration file given
in 'filepath'. Configuration parameter in 'key' must follow the schema
<section>.<option> .
:param key: key to get
:param filepath: config... | python | {
"resource": ""
} |
q242084 | Config.set | train | def set(self, key, value, filepath):
"""Set configuration parameter.
Writes 'value' on 'key' to the configuration file given in
'filepath'. Configuration parameter in 'key' must follow the schema
<section>.<option> .
:param key: key to set
:param value: value to set
... | python | {
"resource": ""
} |
q242085 | Config.__check_config_key | train | def __check_config_key(self, key):
"""Check whether the key is valid.
A valid key has the schema <section>.<option>. Keys supported
are listed in CONFIG_OPTIONS dict.
:param key: <section>.<option> key
"""
try:
section, option = key.split('.')
except... | python | {
"resource": ""
} |
q242086 | Export.run | train | def run(self, *args):
"""Export data from the registry.
By default, it writes the data to the standard output. If a
positional argument is given, it will write the data on that
file.
"""
params = self.parser.parse_args(args)
with params.outfile as outfile:
... | python | {
"resource": ""
} |
q242087 | Export.export_identities | train | def export_identities(self, outfile, source=None):
"""Export identities information to a file.
The method exports information related to unique identities, to
the given 'outfile' output file.
When 'source' parameter is given, only those unique identities which have
one or more ... | python | {
"resource": ""
} |
q242088 | Export.export_organizations | train | def export_organizations(self, outfile):
"""Export organizations information to a file.
The method exports information related to organizations, to
the given 'outfile' output file.
:param outfile: destination file object
"""
exporter = SortingHatOrganizationsExporter(se... | python | {
"resource": ""
} |
q242089 | SortingHatIdentitiesExporter.export | train | def export(self, source=None):
"""Export a set of unique identities.
Method to export unique identities from the registry. Identities schema
will follow Sorting Hat JSON format.
When source parameter is given, only those unique identities which have
one or more identities from ... | python | {
"resource": ""
} |
q242090 | SortingHatOrganizationsExporter.export | train | def export(self):
"""Export a set of organizations.
Method to export organizations from the registry. Organizations schema
will follow Sorting Hat JSON format.
:returns: a JSON formatted str
"""
organizations = {}
orgs = api.registry(self.db)
for org i... | python | {
"resource": ""
} |
q242091 | AutoProfile.run | train | def run(self, *args):
"""Autocomplete profile information."""
params = self.parser.parse_args(args)
sources = params.source
code = self.autocomplete(sources)
return code | python | {
"resource": ""
} |
q242092 | AutoProfile.autocomplete | train | def autocomplete(self, sources):
"""Autocomplete unique identities profiles.
Autocomplete unique identities profiles using the information
of their identities. The selection of the data used to fill
the profile is prioritized using a list of sources.
"""
email_pattern = ... | python | {
"resource": ""
} |
q242093 | AutoProfile.__select_autocomplete_identities | train | def __select_autocomplete_identities(self, sources):
"""Select the identities used for autocompleting"""
MIN_PRIORITY = 99999999
checked = {}
for source in sources:
uids = api.unique_identities(self.db, source=source)
for uid in uids:
if uid.uu... | python | {
"resource": ""
} |
q242094 | Show.run | train | def run(self, *args):
"""Show information about unique identities."""
params = self.parser.parse_args(args)
code = self.show(params.uuid, params.term)
return code | python | {
"resource": ""
} |
q242095 | Show.show | train | def show(self, uuid=None, term=None):
"""Show the information related to unique identities.
This method prints information related to unique identities such as
identities or enrollments.
When <uuid> is given, it will only show information about the unique
identity related to <u... | python | {
"resource": ""
} |
q242096 | StackalyticsParser.__parse_organizations | train | def __parse_organizations(self, json):
"""Parse Stackalytics organizations.
The Stackalytics organizations format is a JSON document stored under the
"companies" key. The next JSON shows the structure of the
document:
{
"companies" : [
{
... | python | {
"resource": ""
} |
q242097 | StackalyticsParser.__parse_identities | train | def __parse_identities(self, json):
"""Parse identities using Stackalytics format.
The Stackalytics identities format is a JSON document under the
"users" key. The document should follow the next schema:
{
"users": [
{
"launchpad_id": "0-... | python | {
"resource": ""
} |
q242098 | StackalyticsParser.__parse_enrollments | train | def __parse_enrollments(self, user):
"""Parse user enrollments"""
enrollments = []
for company in user['companies']:
name = company['company_name']
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
... | python | {
"resource": ""
} |
q242099 | StackalyticsParser.__load_json | train | def __load_json(self, stream):
"""Load json stream into a dict object """
import json
try:
return json.loads(stream)
except ValueError as e:
cause = "invalid json format. %s" % str(e)
raise InvalidFormatError(cause=cause) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.