code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def init_pool(self):
if self.pool is None:
if self.nproc > 1:
self.pool = mp.Pool(processes=self.nproc)
else:
self.pool = None
else:
print('pool already initialized?') | Initialize multiprocessing pool if necessary. |
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
... | Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists. |
def reflected_binary_operator(op):
assert not is_comparison(op)
@with_name(method_name_for_op(op, commute=True))
@coerce_numbers_to_my_dtype
def reflected_binary_operator(self, other):
if isinstance(self, NumericalExpression):
self_expr, other_expr, new_inputs = self.build_binary_op(... | Factory function for making binary operator methods on a Factor.
Returns a function, "reflected_binary_operator" suitable for implementing
functions like __radd__. |
def create_default_config():
config = configparser.RawConfigParser()
config.add_section('global')
config.set('global', 'env_source_rc', False)
config.add_section('shell')
config.set('shell', 'bash', "true")
config.set('shell', 'zsh', "true")
config.set('shell', 'gui', "true")
return conf... | Create a default configuration object, with all parameters filled |
def plotSkymapCatalog(lon,lat,**kwargs):
fig = plt.figure()
ax = plt.subplot(111,projection=projection)
drawSkymapCatalog(ax,lon,lat,**kwargs) | Plot a catalog of coordinates on a full-sky map. |
def _callable_func(self, func, axis, *args, **kwargs):
def callable_apply_builder(df, axis=0):
if not axis:
df.index = index
df.columns = pandas.RangeIndex(len(df.columns))
else:
df.columns = index
df.index = pandas.RangeInd... | Apply callable functions across given axis.
Args:
func: The functions to apply.
axis: Target axis to apply the function along.
Returns:
A new PandasQueryCompiler. |
def render_label(self, cairo_context, shape_id, text=None, label_scale=.9):
text = shape_id if text is None else text
shape = self.canvas.df_bounding_shapes.ix[shape_id]
shape_center = self.canvas.df_shape_centers.ix[shape_id]
font_size, text_shape = \
aspect_fit_font_size(te... | Draw label on specified shape.
Parameters
----------
cairo_context : cairo.Context
Cairo context to draw text width. Can be preconfigured, for
example, to set font style, etc.
shape_id : str
Shape identifier.
text : str, optional
... |
def archive(cls):
req = datastore.BeginTransactionRequest()
resp = datastore.begin_transaction(req)
tx = resp.transaction
req = datastore.RunQueryRequest()
req.read_options.transaction = tx
q = req.query
set_kind(q, kind='Todo')
add_projection(q, '__key__')
set_composite_filter(q.fil... | Delete all Todo items that are done. |
def ignore_path(path, ignore_list=None, whitelist=None):
if ignore_list is None:
return True
should_ignore = matches_glob_list(path, ignore_list)
if whitelist is None:
return should_ignore
return should_ignore and not matches_glob_list(path, whitelist) | Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns. |
def language(self, language):
if language is None:
raise ValueError("Invalid value for `language`, must not be `None`")
allowed_values = ["python", "r", "rmarkdown"]
if language not in allowed_values:
raise ValueError(
"Invalid value for `language` ({0}), ... | Sets the language of this KernelPushRequest.
The language that the kernel is written in # noqa: E501
:param language: The language of this KernelPushRequest. # noqa: E501
:type: str |
def sg_max(tensor, opt):
r
return tf.reduce_max(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | r"""Computes the maximum of elements across axis of a tensor.
See `tf.reduce_max()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with le... |
def bellman_ford(graph, weight, source=0):
n = len(graph)
dist = [float('inf')] * n
prec = [None] * n
dist[source] = 0
for nb_iterations in range(n):
changed = False
for node in range(n):
for neighbor in graph[node]:
alt = dist[node] + weight[node][neighbo... | Single source shortest paths by Bellman-Ford
:param graph: directed graph in listlist or listdict format
:param weight: can be negative.
in matrix format or same listdict graph
:returns: distance table, precedence table, bool
:explanation: bool is True if a negative circuit is
... |
def subjects_download(self, subject_id):
subject = self.subjects_get(subject_id)
if subject is None:
return None
else:
return FileInfo(
subject.data_file,
subject.properties[datastore.PROPERTY_MIMETYPE],
subject.properties[d... | Get data file for subject with given identifier.
Parameters
----------
subject_id : string
Unique subject identifier
Returns
-------
FileInfo
Information about subject's data file on disk or None if identifier
is unknown |
async def end(self):
try:
await self.proc.wait()
finally:
for temporary_file in self.temporary_files:
temporary_file.close()
self.temporary_files = []
return self.proc.returncode | End process execution. |
def set_annotation(self):
assert self.pending_symbol is not None
assert not self.value
annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),)
self.annotations = annotations if not self.annotations else self.annotations + annotations
self.ion_type = None
s... | Appends the context's ``pending_symbol`` to its ``annotations`` sequence. |
def start_patching(name=None):
global _factory_map, _patchers, _mocks
if _patchers and name is None:
warnings.warn('start_patching() called again, already patched')
_pre_import()
if name is not None:
factory = _factory_map[name]
items = [(name, factory)]
else:
items =... | Initiate mocking of the functions listed in `_factory_map`.
For this to work reliably all mocked helper functions should be imported
and used like this:
import dp_paypal.client as paypal
res = paypal.do_paypal_express_checkout(...)
(i.e. don't use `from dp_paypal.client import x` import s... |
def get_utm_epsg(longitude, latitude, crs=None):
if crs is None or crs.authid() == 'EPSG:4326':
epsg = 32600
if latitude < 0.0:
epsg += 100
epsg += get_utm_zone(longitude)
return epsg
else:
epsg_4326 = QgsCoordinateReferenceSystem('EPSG:4326')
transfor... | Return epsg code of the utm zone according to X, Y coordinates.
By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will
be reprojected from the input CRS to WGS84.
The code is based on the code:
http://gis.stackexchange.com/questions/34401
:param longitude: The longitude.
:ty... |
def rows_above_layout(self):
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = self._last_screen.height if self._last_screen else 0
return total_rows - max(self._min_av... | Return the number of rows visible in the terminal above the layout. |
def get_resource_form(self, *args, **kwargs):
if isinstance(args[-1], list) or 'resource_record_types' in kwargs:
return self.get_resource_form_for_create(*args, **kwargs)
else:
return self.get_resource_form_for_update(*args, **kwargs) | Pass through to provider ResourceAdminSession.get_resource_form_for_update |
def dataSetUnit(h5Dataset):
attributes = h5Dataset.attrs
if not attributes:
return ''
for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'):
if key in attributes:
return to_string(attributes[key])
return '' | Returns the unit of the h5Dataset by looking in the attributes.
It searches in the attributes for one of the following keys:
'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty
string is returned.
Always returns a string |
def parseLayoutFeatures(font):
featxt = tounicode(font.features.text or "", "utf-8")
if not featxt:
return ast.FeatureFile()
buf = UnicodeIO(featxt)
ufoPath = font.path
if ufoPath is not None:
buf.name = ufoPath
glyphNames = set(font.keys())
try:
parser = Parser(buf, ... | Parse OpenType layout features in the UFO and return a
feaLib.ast.FeatureFile instance. |
def blackbox_and_coarse_grain(blackbox, coarse_grain):
if blackbox is None:
return
for box in blackbox.partition:
outputs = set(box) & set(blackbox.output_indices)
if coarse_grain is None and len(outputs) > 1:
raise ValueError(
'A blackboxing with multiple out... | Validate that a coarse-graining properly combines the outputs of a
blackboxing. |
def loadhex(self, fobj):
if getattr(fobj, "read", None) is None:
fobj = open(fobj, "r")
fclose = fobj.close
else:
fclose = None
self._offset = 0
line = 0
try:
decode = self._decode_record
try:
for s in fo... | Load hex file into internal buffer. This is not necessary
if object was initialized with source set. This will overwrite
addresses if object was already initialized.
@param fobj file name or file-like object |
def set_xlabels(self, label=None, **kwargs):
if label is None:
label = label_from_attrs(self.data[self._x_var])
for ax in self._bottom_axes:
ax.set_xlabel(label, **kwargs)
return self | Label the x axis on the bottom row of the grid. |
def update_record(self, record, data=None, priority=None,
ttl=None, comment=None):
return self.manager.update_record(self, record, data=data,
priority=priority, ttl=ttl, comment=comment) | Modifies an existing record for this domain. |
def get_minimum_size(self, data):
size = self.element.get_minimum_size(data)
return datatypes.Point(
max(size.x, self.min_width),
max(size.y, self.min_height)
) | Returns the minimum size of the managed element, as long as
it is larger than any manually set minima. |
def get_serializer_class(self):
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
klass = self.get_object().__class__
elif "doctype" in self.request.REQUEST:
base = self.model.get_base_class()
... | gets the class type of the serializer
:return: `rest_framework.Serializer` |
def get_switched_form_field_attrs(self, prefix, input_type, name):
attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'}
attributes['data-' + prefix + 'field-' + input_type] = name
return attributes | Creates attribute dicts for the switchable theme form |
def remove_hash_prefix_indices(self, threat_list, indices):
batch_size = 40
q =
prefixes_to_remove = self.get_hash_prefix_values_to_remove(threat_list, indices)
with self.get_cursor() as dbc:
for i in range(0, len(prefixes_to_remove), batch_size):
remove_batch... | Remove records matching idices from a lexicographically-sorted local threat list. |
def do_IHaveRequest(self, apdu):
if _debug: WhoHasIHaveServices._debug("do_IHaveRequest %r", apdu)
if apdu.deviceIdentifier is None:
raise MissingRequiredParameter("deviceIdentifier required")
if apdu.objectIdentifier is None:
raise MissingRequiredParameter("objectIdentif... | Respond to a I-Have request. |
def on_delivery(self, name, channel, method, properties, body):
message = data.Message(name, channel, method, properties, body)
if self.is_processing:
return self.pending.append(message)
self.invoke_consumer(message) | Process a message from Rabbit
:param str name: The connection name
:param pika.channel.Channel channel: The message's delivery channel
:param pika.frames.MethodFrame method: The method frame
:param pika.spec.BasicProperties properties: The message properties
:param str body: The... |
def complete_node(arg):
try:
cmd = cfg.get('global', 'complete_node_cmd')
except configparser.NoOptionError:
return [ '', ]
cmd = re.sub('%search_string%', pipes.quote(arg), cmd)
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
res, err = p.communicate()... | Complete node hostname
This function is currently a bit special as it looks in the config file
for a command to use to complete a node hostname from an external
system.
It is configured by setting the config attribute "complete_node_cmd" to
a shell command. The string "%search_... |
def patch_string(s):
res = ''
it = PeekIterator(s)
for c in it:
if (ord(c) >> 10) == 0b110110:
n = it.peek()
if n and (ord(n) >> 10) == 0b110111:
res += chr(((ord(c) & 0x3ff) << 10 | (ord(n) & 0x3ff)) + 0x10000)
next(it)
else:
... | Reorganize a String in such a way that surrogates are printable
and lonely surrogates are escaped.
:param s: input string
:return: string with escaped lonely surrogates and 32bit surrogates |
def get_part_filenames(num_parts=None, start_num=0):
if num_parts is None:
num_parts = get_num_part_files()
return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+1)] | Get numbered PART.html filenames. |
def _shuffle_single(fname, extra_fn=None):
records = read_records(fname)
random.shuffle(records)
if extra_fn is not None:
records = extra_fn(records)
out_fname = fname.replace(UNSHUFFLED_SUFFIX, "")
write_records(records, out_fname)
tf.gfile.Remove(fname) | Shuffle a single file of records.
Args:
fname: a string
extra_fn: an optional function from list of TFRecords to list of TFRecords
to be called after shuffling. |
def KL_divergence(P,Q):
assert(P.keys()==Q.keys())
distance = 0
for k in P.keys():
distance += P[k] * log(P[k]/Q[k])
return distance | Compute the KL divergence between distributions P and Q
P and Q should be dictionaries linking symbols to probabilities.
the keys to P and Q should be the same. |
def export_event_based_gateway_info(node_params, output_element):
output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])
output_element.set(consts.Consts.instantiate, node_params[consts.Consts.instantiate])
output_element.set(consts.Consts.event_gateway... | Adds EventBasedGateway node attributes to exported XML element
:param node_params: dictionary with given event based gateway parameters,
:param output_element: object representing BPMN XML 'eventBasedGateway' element. |
def init(self):
self.url = self.url.format(host=self.host, port=self.port,
api_key=self.api_key) | Initialize the URL used to connect to SABnzbd. |
def import_submodules(package):
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for _, full_name, is_pkg in pkgutil.walk_packages(package.__path__, package.__name__ + '.'):
results[full_name] = importlib.import_module(full_name)
if is_pkg:
... | Return list of imported module instances from beneath root_package |
def dump_commands(self, commands):
directory = os.path.join(os.path.dirname(self.sql_script), 'fails')
fname = os.path.basename(self.sql_script.rsplit('.')[0])
return dump_commands(commands, directory, fname) | Dump commands wrapper for external access. |
def get_manhole_factory(namespace, **passwords):
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = (
lambda _: EnhancedColoredManhole(namespace)
)
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords... | Get a Manhole Factory |
def load_modules_from_python(self, route_list):
for name, modpath in route_list:
if ':' in modpath:
path, attr = modpath.split(':', 1)
else:
path, attr = modpath, None
self.commands[name] = ModuleLoader(path, attr=attr) | Load modules from the native python source. |
def validate(obj, schema):
if not framework.EvaluationContext.current().validate:
return obj
if hasattr(obj, 'tuple_schema'):
obj.tuple_schema.validate(obj)
if schema:
schema.validate(obj)
return obj | Validate an object according to its own AND an externally imposed schema. |
def flat_model(tree):
names = []
for columns in viewvalues(tree):
for col in columns:
if isinstance(col, dict):
col_name = list(col)[0]
names += [col_name + '__' + c for c in flat_model(col)]
else:
names.append(col)
return names | Flatten the tree into a list of properties adding parents as prefixes. |
def layer(self, layer_name):
uri = self.layer_uri(layer_name)
layer = QgsVectorLayer(uri, layer_name, 'ogr')
if not layer.isValid():
layer = QgsRasterLayer(uri, layer_name)
if not layer.isValid():
return False
monkey_patch_keywords(layer)
r... | Get QGIS layer.
:param layer_name: The name of the layer to fetch.
:type layer_name: str
:return: The QGIS layer.
:rtype: QgsMapLayer
.. versionadded:: 4.0 |
def iter_halfs_bend(graph):
for atom2 in range(graph.num_vertices):
neighbors = list(graph.neighbors[atom2])
for index1, atom1 in enumerate(neighbors):
for atom3 in neighbors[index1+1:]:
try:
affected_atoms = graph.get_halfs(atom2, atom1)[0]
... | Select randomly two consecutive bonds that divide the molecule in two |
def update_global_secondary_index(table_name, global_indexes, region=None,
key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
table = Table(table_name, connection=conn)
return table.update_global_secondary_index(globa... | Updates the throughput of the given global secondary indexes.
CLI Example:
.. code-block:: bash
salt myminion boto_dynamodb.update_global_secondary_index table_name /
indexes |
def _add(self, error: "Err"):
if self.trace_errs is True:
self.errors.append(error) | Adds an error to the trace if required |
def format_py3o_val(value):
value = force_unicode(value)
value = escape(value)
value = value.replace(u'\n', u'<text:line-break/>')
return Markup(value) | format a value to fit py3o's context
* Handle linebreaks |
def page(self, number, **context):
size = max(0, self.context(**context).pageSize)
if not size:
return self.copy()
else:
return self.copy(page=number, pageSize=size) | Returns the records for the current page, or the specified page number.
If a page size is not specified, then this record sets page size will
be used.
:param pageno | <int>
pageSize | <int>
:return <orb.RecordSet> |
def _handle_child(
self, node: SchemaNode, stmt: Statement, sctx: SchemaContext) -> None:
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
node.name = stmt.argument
node.ns = sctx.default_ns
node._get_description(stmt)
self._add_child(node)... | Add child node to the receiver and handle substatements. |
def desc(self) -> str:
kind, value = self.kind.value, self.value
return f"{kind} {value!r}" if value else kind | A helper property to describe a token as a string for debugging |
def _deserialize(self, value, attr, obj):
if not self.context.get('convert_dates', True) or not value:
return value
value = super(PendulumField, self)._deserialize(value, attr, value)
timezone = self.get_field_value('timezone')
target = pendulum.instance(value)
if (ti... | Deserializes a string into a Pendulum object. |
def rule(self, key):
def register(f):
self.rules[key] = f
return f
return register | Decorate as a rule for a key in top level JSON. |
def repair(self, volume_id_or_uri, timeout=-1):
data = {
"type": "ExtraManagedStorageVolumePaths",
"resourceUri": self._client.build_uri(volume_id_or_uri)
}
custom_headers = {'Accept-Language': 'en_US'}
uri = self.URI + '/repair'
return self._client.create... | Removes extra presentations from a specified volume on the storage system.
Args:
volume_id_or_uri:
Can be either the volume id or the volume uri.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in... |
def install_middleware(middleware_name, lookup_names=None):
if lookup_names is None:
lookup_names = (middleware_name,)
middleware_attr = 'MIDDLEWARE' if getattr(settings,
'MIDDLEWARE',
None) is not None \
... | Install specified middleware |
def mouseDoubleClickEvent(self, event):
if self.rename_tabs is True and \
event.buttons() == Qt.MouseButtons(Qt.LeftButton):
index = self.tabAt(event.pos())
if index >= 0:
self.tab_name_editor.edit_tab(index)
else:
QTabBar.mouseD... | Override Qt method to trigger the tab name editor. |
async def recv_message(self):
if not self._recv_initial_metadata_done:
await self.recv_initial_metadata()
with self._wrapper:
message = await recv_message(self._stream, self._codec,
self._recv_type)
self._recv_message_count += ... | Coroutine to receive incoming message from the server.
If server sends UNARY response, then you can call this coroutine only
once. If server sends STREAM response, then you should call this
coroutine several times, until it returns None. To simplify you code in
this case, :py:class:`Str... |
def set_source_variable(self, source_id, variable, value):
source_id = int(source_id)
return self._send_cmd("SET S[%d].%s=\"%s\"" % (
source_id, variable, value)) | Change the value of a source variable. |
def _create_and_add_parameters(params):
global _current_parameter
if _is_simple_type(params):
_current_parameter = SimpleParameter(params)
_current_option.add_parameter(_current_parameter)
else:
for i in params:
if _is_simple_type(i):
_current_parameter = ... | Parses the configuration and creates Parameter instances. |
def simulate(self, ts_length=100, random_state=None):
r
random_state = check_random_state(random_state)
x0 = multivariate_normal(self.mu_0.flatten(), self.Sigma_0)
w = random_state.randn(self.m, ts_length-1)
v = self.C.dot(w)
x = simulate_linear_model(self.A, x0, v, ts_le... | r"""
Simulate a time series of length ts_length, first drawing
.. math::
x_0 \sim N(\mu_0, \Sigma_0)
Parameters
----------
ts_length : scalar(int), optional(default=100)
The length of the simulation
random_state : int or np.random.RandomState, o... |
def _check_time_fn(self, time_instance=False):
if time_instance and not isinstance(self.time_fn, param.Time):
raise AssertionError("%s requires a Time object"
% self.__class__.__name__)
if self.time_dependent:
global_timefn = self.time_fn is param... | If time_fn is the global time function supplied by
param.Dynamic.time_fn, make sure Dynamic parameters are using
this time function to control their behaviour.
If time_instance is True, time_fn must be a param.Time instance. |
def on(self, year, month, day):
return self.set(year=int(year), month=int(month), day=int(day)) | Returns a new instance with the current date set to a different date.
:param year: The year
:type year: int
:param month: The month
:type month: int
:param day: The day
:type day: int
:rtype: DateTime |
def _get_rom_firmware_version(self, data):
firmware_details = self._get_firmware_embedded_health(data)
if firmware_details:
try:
rom_firmware_version = (
firmware_details['HP ProLiant System ROM'])
return {'rom_firmware_version': rom_firmwa... | Gets the rom firmware version for server capabilities
Parse the get_host_health_data() to retreive the firmware
details.
:param data: the output returned by get_host_health_data()
:returns: a dictionary of rom firmware version. |
def accept_line(self, logevent):
if ("is now in state" in logevent.line_str and
logevent.split_tokens[-1] in self.states):
return True
if ("replSet" in logevent.line_str and
logevent.thread == "rsMgr" and
logevent.split_tokens[-1] in self.state... | Return True on match.
Only match log lines containing 'is now in state' (reflects other
node's state changes) or of type "[rsMgr] replSet PRIMARY" (reflects
own state changes). |
def intcomma(value):
try:
if isinstance(value, compat.string_types):
float(value.replace(',', ''))
else:
float(value)
except (TypeError, ValueError):
return value
orig = str(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
... | Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'. To maintain
some compatability with Django's intcomma, this function also accepts
floats. |
def disaggregate_wind(wind_daily, method='equal', a=None, b=None, t_shift=None):
assert method in ('equal', 'cosine', 'random'), 'Invalid method'
wind_eq = melodist.distribute_equally(wind_daily)
if method == 'equal':
wind_disagg = wind_eq
elif method == 'cosine':
assert None not in (a, ... | general function for windspeed disaggregation
Args:
wind_daily: daily values
method: keyword specifying the disaggregation method to be used
a: parameter a for the cosine function
b: parameter b for the cosine function
t_shift: parameter t_shift for the cosine function
... |
def is_unix(name=None):
name = name or sys.platform
return Platform.is_darwin(name) or Platform.is_linux(name) or Platform.is_freebsd(name) | Return true if the platform is a unix, False otherwise. |
def pop(self):
if self.stack:
val = self.stack[0]
self.stack = self.stack[1:]
return val
else:
raise StackError('Stack empty') | Pops a value off the top of the stack.
@return: Value popped off the stack.
@rtype: *
@raise StackError: Raised when there is a stack underflow. |
def encode_offset_commit_request(cls, client_id, correlation_id,
group, payloads):
grouped_payloads = group_by_topic_and_partition(payloads)
message = []
message.append(cls._encode_message_header(client_id, correlation_id,
... | Encode some OffsetCommitRequest structs
Arguments:
client_id: string
correlation_id: int
group: string, the consumer group you are committing offsets for
payloads: list of OffsetCommitRequest |
def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain:
if not isinstance(chain, MiningChain):
raise ValidationError("`at_block_number` may only be used with 'MiningChain")
at_block = chain.get_canonical_block_by_number(block_number)
db = chain.chaindb.db
chain_at_bloc... | Rewind the chain back to the given block number. Calls to things like
``get_canonical_head`` will still return the canonical head of the chain,
however, you can use ``mine_block`` to mine fork chains. |
def unlock_password(self, ID, reason):
log.info('Unlock password %s, Reason: %s' % (ID, reason))
self.unlock_reason = reason
self.put('passwords/%s/unlock.json' % ID) | Unlock a password. |
def set_iscsi_info(self, target_name, lun, ip_address,
port='3260', auth_method=None, username=None,
password=None):
if(self._is_boot_mode_uefi()):
iscsi_info = {}
iscsi_info['iSCSITargetName'] = target_name
iscsi_info['iSCSILUN']... | Set iSCSI details of the system in UEFI boot mode.
The initiator system is set with the target details like
IQN, LUN, IP, Port etc.
:param target_name: Target Name for iSCSI.
:param lun: logical unit number.
:param ip_address: IP address of the target.
:param port: port ... |
def expandf(m, format):
_assert_expandable(format, True)
return _apply_replace_backrefs(m, format, flags=FORMAT) | Expand the string using the format replace pattern or function. |
def set_viewbox(self, x, y, w, h):
self.attributes['viewBox'] = "%s %s %s %s" % (x, y, w, h)
self.attributes['preserveAspectRatio'] = 'none' | Sets the origin and size of the viewbox, describing a virtual view area.
Args:
x (int): x coordinate of the viewbox origin
y (int): y coordinate of the viewbox origin
w (int): width of the viewbox
h (int): height of the viewbox |
def anchor(args):
from jcvi.formats.blast import bed
p = OptionParser(anchor.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
mapbed, blastfile = args
bedfile = bed([blastfile])
markersbed = Bed(bedfile)
markers = markersbed.order
mapbe... | %prog anchor map.bed markers.blast > anchored.bed
Anchor scaffolds based on map. |
def getServiceRequest(self, request, target):
try:
return self._request_class(
request.envelope, self.services[target], None)
except KeyError:
pass
try:
sp = target.split('.')
name, meth = '.'.join(sp[:-1]), sp[-1]
retur... | Returns a service based on the message.
@raise UnknownServiceError: Unknown service.
@param request: The AMF request.
@type request: L{Request<pyamf.remoting.Request>}
@rtype: L{ServiceRequest} |
def add_port_forward_rule(self, is_ipv6, rule_name, proto, host_ip, host_port, guest_ip, guest_port):
if not isinstance(is_ipv6, bool):
raise TypeError("is_ipv6 can only be an instance of type bool")
if not isinstance(rule_name, basestring):
raise TypeError("rule_name can only be... | Protocol handled with the rule.
in is_ipv6 of type bool
in rule_name of type str
in proto of type :class:`NATProtocol`
Protocol handled with the rule.
in host_ip of type str
IP of the host interface to which the rule should apply.
An empty ip addre... |
def _tot_unhandled_hosts_by_state(self, state):
return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and
h.is_problem and not h.problem_has_been_acknowledged) | Generic function to get the number of unhandled problem hosts in the specified state
:param state: state to filter on
:type state:
:return: number of host in state *state* and which are not acknowledged problems
:rtype: int |
def _apply_key_type(self, keys):
typed_key = ()
for dim, key in zip(self.kdims, keys):
key_type = dim.type
if key_type is None:
typed_key += (key,)
elif isinstance(key, slice):
sl_vals = [key.start, key.stop, key.step]
t... | If a type is specified by the corresponding key dimension,
this method applies the type to the supplied key. |
def get_archive(self, archive_name):
try:
spec = self._get_archive_spec(archive_name)
return spec
except KeyError:
raise KeyError('Archive "{}" not found'.format(archive_name)) | Get a data archive given an archive name
Returns
-------
archive_specification : dict
archive_name: name of the archive to be retrieved
authority: name of the archive's authority
archive_path: service path of archive |
def is_config_container(v):
cls = type(v)
return (
issubclass(cls, list) or
issubclass(cls, dict) or
issubclass(cls, Config)
) | checks whether v is of type list,dict or Config |
def declare_queue(self, queue_name):
attempts = 1
while True:
try:
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self._declare_queue(queue_name)
self.queues.add(queue_name)
... | Declare a queue. Has no effect if a queue with the given
name already exists.
Parameters:
queue_name(str): The name of the new queue.
Raises:
ConnectionClosed: If the underlying channel or connection
has been closed. |
def _get_thumbnail_filename(filename, append_text="-thumbnail"):
name, ext = os.path.splitext(filename)
return ''.join([name, append_text, ext]) | Returns a thumbnail version of the file name. |
def types_of_specie(self):
if not self.is_ordered:
raise TypeError(
)
types = []
for site in self:
if site.specie not in types:
types.append(site.specie)
return types | List of types of specie. Only works for ordered structures.
Disordered structures will raise TypeError. |
def get_SZ_orient(self):
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
scatter_outdated = self._scatter_signature != (self.thet0, self.thet,
self.phi0, self.phi, self... | Get the S and Z matrices using the specified orientation averaging. |
def load_structure_path(self, structure_path, file_type):
if not file_type:
raise ValueError('File type must be specified')
self.file_type = file_type
self.structure_dir = op.dirname(structure_path)
self.structure_file = op.basename(structure_path) | Load a structure file and provide pointers to its location
Args:
structure_path (str): Path to structure file
file_type (str): Type of structure file |
async def oauth2_request(
self,
url: str,
access_token: str = None,
post_args: Dict[str, Any] = None,
**args: Any
) -> Any:
all_args = {}
if access_token:
all_args["access_token"] = access_token
all_args.update(args)
if all_args... | Fetches the given URL auth an OAuth2 access token.
If the request is a POST, ``post_args`` should be provided. Query
string arguments should be given as keyword arguments.
Example usage:
..testcode::
class MainHandler(tornado.web.RequestHandler,
... |
def addJsonDirectory(self, directory, test=None):
for filename in os.listdir(directory):
try:
fullPath = os.path.join(directory, filename)
if not test or test(filename, fullPath):
with open(fullPath) as f:
jsonData = json.load(f)
name, _ = os.path.splitext(fil... | Adds data from json files in the given directory. |
def update_tasks(self):
for task in self.task_manager.timeout_tasks():
self.task_manager.task_done(
task.id, TimeoutError("Task timeout", task.timeout))
self.worker_manager.stop_worker(task.worker_id)
for task in self.task_manager.cancelled_tasks():
se... | Handles timing out Tasks. |
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True,
erase_args: bool = True) -> None:
parser.add_argument("--log-level", default="INFO", choices=logging._nameToLevel,
help="Logging verbosity.")
parser.add_argument("--log-structured", action="sto... | Add command line flags specific to logging.
:param parser: `argparse` parser where to add new flags.
:param erase_args: Automatically remove logging-related flags from parsed args.
:param patch: Patch parse_args() to automatically setup logging. |
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None:
existing_plugin = cls.available.get(name)
if existing_plugin is None:
cls.available[name] = plugin
elif existing_plugin != plugin:
raise ConnectionPluginAlreadyRegistered(
f"Connection p... | Registers a connection plugin with a specified name
Args:
name: name of the connection plugin to register
plugin: defined connection plugin class
Raises:
:obj:`nornir.core.exceptions.ConnectionPluginAlreadyRegistered` if
another plugin with the speci... |
def save_list(key, *values):
return json.dumps({key: [_get_json(value) for value in values]}) | Convert the given list of parameters to a JSON object.
JSON object is of the form:
{ key: [values[0], values[1], ... ] },
where values represent the given list of parameters. |
def spec(self):
pspec = {}
pspec['name'] = self.NAME
pspec['version'] = self.VERSION
pspec['description'] = self.DESCRIPTION
components = [sys.argv[0], self.NAME]
if self.USE_ARGUMENTS: components.append('$(arguments)')
pspec['exe_command'] = self.COMMAND or ' '.j... | Generate spec for the processor as a Python dictionary.
A spec is a standard way to describe a MountainLab processor in a way
that is easy to process, yet still understandable by humans.
This method generates a Python dictionary that complies with a spec
definition. |
def clone(self, substitutions, commit=True, **kwargs):
return self.store.clone(substitutions, **kwargs) | Clone a DAG, optionally skipping the commit. |
def _env_filenames(filenames, env):
env_filenames = []
for filename in filenames:
filename_parts = filename.split('.')
filename_parts.insert(1, env)
env_filenames.extend([filename, '.'.join(filename_parts)])
return env_filenames | Extend filenames with ennv indication of environments.
:param list filenames: list of strings indicating filenames
:param str env: environment indicator
:returns: list of filenames extended with environment version
:rtype: list |
def get_p2o_params_from_url(cls, url):
if PRJ_JSON_FILTER_SEPARATOR not in url:
return {"url": url}
params = {'url': url.split(' ', 1)[0]}
tokens = url.split(PRJ_JSON_FILTER_SEPARATOR)[1:]
if len(tokens) > 1:
cause = "Too many filters defined for %s, only the firs... | Get the p2o params given a URL for the data source |
def init_threads(t=None, s=None):
global THREAD, SIGNAL
THREAD = t or dummyThread
SIGNAL = s or dummySignal | Should define dummyThread class and dummySignal class |
def accounts(self):
response = self.graph.get('%s/accounts' % self.id)
accounts = []
for item in response['data']:
account = Structure(
page = Page(
id = item['id'],
name = item['name'],
category = item['cate... | A list of structures describing apps and pages owned by this user. |
def get_valid_kwargs(func, potential_kwargs):
kwargs = {}
for name in get_kwarg_names(func):
with suppress(KeyError):
kwargs[name] = potential_kwargs[name]
return kwargs | Return valid kwargs to function func |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.