code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def items(self):
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result | Return a list of items. |
def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque):
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype),
'nsuri': nsuri
}) | Domain metadata change events handler |
def _create_cache_filename(self, source_file):
res = self._create_cache_key(source_file) + ".cache"
return os.path.join(self.__dir, res) | return the cache file name for a header file.
:param source_file: Header file name
:type source_file: str
:rtype: str |
def get_list_subtask_positions_objs(client, list_id):
params = {
'list_id' : int(list_id)
}
response = client.authenticated_request(client.api.Endpoints.SUBTASK_POSITIONS, params=params)
return response.json() | Gets all subtask positions objects for the tasks within a given list. This is a convenience method so you don't have to get all the list's tasks before getting subtasks, though I can't fathom how mass subtask reordering is useful.
Returns:
List of SubtaskPositionsObj-mapped objects representing the order of su... |
def build(cls: Type[T], data: Generic) -> T:
fields = fields_dict(cls)
kwargs: Dict[str, Any] = {}
for key, value in data.items():
if key in fields:
if isinstance(value, Mapping):
t = fields[key].type
if issubclass(t, Auto):
... | Build objects from dictionaries, recursively. |
def castable(source, target):
op = source.op()
value = getattr(op, 'value', None)
return dt.castable(source.type(), target.type(), value=value) | Return whether source ir type is implicitly castable to target
Based on the underlying datatypes and the value in case of Literals |
def standard_program_header(self, title, length, line=32768):
self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length) | Generates a standard header block of PROGRAM type |
def stopService(self):
super(_SiteScheduler, self).stopService()
if self.timer is not None:
self.timer.cancel()
self.timer = None | Stop calling persistent timed events. |
def get_addresses_on_both_chains(wallet_obj, used=None, zero_balance=None):
mpub = wallet_obj.serialize_b58(private=False)
wallet_name = get_blockcypher_walletname_from_mpub(
mpub=mpub,
subchain_indices=[0, 1],
)
wallet_addresses = get_wallet_addresses(
wallet... | Get addresses across both subchains based on the filter criteria passed in
Returns a list of dicts of the following form:
[
{'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'},
...,
]
Dicts may also contain WIF and privkeyhex if wallet_obj has private ... |
def folder_size(pth, ignore=None):
if not os.path.isdir(pth):
raise exc.FolderNotFound
ignore = coerce_to_list(ignore)
total = 0
for root, _, names in os.walk(pth):
paths = [os.path.realpath(os.path.join(root, nm)) for nm in names]
for pth in paths[::-1]:
if not os.pa... | Returns the total bytes for the specified path, optionally ignoring
any files which match the 'ignore' parameter. 'ignore' can either be
a single string pattern, or a list of such patterns. |
def save(self, obj, run_id):
id_code = self.generate_save_identifier(obj, run_id)
self.store.save(obj, id_code) | Save a workflow
obj - instance of a workflow to save
run_id - unique id to give the run |
def _parse_mode(self, mode, allowed=None, single=False):
r
if type(mode) is str:
mode = [mode]
for item in mode:
if (allowed is not None) and (item not in allowed):
raise Exception('\'mode\' must be one of the following: ' +
... | r"""
This private method is for checking the \'mode\' used in the calling
method.
Parameters
----------
mode : string or list of strings
The mode(s) to be parsed
allowed : list of strings
A list containing the allowed modes. This list is defined... |
def merge_rects(rect1, rect2):
r = pygame.Rect(rect1)
t = pygame.Rect(rect2)
right = max(r.right, t.right)
bot = max(r.bottom, t.bottom)
x = min(t.x, r.x)
y = min(t.y, r.y)
return pygame.Rect(x, y, right - x, bot - y) | Return the smallest rect containning two rects |
def get_containers(self, include_only=[]):
locations = self.get_locations()
if len(locations) == 0:
raise ValueError("No locations for containers exist in Cheminventory")
final_locations = []
if include_only:
for location in locations:
check = loc... | Download all the containers owned by a group
Arguments
---------
include_only: List containg `Group` or `Location` objects
Search only over a list of groups or locations |
def _expand_logical_shortcuts(cls, schema):
def is_of_rule(x):
return isinstance(x, _str_type) and \
x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_'))
for field in schema:
for of_rule in (x for x in schema[field] if is_of_rule(x)):
operator, ... | Expand agglutinated rules in a definition-schema.
:param schema: The schema-definition to expand.
:return: The expanded schema-definition. |
def new_config_event(self):
try:
self.on_set_config()
except Exception as ex:
self.logger.exception(ex)
raise StopIteration() | Called by the event loop when new config is available. |
def get_occupied_slots(instance):
return [slot for slot in get_all_slots(type(instance))
if hasattr(instance,slot)] | Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.) |
def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[],
policies=[], dashboards=[], credentials=[], description=''):
return self.raw_query('group', 'add', data={
'lces': [{'id': i} for i in lces],
'assets': [{'id': i} for i in assets],
'qu... | group_add name, restrict, repos |
def inlink_file(self, filepath):
if not os.path.exists(filepath):
logger.debug("Creating symbolic link to not existent file %s" % filepath)
root, abiext = abi_splitext(filepath)
infile = "in_" + abiext
infile = self.indir.path_in(infile)
self.history.info("Linking pat... | Create a symbolic link to the specified file in the
directory containing the input files of the task. |
def filter(cls, filters, iterable):
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | Returns the elements in `iterable` that pass given `filters` |
def moveaxis(tensor, source, destination):
try:
source = np.core.numeric.normalize_axis_tuple(source, tensor.ndim)
except IndexError:
raise ValueError('Source should verify 0 <= source < tensor.ndim'
'Got %d' % source)
try:
destination = np.core.numeric.norma... | Moves the `source` axis into the `destination` position
while leaving the other axes in their original order
Parameters
----------
tensor : mx.nd.array
The array which axes should be reordered
source : int or sequence of int
Original position of the axes to move. Can be negative but... |
def primary_transcript(entrystream, parenttype='gene', logstream=stderr):
for entry in entrystream:
if not isinstance(entry, tag.Feature):
yield entry
continue
for parent in tag.select.features(entry, parenttype, traverse=True):
if parent.num_children == 0:
... | Select a single transcript as a representative for each gene.
This function is a generalization of the `primary_mrna` function that
attempts, under certain conditions, to select a single transcript as a
representative for each gene. If a gene encodes multiple transcript types,
one of those types must b... |
def make_geojson(contents):
if isinstance(contents, six.string_types):
return contents
if hasattr(contents, '__geo_interface__'):
features = [_geo_to_feature(contents)]
else:
try:
feature_iter = iter(contents)
except TypeError:
raise ValueError('Unknow... | Return a GeoJSON string from a variety of inputs.
See the documentation for make_url for the possible contents
input.
Returns
-------
GeoJSON string |
async def send(self, message_type, message_content, timeout=None):
return await self._sender.send(
message_type, message_content, timeout=timeout) | Sends a message and returns a future for the response. |
def missing_datetimes(self, finite_datetimes):
return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()] | Override in subclasses to do bulk checks.
Returns a sorted list.
This is a conservative base implementation that brutally checks completeness, instance by instance.
Inadvisable as it may be slow. |
def add_view_no_menu(self, baseview, endpoint=None, static_folder=None):
baseview = self._check_and_init(baseview)
log.info(LOGMSG_INF_FAB_ADD_VIEW.format(baseview.__class__.__name__, ""))
if not self._view_exists(baseview):
baseview.appbuilder = self
self.baseviews.appen... | Add your views without creating a menu.
:param baseview:
A BaseView type class instantiated. |
def winrm_cmd(session, command, flags, **kwargs):
log.debug('Executing WinRM command: %s %s', command, flags)
session.protocol.transport.build_session()
r = session.run_cmd(command, flags)
return r.status_code | Wrapper for commands to be run against Windows boxes using WinRM. |
def view_running_services(self, package: str='') -> str:
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'services', package)
return output | View running services. |
def one(self, filetype, **kwargs):
expanded_files = self.expand(filetype, **kwargs)
isany = self.any(filetype, **kwargs)
return choice(expanded_files) if isany else None | Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of files by
before random sel... |
def results(self):
self.out('cif', self.ctx.cif)
if 'group_cif' in self.inputs:
self.inputs.group_cif.add_nodes([self.ctx.cif])
if 'group_structure' in self.inputs:
try:
structure = self.ctx.structure
except AttributeError:
retu... | If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain.
The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif`
was defined in the inputs, the node is added to it. If the structure should have been pa... |
def convert_geojson_to_shapefile(geojson_path):
layer = QgsVectorLayer(geojson_path, 'vector layer', 'ogr')
if not layer.isValid():
return False
shapefile_path = os.path.splitext(geojson_path)[0] + '.shp'
QgsVectorFileWriter.writeAsVectorFormat(
layer,
shapefile_path,
'ut... | Convert geojson file to shapefile.
It will create a necessary file next to the geojson file. It will not
affect another files (e.g. .xml, .qml, etc).
:param geojson_path: The path to geojson file.
:type geojson_path: basestring
:returns: True if shapefile layer created, False otherwise.
:rtyp... |
def add_tab(self, tab, title='', icon=None):
if icon:
tab._icon = icon
if not hasattr(tab, 'clones'):
tab.clones = []
if not hasattr(tab, 'original'):
tab.original = None
if icon:
self.main_tab_widget.addTab(tab, icon, title)
else:
... | Adds a tab to main tab widget.
:param tab: Widget to add as a new tab of the main tab widget.
:param title: Tab title
:param icon: Tab icon |
def parse_source(info):
if "extractor_key" in info:
source = info["extractor_key"]
lower_source = source.lower()
for key in SOURCE_TO_NAME:
lower_key = key.lower()
if lower_source == lower_key:
source = SOURCE_TO_NAME[lower_key]
if source != "G... | Parses the source info from an info dict generated by youtube-dl
Args:
info (dict): The info dict to parse
Returns:
source (str): The source of this song |
def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None):
return DataReader(symbol, source, start=start, end=end) | Fetch from yahoo! finance historical quotes |
def _build_web_client(cls, session: AppSession):
cookie_jar = cls._build_cookie_jar(session)
http_client = cls._build_http_client(session)
redirect_factory = functools.partial(
session.factory.class_map['RedirectTracker'],
max_redirects=session.args.max_redirect
)... | Build Web Client. |
def expect_equal(first, second, msg=None, extras=None):
try:
asserts.assert_equal(first, second, msg, extras)
except signals.TestSignal as e:
logging.exception('Expected %s equals to %s, but they are not.', first,
second)
recorder.add_error(e) | Expects the equality of objects, otherwise fail the test.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.... |
def find_field(browser, field, value):
return find_field_by_id(browser, field, value) + \
find_field_by_name(browser, field, value) + \
find_field_by_label(browser, field, value) | Locate an input field of a given value
This first looks for the value as the id of the element, then
the name of the element, then a label for the element. |
def scipy_psd(x, f_sample=1.0, nr_segments=4):
f_axis, psd_of_x = scipy.signal.welch(x, f_sample, nperseg=len(x)/nr_segments)
return f_axis, psd_of_x | PSD routine from scipy
we can compare our own numpy result against this one |
def glob_config(pattern, *search_dirs):
patterns = config_search_paths(pattern, *search_dirs, check_exists=False)
for pattern in patterns:
for path in glob.iglob(pattern):
yield path | Return glob results for all possible configuration locations.
Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory.
This is done for performance since this is usually used to find *all* configs for a certain component. |
def show(self, msg, indent=0, style="", **kwargs):
if self.enable_verbose:
new_msg = self.MessageTemplate.with_style.format(
indent=self.tab * indent,
style=style,
msg=msg,
)
print(new_msg, **kwargs) | Print message to console, indent format may apply. |
def call(self, task, decorators=None):
if decorators is None:
decorators = []
task = self.apply_task_decorators(task, decorators)
data = task.get_data()
name = task.get_name()
result = self._inner_call(name, data)
task_result = RawTaskResult(task, result)
... | Call given task on service layer.
:param task: task to be called. task will be decorated with
TaskDecorator's contained in 'decorators' list
:type task: instance of Task class
:param decorators: list of TaskDecorator's / TaskResultDecorator's
inherited classes
:t... |
def warning(message, css_path=CSS_PATH):
env = Environment()
env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
warning = env.get_template("warning.html")
return warning.render(css_path=css_path, text=message) | Print a warning message on the rich text view |
def save(self, force=False):
if (not self._success) and (not force):
raise ConfigError((
'The config file appears to be corrupted:\n\n'
' {fname}\n\n'
'Before attempting to save the configuration, please either '
'fix the config file... | Saves the configuration to a JSON, in the standard config location.
Args:
force (Optional[:obj:`bool`]): Continue writing, even if the original
config file was not loaded properly. This is dangerous, because
it could cause the previous configuration options to be los... |
def set_categories(self):
self.categories = []
temp_categories = self.soup.findAll('category')
for category in temp_categories:
category_text = category.string
self.categories.append(category_text) | Parses and set feed categories |
def list_parameter_ranges(self, parameter, start=None, stop=None,
min_gap=None, max_gap=None,
parameter_cache='realtime'):
path = '/archive/{}/parameters{}/ranges'.format(
self._instance, parameter)
params = {}
if start is n... | Returns parameter ranges between the specified start and stop time.
Each range indicates an interval during which this parameter's
value was uninterrupted and unchanged.
Ranges are a good fit for retrieving the value of a parameter
that does not change frequently. For example an on/off... |
def could_collide_hor(self, vpos, adsb_pkt):
margin = self.asterix_settings.filter_dist_xy
timeout = self.asterix_settings.filter_time
alat = adsb_pkt.lat * 1.0e-7
alon = adsb_pkt.lon * 1.0e-7
avel = adsb_pkt.hor_velocity * 0.01
vvel = sqrt(vpos.vx**2 + vpos.vy**2)
... | return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds |
def sort(self,
key,
by=None,
external=None,
offset=0,
limit=None,
order=None,
alpha=False,
store_as=None):
if order and order not in [b'ASC', b'DESC', 'ASC', 'DESC']:
raise ValueError('invalid sor... | Returns or stores the elements contained in the list, set or sorted
set at key. By default, sorting is numeric and elements are compared by
their value interpreted as double precision floating point number.
The ``external`` parameter is used to specify the
`GET <http://redis.io/commands... |
def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args):
if present:
if not expected:
raise exc_unexpected(*exc_args)
elif expected and expected is not Argument.ignore:
raise exc_missing(*exc_args) | Checks for the presence of an extra to the argument list. Raises expections
if this is unexpected or if it is missing and expected. |
def is_selected(self, model):
if model is None:
return len(self._selected) == 0
return model in self._selected | Checks whether the given model is selected
:param model:
:return: True if the model is within the selection, False else
:rtype: bool |
def _locate_point(nodes, point):
r
candidates = [(0.0, 1.0, nodes)]
for _ in six.moves.xrange(_MAX_LOCATE_SUBDIVISIONS + 1):
next_candidates = []
for start, end, candidate in candidates:
if _helpers.contains_nd(candidate, point.ravel(order="F")):
midpoint = 0.5 * ... | r"""Locate a point on a curve.
Does so by recursively subdividing the curve and rejecting
sub-curves with bounding boxes that don't contain the point.
After the sub-curves are sufficiently small, uses Newton's
method to zoom in on the parameter value.
.. note::
This assumes, but does not c... |
def _calc_order(self, order):
if order is not None and order != '':
self.order = order.upper()
else:
shape = self.shape
if len(shape) <= 2:
self.order = 'M'
else:
depth = shape[-1]
if depth == 1:
... | Called to set the order of a multi-channel image.
The order should be determined by the loader, but this will
make a best guess if passed `order` is `None`. |
def encode(self, boundary):
if self.value is None:
value = self.fileobj.read()
else:
value = self.value
if re.search("^--%s$" % re.escape(boundary), value, re.M):
raise ValueError("boundary found in encoded string")
return "%s%s\r\n" % (self.encode_hdr... | Returns the string encoding of this parameter |
def _writeCloseFrame(self, reason=DISCONNECT.GO_AWAY):
self.transport.writeClose(reason)
self.transport.loseConnection()
self.transport = None | Write a close frame with the given reason and schedule this
connection close. |
def check_paths(self, paths, update=None):
exclude = [] if not self.exclude else self.exclude \
if isinstance(self.exclude, list) else [self.exclude]
for pathname, path in paths.items():
if update and pathname.upper() not in exclude:
os.environ[pathname.upper()] =... | Check if the path is in the os environ, and if not add it
Paramters:
paths (OrderedDict):
An ordered dict containing all of the paths from the
a given section, as key:val = name:path
update (bool):
If True, overwrites existing tree environ... |
def benchmark(store, n=10000):
x = UpdatableItem(store=store, count=0)
for _ in xrange(n):
x.count += 1 | Increments an integer count n times. |
def fullData(master):
builders = []
for b in master.config.builders:
steps = []
for step in b.factory.steps:
steps.append(getName(step))
builders.append(steps)
return {'builders': builders} | Send the actual configuration of the builders, how the steps are agenced.
Note that full data will never send actual detail of what command is run, name of servers, etc. |
def read(cls, *criteria, **kwargs):
if not kwargs.get('removed', False):
return cls.query.filter(cls.time_removed == 0, *criteria)
return cls.query.filter(*criteria) | filter query helper that handles soft delete logic. If your query conditions do not require expressions,
consider using read_by.
:param criteria: where clause conditions
:param kwargs: set removed=True if you want soft-deleted rows
:return: row object generator |
def function_call_action(self, text, loc, fun):
exshared.setpos(loc, text)
if DEBUG > 0:
print("FUN_CALL:",fun)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
if len(self.function_arguments) != self.symtab.get_attribute(self.function_call_inde... | Code executed after recognising the whole function call |
def get_response(self, results):
if results is None:
return None
for result in itertools.chain.from_iterable(results):
if isinstance(result, BaseResponse):
return result | Get response object from results.
:param results: list
:return: |
def close(self, terminate=True, kill=False):
if not self.closed:
if self.child_fd is not None:
os.close(self.child_fd)
self.child_fd = None
if self.child_fde is not None:
os.close(self.child_fde)
self.child_fde = None
... | Close the communication with the terminal's child.
If ``terminate`` is ``True`` then additionally try to terminate the
terminal, and if ``kill`` is also ``True``, kill the terminal if
terminating it was not enough. |
def load_data_file(
file_path,
file_path_is_relative=False,
comment_string=DATA_FILE_COMMENT,
field_separator=DATA_FILE_FIELD_SEPARATOR,
line_format=None
):
raw_tuples = []
if file_path_is_relative:
file_path = os.path.join(os.path.dirname(__file__), file_path)
with io.open(file_... | Load a data file, with one record per line and
fields separated by ``field_separator``,
returning a list of tuples.
It ignores lines starting with ``comment_string`` or empty lines.
If ``values_per_line`` is not ``None``,
check that each line (tuple)
has the prescribed number of values.
:... |
def _get_info(self, host, port, unix_socket, auth):
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
info = client.info()
del client
return info | Return info dict from specified Redis instance
:param str host: redis host
:param int port: redis port
:rtype: dict |
def _rule_as_string(self, rule):
if isinstance(rule, RuleSet):
return '%s{%s}' % (
self._selector_as_string(rule.selector),
self._declarations_as_string(rule.declarations))
elif isinstance(rule, ImportRule):
return "@import url('%s') %s;" % (
... | Converts a tinycss rule to a formatted CSS string
:param rule: The rule to format
:type rule: tinycss Rule object
:returns: The Rule as a CSS string
:rtype: str |
def do_batch_status(args):
rest_client = RestClient(args.url, args.user)
batch_ids = args.batch_ids.split(',')
if args.wait and args.wait > 0:
statuses = rest_client.get_statuses(batch_ids, args.wait)
else:
statuses = rest_client.get_statuses(batch_ids)
if args.format == 'yaml':
... | Runs the batch-status command, printing output to the console
Args:
args: The parsed arguments sent to the command at runtime |
def process_openxml_file(filename: str,
print_good: bool,
delete_if_bad: bool) -> None:
print_bad = not print_good
try:
file_good = is_openxml_good(filename)
file_bad = not file_good
if (print_good and file_good) or (print_bad and file_ba... | Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if ``True``, then prints the filename if the file
appears good.
delete_if_bad: if ``True``, then deletes the file if the file
... |
def zpopmin(self, key, count=None, *, encoding=_NOTSET):
if count is not None and not isinstance(count, int):
raise TypeError("count argument must be int")
args = []
if count is not None:
args.extend([count])
fut = self.execute(b'ZPOPMIN', key, *args, encoding=enc... | Removes and returns up to count members with the lowest scores
in the sorted set stored at key.
:raises TypeError: if count is not int |
def _get_http_args(self, params):
headers = self.http_args.get('headers', {})
if self.auth is not None:
auth_headers = self.auth.get_headers()
headers.update(auth_headers)
http_args = self.http_args.copy()
if self._source_id is not None:
headers['sourc... | Return a copy of the http_args
Adds auth headers and 'source_id', merges in params. |
def delete_mirror(name, config_path=_DEFAULT_CONFIG_PATH, force=False):
_validate_config(config_path)
force = six.text_type(bool(force)).lower()
current_mirror = __salt__['aptly.get_mirror'](name=name, config_path=config_path)
if not current_mirror:
log.debug('Mirror already absent: %s', name)
... | Remove a mirrored remote repository. By default, Package data is not removed.
:param str name: The name of the remote repository mirror.
:param str config_path: The path to the configuration file for the aptly instance.
:param bool force: Whether to remove the mirror even if it is used as the source
... |
def to_carrier(self, span_context, carrier):
carrier[_TRACE_ID_KEY] = str(span_context.trace_id)
if span_context.span_id is not None:
carrier[_SPAN_ID_KEY] = str(span_context.span_id)
carrier[_TRACE_OPTIONS_KEY] = str(
span_context.trace_options.trace_options_byte)
... | Inject the SpanContext fields to carrier dict.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:type carrier: dict
:param carrier: The carrier which holds the trace_id, span_id, options
... |
def get_default_classes(self):
default_classes = super(TabGroup, self).get_default_classes()
default_classes.extend(CSS_TAB_GROUP_CLASSES)
return default_classes | Returns a list of the default classes for the tab group.
Defaults to ``["nav", "nav-tabs", "ajax-tabs"]``. |
def getcoords(ddtt):
n_vertices_index = ddtt.objls.index('Number_of_Vertices')
first_x = n_vertices_index + 1
pts = ddtt.obj[first_x:]
return list(grouper(3, pts)) | return the coordinates of the surface |
def _set_last_aid(func):
@functools.wraps(func)
def new_func(self, *args, **kwargs):
aid = func(self, *args, **kwargs)
self.last_aid = aid
return aid
return new_func | Decorator for setting last_aid. |
def list(self):
if self.is_fake:
return
for item in self.collection.list():
yield item.uid + self.content_suffix | List collection items. |
def FormatDescriptorToPython(i):
i = i.replace("/", "_")
i = i.replace(";", "")
i = i.replace("[", "")
i = i.replace("(", "")
i = i.replace(")", "")
i = i.replace(" ", "")
i = i.replace("$", "")
return i | Format a descriptor into a form which can be used as a python attribute
example::
>>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V')
'Ljava_lang_LongLjava_lang_LongZZV
:param i: name to transform
:rtype: str |
def get_person_by_regid(self, regid):
if not self.valid_uwregid(regid):
raise InvalidRegID(regid)
url = "{}/{}/full.json".format(PERSON_PREFIX, regid.upper())
response = DAO.getURL(url, {"Accept": "application/json"})
if response.status != 200:
raise DataFailureEx... | Returns a restclients.Person object for the given regid. If the
regid isn't found, or if there is an error communicating with the PWS,
a DataFailureException will be thrown. |
def tracefunc_xml(func):
funcname = meta_util_six.get_funcname(func)
def wrp_tracefunc2(*args, **kwargs):
verbose = kwargs.get('verbose', True)
if verbose:
print('<%s>' % (funcname,))
with util_print.Indenter(' '):
ret = func(*args, **kwargs)
if verbose... | Causes output of function to be printed in an XML style block |
def pageLeft(self):
targetIdx = self.leftVisibleColIndex
firstNonKeyVisibleColIndex = self.visibleCols.index(self.nonKeyVisibleCols[0])
while self.rightVisibleColIndex != targetIdx and self.leftVisibleColIndex > firstNonKeyVisibleColIndex:
self.cursorVisibleColIndex -= 1
... | Redraw page one screen to the left.
Note: keep the column cursor in the same general relative position:
- if it is on the furthest right column, then it should stay on the
furthest right column if possible
- likewise on the left or in the middle
So really both the `leftI... |
def new(name):
vi = vips_lib.vips_interpolate_new(_to_bytes(name))
if vi == ffi.NULL:
raise Error('no such interpolator {0}'.format(name))
return Interpolate(vi) | Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interpolate
See for exa... |
def milestone(self, column=None, value=None, **kwargs):
return self._resolve_call('GIC_MILESTONE', column, value, **kwargs) | Status codes and related dates of certain grants,
>>> GICS().milestone('milestone_date', '16-MAR-01') |
def hexists(self, hashkey, attribute):
redis_hash = self._get_hash(hashkey, 'HEXISTS')
return self._encode(attribute) in redis_hash | Emulate hexists. |
def to_json(self):
return {
'st_month': self.st_month,
'st_day': self.st_day,
'st_hour': self.st_hour,
'end_month': self.end_month,
'end_day': self.end_day,
'end_hour': self.end_hour,
'timestep': self.timestep,
'is_l... | Convert the analysis period to a dictionary. |
def _def_check(self):
if self._def != dict():
for key, val in iteritems_(self._def):
if key not in list(TEXT_INDEX_ARGS.keys()):
raise CloudantArgumentError(127, key)
if not isinstance(val, TEXT_INDEX_ARGS[key]):
raise CloudantA... | Checks that the definition provided contains only valid arguments for a
text index. |
def read_csv(filename):
field_names = ('latitude', 'longitude', 'name')
data = utils.prepare_csv_read(filename, field_names, skipinitialspace=True)
locations = {}
args = []
for index, row in enumerate(data, 1):
name = '%02i:%s' % (index, row['name'])
locations[name] = (row['latitude'... | Pull locations from a user's CSV file.
Read gpsbabel_'s CSV output format
.. _gpsbabel: http://www.gpsbabel.org/
Args:
filename (str): CSV file to parse
Returns:
tuple of dict and list: List of locations as ``str`` objects |
def _remove_tree(self, tree, parent=None):
for sub_tree in tree.sub_trees:
self._remove_tree(sub_tree, parent=tree)
for index in tree.indexes:
if not getattr(tree, index):
continue
self._remove_from(
getattr(self, index + "_db"),
... | Really remove the tree identified by `tree` instance from all indexes
from database.
Args:
tree (obj): :class:`.Tree` instance.
parent (obj, default None): Reference to parent. |
def Definition(self):
result = self._FormatDescriptionComment()
result += " enum %s {\n" % self.enum_name
for k, v in sorted(iteritems(self.reverse_enum)):
result += " %s = %s;\n" % (v, k)
result += " }\n"
result += self._FormatField()
return result | Return a string with the definition of this field. |
def execute_request(self, url, http_method, query_params, post_data):
response = requests.request(http_method, url, params=query_params,
auth=self._auth, json=post_data,
headers={'User-Agent': USER_AGENT})
if isinstance(self._output... | Makes a request to the specified url endpoint with the
specified http method, params and post data.
Args:
url (string): The url to the API without query params.
Example: "https://api.housecanary.com/v2/property/value"
http_method (string): The http meth... |
def parse(self, data):
ASNlist = []
for line in data.splitlines()[1:]:
line = plain_str(line)
if "|" not in line:
continue
asn, ip, desc = [elt.strip() for elt in line.split('|')]
if asn == "NA":
continue
asn = "... | Parse bulk cymru data |
def list_commands(self, ctx):
rv = []
files = [_ for _ in next(os.walk(self.folder))[2] if not _.startswith("_") and _.endswith(".py")]
for filename in files:
rv.append(filename[:-3])
rv.sort()
return rv | List commands from folder. |
def create_event_subscription(self, url):
params = {'callbackUrl': url}
response = self._do_request('POST', '/v2/eventSubscriptions', params)
return response.json() | Register a callback URL as an event subscriber.
:param str url: callback URL
:returns: the created event subscription
:rtype: dict |
def assign_vertex_attrib_location(self, vbo, location):
with vbo:
if self.n_verts:
assert vbo.data.shape[0] == self.n_verts
else:
self.n_verts = vbo.data.shape[0]
gl.glVertexAttribPointer(location, vbo.data.shape[1], gl.GL_FLOAT, gl.GL_FALSE, 0... | Load data into a vbo |
def team_robots(self, team):
return [Robot(raw) for raw in self._get('team/%s/robots' % self.team_key(team))] | Get data about a team's robots.
:param team: Key for team whose robots you want data on.
:return: List of Robot objects |
def send(self, msg, timeout=None):
arb_id = msg.arbitration_id
if msg.is_extended_id:
arb_id |= NC_FL_CAN_ARBID_XTD
raw_msg = TxMessageStruct(arb_id,
bool(msg.is_remote_frame),
msg.dlc,
... | Send a message to NI-CAN.
:param can.Message msg:
Message to send
:raises can.interfaces.nican.NicanError:
If writing to transmit buffer fails.
It does not wait for message to be ACKed currently. |
def ensure_specification_cols_are_in_dataframe(specification, dataframe):
try:
assert isinstance(specification, OrderedDict)
except AssertionError:
raise TypeError("`specification` must be an OrderedDict.")
assert isinstance(dataframe, pd.DataFrame)
problem_cols = []
dataframe_cols =... | Checks whether each column in `specification` is in `dataframe`. Raises
ValueError if any of the columns are not in the dataframe.
Parameters
----------
specification : OrderedDict.
Keys are a proper subset of the columns in `data`. Values are either a
list or a single string, "all_diff... |
def weight_statistics(self):
all_weights = [d.get('weight', None) for u, v, d
in self.graph.edges(data=True)]
stats = describe(all_weights, nan_policy='omit')
return {
'all_weights': all_weights,
'min': stats.minmax[0],
'max': stats.minm... | Extract a statistical summary of edge weights present in
the graph.
:return: A dict with an 'all_weights' list, 'minimum',
'maximum', 'median', 'mean', 'std_dev' |
def add_f90_to_env(env):
try:
F90Suffixes = env['F90FILESUFFIXES']
except KeyError:
F90Suffixes = ['.f90']
try:
F90PPSuffixes = env['F90PPFILESUFFIXES']
except KeyError:
F90PPSuffixes = []
DialectAddToEnv(env, "F90", F90Suffixes, F90PPSuffixes,
sup... | Add Builders and construction variables for f90 to an Environment. |
def loads(schema_str):
try:
if sys.version_info[0] < 3:
return schema.parse(schema_str)
else:
return schema.Parse(schema_str)
except schema.SchemaParseException as e:
raise ClientError("Schema parse failed: %s" % (str(e))) | Parse a schema given a schema string |
def bootstraps(self, _args):
for bs in Bootstrap.list_bootstraps():
bs = Bootstrap.get_bootstrap(bs, self.ctx)
print('{Fore.BLUE}{Style.BRIGHT}{bs.name}{Style.RESET_ALL}'
.format(bs=bs, Fore=Out_Fore, Style=Out_Style))
print(' {Fore.GREEN}depends: {bs.rec... | List all the bootstraps available to build with. |
def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True):
text_view = Gtk.TextView()
text_view.set_wrap_mode(wrap_mode)
text_view.set_editable(editable)
if not editable:
text_view.set_cursor_visible(False)
... | Function creates a text view with wrap_mode
and justification |
def disable(self):
self.post("disable")
if self.service.restart_required:
self.service.restart(120)
return self | Disables the entity at this endpoint. |
def PrintFeed(feed):
import gdata
for i, entry in enumerate(feed.entry):
if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed):
print '%s %s\n' % (entry.title.text, entry.content.text)
elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed):
print '%s %s %s' % (i, entry.title.text, ... | Example function from Google to print a feed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.