Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
19,800 | def init_app(self, app):
provider = app.config.get("STORAGE_PROVIDER", None)
key = app.config.get("STORAGE_KEY", None)
secret = app.config.get("STORAGE_SECRET", None)
container = app.config.get("STORAGE_CONTAINER", None)
allowed_extensions = app.config.get("STORAGE_ALLOW... | To initiate with Flask
:param app: Flask object
:return: |
19,801 | def add_watch_point(self, string, rating, importance=5):
d = {}
d[] = string
d[] = rating
d[] = importance
self.watch_points.append(d) | For a log session you can add as many watch points
which are used in the aggregation and extraction of
key things that happen.
Each watch point has a rating (up to you and can range
from success to total failure and an importance for
finer control of display |
19,802 | def temporarily_enabled(self):
old_setting = self.options.enabled
self.enable()
try:
yield
finally:
self.options.enabled = old_setting | Temporarily enable the cache (useful for testing) |
19,803 | def credential_delete(self, *ids):
return self.raw_query("credential", "delete", data={
"credentials": [{"id": str(id)} for id in ids]
}) | Delete one or more credentials.
:param ids: one or more credential ids |
19,804 | def add_house(self, complex: str, **kwargs):
self.check_complex(complex)
self.post(.format(developer=self.developer, complex=complex), data=kwargs) | Add a new house to the rumetr db |
19,805 | def guinieranalysis(samplenames, qranges=None, qmax_from_shanum=True, prfunctions_postfix=, dist=None,
plotguinier=True, graph_extension=, dmax=None, dmax_from_shanum=False):
figpr = plt.figure()
ip = get_ipython()
axpr = figpr.add_subplot(1, 1, 1)
if qranges is None:
qr... | Perform Guinier analysis on the samples.
Inputs:
samplenames: list of sample names
qranges: dictionary of q ranges for each sample. The keys are sample names. The special '__default__' key
corresponds to all samples which do not have a key in the dict.
qmax_from_shanum: use the ... |
19,806 | def iter_packages(self, name, range_=None, paths=None):
for package in iter_packages(name, range_, paths):
if not self.excludes(package):
yield package | Same as iter_packages in packages.py, but also applies this filter.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search ... |
19,807 | def bind(_self, **kwargs):
return Logger(
{**_self._extra, **kwargs},
_self._exception,
_self._record,
_self._lazy,
_self._ansi,
_self._raw,
_self._depth,
) | Bind attributes to the ``extra`` dict of each logged message record.
This is used to add custom context to each logging call.
Parameters
----------
**kwargs
Mapping between keys and values that will be added to the ``extra`` dict.
Returns
-------
:c... |
19,808 | def create_record(self, type, name, data, priority=None, port=None,
weight=None, **kwargs):
api = self.doapi_manager
data = {
"type": type,
"name": name,
"data": data,
"priority": priority,
"port": port,
... | Add a new DNS record to the domain
:param str type: the type of DNS record to add (``"A"``, ``"CNAME"``,
etc.)
:param str name: the name (hostname, alias, etc.) of the new record
:param str data: the value of the new record
:param int priority: the priority of the new record... |
19,809 | def _get_dimension_scales(self, dimension, preserve_domain=False):
if preserve_domain:
return [
self.scales[k] for k in self.scales if (
k in self.scales_metadata and
self.scales_metadata[k].get() == dimension and
n... | Return the list of scales corresponding to a given dimension.
The preserve_domain optional argument specifies whether one should
filter out the scales for which preserve_domain is set to True. |
19,810 | def tool_classpath_from_products(products, key, scope):
callback_product_map = products.get_data() or {}
callback = callback_product_map.get(scope, {}).get(key)
if not callback:
raise TaskError(
.format(key=key, scope=scope))
return callback() | Get a classpath for the tool previously registered under key in the given scope.
:param products: The products of the current pants run.
:type products: :class:`pants.goal.products.Products`
:param string key: The key the tool configuration was registered under.
:param string scope: The scope the tool ... |
19,811 | def nvmlDeviceGetMultiGpuBoard(handle):
r
c_multiGpu = c_uint();
fn = _nvmlGetFunctionPointer("nvmlDeviceGetMultiGpuBoard")
ret = fn(handle, byref(c_multiGpu))
_nvmlCheckReturn(ret)
return bytes_to_str(c_multiGpu.value) | r"""
/**
* Retrieves whether the device is on a Multi-GPU Board
* Devices that are on multi-GPU boards will set \a multiGpuBool to a non-zero value.
*
* For Fermi &tm; or newer fully supported devices.
*
* @param device The identifier of the target device
... |
19,812 | def idle_send_acks_and_nacks(self):
max_blocks_to_send = 10
blocks_sent = 0
i = 0
now = time.time()
while (i < len(self.blocks_to_ack_and_nack) and
blocks_sent < max_blocks_to_send):
stuff = self.blocks_to_ack_and_nack... | Send packets to UAV in idle loop |
19,813 | def add_dashboard_panel(self, dashboard, name, panel_type, metrics, scope=None, sort_by=None, limit=None, layout=None):
panel_configuration = {
: name,
: None,
: None,
: [],
: {
: 1,
: 1,
: 12,
... | **Description**
Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel.
**Arguments**
- **dashboard**: dashboard to edit
- **name**: name of the new panel
- **panel_type**: type of the new panel. Valid valu... |
19,814 | def get_build_output(self, process):
while True:
output = process.stdout.readline()
if output == b and process.poll() is not None:
if process.returncode > 0:
raise Exception("Compilation ended with an error"
... | Parse the output of the ns-3 build process to extract the information
that is needed to draw the progress bar.
Args:
process: the subprocess instance to listen to. |
19,815 | def _mkOp(fn):
def op(*operands, key=None) -> RtlSignalBase:
assert operands, operands
top = None
if key is not None:
operands = map(key, operands)
for s in operands:
if top is None:
top = s
else:
top ... | Function to create variadic operator function
:param fn: function to perform binary operation |
19,816 | def main():
parser = argparse.ArgumentParser(description=)
parser.add_argument(, , type=int, help=, default=5556)
parser.add_argument(, , help=, nargs=)
parser.add_argument(, , type=str, help=)
args = parser.parse_args()
if args.config:
_add_devices_from_config(args)
if args.d... | Set up the server. |
19,817 | def _set_vni_any(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="vni-any", rest_name="vni-any", parent=self, choice=(u, u), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=... | Setter method for vni_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_vni_any is considered as a private
method. Backends looking to populate this variable should
do so via callin... |
19,818 | def transpose_func(classes, table):
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerate(classes):
if i > j:
temp = transposed_table[item1][item2]
transposed_table[item1][item2] = transposed_table[item2][item1]
... | Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict |
19,819 | def get_next_action(self, request, application, label, roles):
if label is not None:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
actions = self.get_actions(request, application, roles)
if request.method == "GET":
context = ... | Django view method. We provide a default detail view for
applications. |
19,820 | def node_done(self, ssid=None):
if self.api_key is None:
raise exceptions.ApiKeyRequired
if ssid is None:
raise exceptions.SsidRequired
requested_hosts = dict()
for host in self.self_inventory:
if ssid == self.self_inventor... | Release the servers for the specified ssid.
The API doesn't provide any kind of output, try to be helpful by
providing the list of servers to be released.
:param ssid: ssid of the server pool
:return: [ requested_hosts ] |
19,821 | def rowsAboutToBeRemoved(self, parent, start, end):
self._viewIsDirty = True
super(StimulusView, self).rowsAboutToBeRemoved(parent, start, end) | Marks view for repaint. :qtdoc:`Re-implemented<QAbstractItemView.rowsAboutToBeRemoved>` |
19,822 | def _validate_tileset(self, tileset):
if not in tileset:
tileset = "{0}.{1}".format(self.username, tileset)
pattern =
if not re.match(pattern, tileset, flags=re.IGNORECASE):
raise ValidationError(
.format(
tileset, pattern))... | Validate the tileset name and
ensure that it includes the username |
19,823 | def take(self, obj):
cached = self._thread_local.cache[self._get_cache_key(obj)]
build_kwargs = {}
if in cached and in cached:
build_kwargs[] = cached[].objects.filter(pk__in=cached[])
elif in cached:
if cached[].__class__.objects.filter(pk=cached[].... | Get cached value and clean cache. |
19,824 | def send(self, msg, timeout=None):
try:
timestamp = struct.pack(, int(msg.timestamp * 1000))
except struct.error:
raise ValueError()
try:
a_id = struct.pack(, msg.arbitration_id)
except struct.error:
raise ValueError()
byte... | Send a message over the serial device.
:param can.Message msg:
Message to send.
.. note:: Flags like ``extended_id``, ``is_remote_frame`` and
``is_error_frame`` will be ignored.
.. note:: If the timestamp is a float value it will be converted
... |
19,825 | def has_mixture_channel(val: Any) -> bool:
mixture_getter = getattr(val, , None)
result = NotImplemented if mixture_getter is None else mixture_getter()
if result is not NotImplemented:
return result
result = has_unitary(val)
if result is not NotImplemented and result:
return r... | Returns whether the value has a mixture channel representation.
In contrast to `has_mixture` this method falls back to checking whether
the value has a unitary representation via `has_channel`.
Returns:
If `val` has a `_has_mixture_` method and its result is not
NotImplemented, that result... |
19,826 | def guess_xml_encoding(self, content):
r
matchobj = self.__regex[].match(content)
return matchobj and matchobj.group(1).lower() | r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None |
19,827 | def clean(self):
if self.clean_level == :
idx, = np.where(self.data.altitude <= 550)
self.data = self[idx,:]
self.data.replace(-999999., np.nan, inplace=True)
if (self.clean_level == ) | (self.clean_level == ):
try:
idx, = np.where(... | Routine to return C/NOFS IVM data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneType)
data in ins... |
19,828 | def _filehandle(self):
if not self._fh or self._is_closed():
filename = self._rotated_logfile or self.filename
if filename.endswith():
self._fh = gzip.open(filename, )
else:
self._fh = open(filename, "r", 1)
if self.read_fr... | Return a filehandle to the file being tailed, with the position set
to the current offset. |
19,829 | def isCompatible(self, other, cls):
if not isinstance(other, cls):
raise TypeError(
% (cls.__name__, other.__class__.__name__))
reporter = self.compatibilityReporterClass(self, other)
self._isCompatible(other, reporter)
return not rep... | Evaluate interpolation compatibility with other. |
19,830 | def saddr(address):
if isinstance(address, six.string_types):
return address
elif isinstance(address, tuple) and len(address) >= 2 and in address[0]:
return .format(address[0], address[1])
elif isinstance(address, tuple) and len(address) >= 2:
return .format(*address)
else:... | Return a string representation for an address.
The *address* paramater can be a pipe name, an IP address tuple, or a
socket address.
The return value is always a ``str`` instance. |
19,831 | def _split_header(header):
params = {}
parts = header.split()
for param in parts:
if param.find() > -1:
continue
param = param.strip()
param_parts = param.split(, 1)
param... | Turn Authorization: header into parameters. |
19,832 | def solid_angle(center, coords):
r = [np.subtract(c, center) for c in coords]
r_norm = [np.linalg.norm(i) for i in r]
angle = 0
for i in range(1, len(r) - 1):
j = i + 1
tp = np.abs(np.dot(r[0], np.cross(r[i], r[j])))
de = r_norm[0] * r_norm[i] * r_norm... | Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle. |
19,833 | def create(parallel):
queue = {k: v for k, v in parallel.items() if k in ["queue", "cores_per_job", "mem"]}
yield queue | Create a queue based on the provided parallel arguments.
TODO Startup/tear-down. Currently using default queue for testing |
19,834 | def _set_show_firmware_option(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=show_firmware_option.show_firmware_option, is_container=, presence=False, yang_name="show-firmware-option", rest_name="firmware", parent=self, path_helper=self._path_helper,... | Setter method for show_firmware_option, mapped from YANG variable /show/show_firmware_dummy/show_firmware_option (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_firmware_option is considered as a private
method. Backends looking to populate this variable sho... |
19,835 | def check_docstring_sections(self, definition, docstring):
if not docstring:
return
lines = docstring.split("\n")
if len(lines) < 2:
return
lower_section_names = [s.lower() for s in self.SECTION_NAMES]
def _suspected_as_section(_line):
... | D21{4,5}, D4{05,06,07,08,09,10}: Docstring sections checks.
Check the general format of a sectioned docstring:
'''This is my one-liner.
Short Summary
-------------
This is my summary.
Returns
-------
None.
'''
... |
19,836 | def import_key_pair(name, key, profile, key_type=None, **libcloud_kwargs):
s import_key_pair_from_xxx method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: bash
salt myminion libcloud_compute.import_key_pair pair1 key_value_data123 profile1
salt myminion libcloud_comput... | Import a new public key from string or a file path
:param name: Key pair name.
:type name: ``str``
:param key: Public key material, the string or a path to a file
:type key: ``str`` or path ``str``
:param profile: The profile key
:type profile: ``str``
:param key_type: The key pair typ... |
19,837 | def _skip_trampoline(handler):
data_event, self = (yield None)
delegate = handler
event = None
depth = 0
while True:
def pass_through():
_trans = delegate.send(Transition(data_event, delegate))
return _trans, _trans.delegate, _trans.event
if data_event i... | Intercepts events from container handlers, emitting them only if they should not be skipped. |
19,838 | def add_node(node, **kwds):
nodes._add_node_class_names([node.__name__])
for key, val in kwds.iteritems():
try:
visit, depart = val
except ValueError:
raise ValueError(
% key)
if key == :
from docutils.writers.htm... | add_node from Sphinx |
19,839 | def is_quote_artifact(orig_text, span):
res = False
cursor = re.finditer(r)[^ .,:;?!()*+-].*?("|\, orig_text)
for item in cursor:
if item.span()[1] == span[1]:
res = True
return res | Distinguish between quotes and units. |
19,840 | def process_raw_data(cls, raw_data):
properties = raw_data.get("properties", {})
raw_content = properties.get("ipConfiguration", None)
if raw_content is not None:
resource = Resource.from_raw_data(raw_content)
properties["ipConfiguration"] = resource
re... | Create a new model using raw API response. |
19,841 | def maybe_timeout_options(self):
if self._exit_timeout_start_time:
return NailgunProtocol.TimeoutOptions(self._exit_timeout_start_time, self._exit_timeout)
else:
return None | Implements the NailgunProtocol.TimeoutProvider interface. |
19,842 | def timestamp_datetime(self, timestamp):
format =
timestamp = time.localtime(timestamp)
return time.strftime(format, timestamp) | 将uninx时间戳转换为可读性的时间 |
19,843 | def get_memory_annotations(cls, exclude=None):
result = set()
annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__
exclude = () if exclude is None else exclude
for annotation_cls in annotations_in_memory:
if issubclass(anno... | Get annotations in memory which inherits from cls.
:param tuple/type exclude: annotation type(s) to exclude from search.
:return: found annotations which inherits from cls.
:rtype: set |
19,844 | def load_data_split(proc_data_dir):
ds_train = Dataset.load(path.join(proc_data_dir, ))
ds_val = Dataset.load(path.join(proc_data_dir, ))
ds_test = Dataset.load(path.join(proc_data_dir, ))
return ds_train, ds_val, ds_test | Loads a split dataset
Args:
proc_data_dir: Directory with the split and processed data
Returns:
(Training Data, Validation Data, Test Data) |
19,845 | def _build(self, inputs, is_training):
input_shape = tf.shape(inputs)
with tf.control_dependencies([
tf.Assert(tf.equal(input_shape[-1], self._embedding_dim),
[input_shape])]):
flat_inputs = tf.reshape(inputs, [-1, self._embedding_dim])
distances = (tf.reduce_sum(f... | Connects the module to some inputs.
Args:
inputs: Tensor, final dimension must be equal to embedding_dim. All other
leading dimensions will be flattened and treated as a large batch.
is_training: boolean, whether this connection is to training data.
Returns:
dict containing the follo... |
19,846 | def compute(self):
for varname in self.tendencies:
self.tendencies[varname] *= 0.
if not self.has_process_type_list:
self._build_process_type_list()
tendencies = {}
ignored = self._compute_type()
tendencies[] = self._compute_type()
... | Computes the tendencies for all state variables given current state
and specified input.
The function first computes all diagnostic processes. They don't produce
any tendencies directly but they may affect the other processes (such as
change in solar distribution). Subsequently, all ten... |
19,847 | def multiline_merge(lines, current_event, re_after, re_before):
events = []
for line in lines:
if re_before and re_before.match(line):
current_event.append(line)
elif re_after and current_event and re_after.match(current_event[-1]):
current_event.append(line)
... | Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match re_after, it will be merged with next line.
If a line match re_... |
19,848 | def from_dict(input_dict, data=None):
import GPy
m = GPy.core.model.Model.from_dict(input_dict, data)
from copy import deepcopy
sparse_gp = deepcopy(m)
return SparseGPClassification(sparse_gp.X, sparse_gp.Y, sparse_gp.Z, sparse_gp.kern, sparse_gp.likelihood, sparse_gp.i... | Instantiate an SparseGPClassification object using the information
in input_dict (built by the to_dict method).
:param data: It is used to provide X and Y for the case when the model
was saved using save_data=False in to_dict method.
:type data: tuple(:class:`np.ndarray`, :class:`np.... |
19,849 | def apply_new_global_variable_name(self, path, new_gv_name):
gv_name = self.list_store[path][self.NAME_STORAGE_ID]
if gv_name == new_gv_name or not self.global_variable_is_editable(gv_name, ):
return
data_value = self.model.global_variable_manager.get_representation(gv_name... | Change global variable name/key according handed string
Updates the global variable name only if different and already in list store.
:param path: The path identifying the edited global variable tree view row, can be str, int or tuple.
:param str new_gv_name: New global variable name |
19,850 | def get_template(self, context, **kwargs):
if in kwargs[]:
self.template = kwargs[][]
return super(GoscaleTemplateInclusionTag, self).get_template(context, **kwargs) | Returns the template to be used for the current context and arguments. |
19,851 | def capture_message(sock, get_channel=False):
try:
if get_channel:
if HAS_NATIVE_SUPPORT:
cf, addr = sock.recvfrom(CANFD_MTU)
channel = addr[0] if isinstance(addr, tuple) else addr
else:
data = ctypes.create_string_buffer(CANF... | Captures a message from given socket.
:param socket.socket sock:
The socket to read a message from.
:param bool get_channel:
Find out which channel the message comes from.
:return: The received message, or None on failure. |
19,852 | def on_connected(self, headers, body):
if in headers:
self.heartbeats = utils.calculate_heartbeats(
headers[].replace(, ).split(), self.heartbeats)
if self.heartbeats != (0, 0):
self.send_sleep = self.heartbeats[0] / 1000
... | Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real
heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats
are not 0, we start up the heartbeat loop accordingly.
:param dict headers: headers in t... |
19,853 | def merge_segments(filename, scan, cleanup=True, sizelimit=0):
workdir = os.path.dirname(filename)
fileroot = os.path.basename(filename)
candslist = glob.glob(os.path.join(workdir, + fileroot + + str(scan) + ))
noiselist = glob.glob(os.path.join(workdir, + fileroot + + str(scan) + ))
cands... | Merges cands/noise pkl files from multiple segments to single cands/noise file.
Expects segment cands pkls with have (1) state dict and (2) cands dict.
Writes tuple state dict and duple of numpy arrays
A single pkl written per scan using root name fileroot.
if cleanup, it will remove segments after mer... |
19,854 | def one_of(s):
@Parser
def one_of_parser(text, index=0):
if index < len(text) and text[index] in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, .format(s))
return one_of_parser | Parser a char from specified string. |
19,855 | def get_access_token(client_id, client_secret):
headers = {: }
payload = {
: client_id,
: client_secret
}
request = requests.post(token_url, data=payload, headers=headers)
if request.status_code == 200:
token = request.json()
return token
return {: request.status_code, "message": request.text} | Name: token
Parameters: client_id, client_secret
Return: dictionary |
19,856 | def type(self):
properties = {self.is_code: "code",
self.is_data: "data",
self.is_string: "string",
self.is_tail: "tail",
self.is_unknown: "unknown"}
for k, v in properties.items():
if k: return ... | return the type of the Line |
19,857 | def get_standard_form(self, data):
if self.synonym_map is None:
return data
from indic_transliteration import sanscript
return sanscript.transliterate(data=sanscript.transliterate(_from=self.name, _to=sanscript.DEVANAGARI, data=data), _from=sanscript.DEVANAGARI, _to=self.nam... | Roman schemes define multiple representations of the same devanAgarI character. This method gets a library-standard representation.
data : a text in the given scheme. |
19,858 | def currencyFormat(_context, code, symbol, format,
currency_digits=True, decimal_quantization=True,
name=):
_context.action(
discriminator=(, name, code),
callable=_register_currency,
args=(name, code, symbol, format, cur... | Handle currencyFormat subdirectives. |
19,859 | def is_locked(self):
if self.provider.lock_manager is None:
return False
return self.provider.lock_manager.is_url_locked(self.get_ref_url()) | Return True, if URI is locked. |
19,860 | def send_static_file(self, filename):
if self.config[] == :
abort(404)
theme_static_folder = getattr(self, , None)
if theme_static_folder:
try:
return send_from_directory(theme_static_folder, filename)
except NotFound:
... | Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object |
19,861 | def collect_hunt_results(self, hunt):
if not os.path.isdir(self.output_path):
os.makedirs(self.output_path)
output_file_path = os.path.join(
self.output_path, .join((self.hunt_id, )))
if os.path.exists(output_file_path):
print(.format(output_file_path))
return None
self... | Download current set of files in results.
Args:
hunt: The GRR hunt object to download files from.
Returns:
list: tuples containing:
str: human-readable description of the source of the collection. For
example, the name of the source host.
str: path to the collecte... |
19,862 | def _read_vector(ctx: ReaderContext) -> vector.Vector:
start = ctx.reader.advance()
assert start == "["
return _read_coll(ctx, vector.vector, "]", "vector") | Read a vector element from the input stream. |
19,863 | def make_tmp_name(name):
path, base = os.path.split(name)
tmp_base = ".tmp-%s-%s" % (base, uuid4().hex)
tmp_name = os.path.join(path, tmp_base)
try:
yield tmp_name
finally:
safe_remove(tmp_name) | Generates a tmp name for a file or dir.
This is a tempname that sits in the same dir as `name`. If it exists on
disk at context exit time, it is deleted. |
19,864 | def spendables_for_address(address, netcode, format=None):
if format:
method = "as_%s" % format
for m in service_provider_methods("spendables_for_address", get_default_providers_for_netcode(netcode)):
try:
spendables = m(address)
if format:
spendables... | Return a list of Spendable objects for the
given bitcoin address.
Set format to "text" or "dict" to transform return value
from an object to a string or dict.
This is intended to be a convenience function. There is no way to know that
the list returned is a complete list of spendables for the addr... |
19,865 | def _write_cdx_field(self, record, raw_file_record_size, raw_file_offset):
if record.fields[WARCRecord.WARC_TYPE] != WARCRecord.RESPONSE \
or not re.match(r,
record.fields[WARCRecord.CONTENT_TYPE]):
return
url = record.fields[]
_logger... | Write the CDX field if needed. |
19,866 | def ptmsiReallocationComplete():
a = TpPd(pd=0x3)
b = MessageType(mesType=0x11)
packet = a / b
return packet | P-TMSI REALLOCATION COMPLETE Section 9.4.8 |
19,867 | def sprand(m, n, density, format=):
m, n = int(m), int(n)
A = _rand_sparse(m, n, density, format=)
A.data = sp.rand(A.nnz)
return A.asformat(format) | Return a random sparse matrix.
Parameters
----------
m, n : int
shape of the result
density : float
target a matrix with nnz(A) = m*n*density, 0<=density<=1
format : string
sparse matrix format to return, e.g. 'csr', 'coo', etc.
Return
------
A : sparse matrix
... |
19,868 | def _verifyHostKey(self, hostKey, fingerprint):
if fingerprint in self.knownHosts:
return defer.succeed(True)
return defer.fail(UnknownHostKey(hostKey, fingerprint)) | Called when ssh transport requests us to verify a given host key.
Return a deferred that callback if we accept the key or errback if we
decide to reject it. |
19,869 | def add_extra_headers(self, sample_names):
if not sample_names:
return []
full_headers = list(self.orient_data[sample_names[0]].keys())
add_ons = []
for head in full_headers:
if head not in self.header_names:
add_ons.append((head, head))
... | If there are samples, add any additional keys they might use
to supplement the default headers.
Return the headers headers for adding, with the format:
[(header_name, header_display_name), ....] |
19,870 | def get_elb_names(self, region, config):
region_dict = config.get(, {}).get(region, {})
if not in region_dict:
elb_conn = boto.ec2.elb.connect_to_region(region,
**self.auth_kwargs)
full_elb... | :param region: name of a region
:param config: Collector config dict
:return: list of elb names to query in the given region |
19,871 | def send_login_code(self, code, context, **kwargs):
from_number = self.from_number or getattr(settings, )
sms_content = render_to_string(self.template_name, context)
self.twilio_client.messages.create(
to=code.user.phone_number,
from_=from_number,
bo... | Send a login code via SMS |
19,872 | def prune(self, root):
max_entries_per_target = self._max_entries_per_target
if os.path.isdir(root) and max_entries_per_target:
safe_rm_oldest_items_in_dir(root, max_entries_per_target) | Prune stale cache files
If the option --cache-target-max-entry is greater than zero, then prune will remove all but n
old cache files for each target/task.
:param str root: The path under which cacheable artifacts will be cleaned |
19,873 | def _decode_response(response):
content_type = response.headers.get(, )
logger.debug("status[%s] content_type[%s] encoding[%s]" %
(response.status_code, content_type, response.encoding))
response.raise_for_status()
content = response.content.strip()
if response.encoding:
... | Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code. |
19,874 | def command_drop_tables(self, meta_name=None):
answer = six.moves.input(u)
if answer.strip().lower()!=:
sys.exit()
def _drop_metadata_tables(metadata):
table = next(six.itervalues(metadata.tables), None)
if table is None:
print()
... | Drops all tables without dropping a database::
./manage.py sqla:drop_tables [meta_name] |
19,875 | def rewrite_return_as_assignments(func_node, interface):
func_node = _RewriteReturn(interface).visit(func_node)
ast.fix_missing_locations(func_node)
return func_node | Modify FunctionDef node to directly assign instead of return. |
19,876 | def _peer_get_bfd(self, tx, rx, multiplier):
tx = self._callback(tx, handler=)
rx = self._callback(rx, handler=)
multiplier = self._callback(multiplier, handler=)
tx = pynos.utilities.return_xml(str(tx))
rx = pynos.utilities.return_xml(str(rx))
multiplier = pynos... | Get and merge the `bfd` config from global BGP.
You should not use this method.
You probably want `BGP.bfd`.
Args:
tx: XML document with the XML to get the transmit interval.
rx: XML document with the XML to get the receive interval.
multiplier: XML document... |
19,877 | def enable_performance_data(self):
if not self.my_conf.process_performance_data:
self.my_conf.modified_attributes |= \
DICT_MODATTR["MODATTR_PERFORMANCE_DATA_ENABLED"].value
self.my_conf.process_performance_data = True
self.my_conf.explode_global_conf... | Enable performance data processing (globally)
Format of the line that triggers function call::
ENABLE_PERFORMANCE_DATA
:return: None |
19,878 | def wait(self, seconds=None, **kw):
self._heartbeat_thread.hurry()
self._transport.set_timeout(seconds=1)
warning_screen = self._yield_warning_screen(seconds)
for elapsed_time in warning_screen:
if self._should_stop_waiting(**kw):
... | Wait in a loop and react to events as defined in the namespaces |
19,879 | def _align_orthologous_gene_pairwise(self, g_id, gapopen=10, gapextend=0.5, engine=, parse=True, force_rerun=False):
protein_seqs_aln_pickle_path = op.join(self.sequences_by_gene_dir, .format(g_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=protein_seqs_aln_pickle_path):
... | Align orthologous strain sequences to representative Protein sequence, save as new pickle |
19,880 | def next_requests(self):
use_set = self.settings.getbool(, defaults.START_URLS_AS_SET)
fetch_one = self.server.spop if use_set else self.server.lpop
found = 0
while found < self.redis_batch_size:
data = fetch_one(self.redis_key)
if not d... | Returns a request to be scheduled or none. |
19,881 | def return_rri(self, begsam, endsam):
interval = endsam - begsam
dat = empty(interval)
k = 0
with open(self.filename, ) as f:
[next(f) for x in range(12)]
for j, datum in enumerate(f):
if begsam <... | Return raw, irregularly-timed RRI. |
19,882 | def dumps(self, msg, use_bin_type=False):
strbytes
def ext_type_encoder(obj):
if isinstance(obj, six.integer_types):
return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(
obj.strftime()))
... | Run the correct dumps serialization format
:param use_bin_type: Useful for Python 3 support. Tells msgpack to
differentiate between 'str' and 'bytes' types
by encoding them differently.
Since this changes the wire protocol, ... |
19,883 | def convert_meas_df_thellier_gui(meas_df_in, output):
output = int(output)
meas_mapping = get_thellier_gui_meas_mapping(meas_df_in, output)
meas_df_out = meas_df_in.rename(columns=meas_mapping)
if not in meas_df_out.columns:
meas_df_out[] = meas_df_in[]
return meas_df_out | Take a measurement dataframe and convert column names
from MagIC 2 --> 3 or vice versa.
Use treat_step_num --> measurement_number if available,
otherwise measurement --> measurement_number.
Parameters
----------
meas_df_in : pandas DataFrame
input dataframe with measurement data
out... |
19,884 | def _ScheduleTasks(self, storage_writer):
logger.debug()
self._status = definitions.STATUS_INDICATOR_RUNNING
event_source_heap = _EventSourceHeap()
self._FillEventSourceHeap(
storage_writer, event_source_heap, start_with_first=True)
event_source = event_source_heap.... | Schedules tasks.
Args:
storage_writer (StorageWriter): storage writer for a session storage. |
19,885 | def set_order(self, order):
m = gtk.ListStore(bool, str)
for item in order:
m.append(
(item[], item[])
)
self.set_model(m) | Takes a list of dictionaries. Those correspond to the arguments of
`list.sort` and must contain the keys 'key' and 'reverse' (a boolean).
You must call `set_labels` before this! |
19,886 | def index(self, x, x_link=None):
if x is None:
raise ValueError("provide at least one dataframe")
elif x_link is not None:
x = (x, x_link)
elif isinstance(x, (list, tuple)):
x = tuple(x)
else:
x = (x,)
if self.veri... | Make an index of record pairs.
Use a custom function to make record pairs of one or two dataframes.
Each function should return a pandas.MultiIndex with record pairs.
Parameters
----------
x: pandas.DataFrame
A pandas DataFrame. When `x_link` is None, the algorithm ... |
19,887 | def eval_objfn(self):
dfd = self.obfn_dfd()
reg = self.obfn_reg()
obj = dfd + reg[0]
return (obj, dfd) + reg[1:] | Compute components of objective function as well as total
contribution to objective function. |
19,888 | def compare_baselines(old_baseline_filename, new_baseline_filename):
if old_baseline_filename == new_baseline_filename:
raise RedundantComparisonError
old_baseline = _get_baseline_from_file(old_baseline_filename)
new_baseline = _get_baseline_from_file(new_baseline_filename)
_remove_nonexi... | This function enables developers to more easily configure plugin
settings, by comparing two generated baselines and highlighting
their differences.
For effective use, a few assumptions are made:
1. Baselines are sorted by (filename, line_number, hash).
This allows for a deterministic ord... |
19,889 | def get_tablenames(cur):
cur.execute("SELECT name FROM sqlite_master WHERE type=")
tablename_list_ = cur.fetchall()
tablename_list = [str(tablename[0]) for tablename in tablename_list_ ]
return tablename_list | Conveinience: |
19,890 | def changeLocalUserPassword(self, login, user, password):
self.send_changeLocalUserPassword(login, user, password)
self.recv_changeLocalUserPassword() | Parameters:
- login
- user
- password |
19,891 | def text_fd_to_metric_families(fd):
name = None
allowed_names = []
eof = False
seen_metrics = set()
def build_metric(name, documentation, typ, unit, samples):
if name in seen_metrics:
raise ValueError("Duplicate metric: " + name)
seen_metrics.add(name)
if t... | Parse Prometheus text format from a file descriptor.
This is a laxer parser than the main Go parser,
so successful parsing does not imply that the parsed
text meets the specification.
Yields Metric's. |
19,892 | def schedule_host_check(self, host, check_time):
host.schedule(self.daemon.hosts, self.daemon.services,
self.daemon.timeperiods, self.daemon.macromodulations,
self.daemon.checkmodulations, self.daemon.checks,
force=False, force_time=chec... | Schedule a check on a host
Format of the line that triggers function call::
SCHEDULE_HOST_CHECK;<host_name>;<check_time>
:param host: host to check
:type host: alignak.object.host.Host
:param check_time: time to check
:type check_time:
:return: None |
19,893 | def delete_quick(self, get_count=False):
query = + self.full_table_name + self.where_clause
self.connection.query(query)
count = self.connection.query("SELECT ROW_COUNT()").fetchone()[0] if get_count else None
self._log(query[:255])
return count | Deletes the table without cascading and without user prompt.
If this table has populated dependent tables, this will fail. |
19,894 | def convert_coord(coord_from,matrix_file,base_to_aligned=True):
with open(matrix_file) as f:
try:
values = [float(y) for y in .join([x for x in f.readlines() if x.strip()[0]!=]).strip().split()]
except:
nl.notify( % matrix_file, level=nl.level.error)
return F... | Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False`` |
19,895 | def query(self, query_dict: Dict[str, Any]) -> None:
self.parse_url.query = cast(Any, query_dict) | 重写 query |
19,896 | async def list(self, *, filters: Mapping = None) -> List[Mapping]:
params = {"filters": clean_filters(filters)}
response = await self.docker._query_json(
"services", method="GET", params=params
)
return response | Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
name=<service name> |
19,897 | def create_project(type, schema, server, name, output, verbose):
if verbose:
log("Entity Matching Server: {}".format(server))
if schema is not None:
schema_json = json.load(schema)
clkhash.schema.validate_schema_dict(schema_json)
else:
raise ValueError("Schema ... | Create a new project on an entity matching server.
See entity matching service documentation for details on mapping type and schema
Returns authentication details for the created project. |
19,898 | def create_weather(self, **kwargs):
weather = predix.admin.weather.WeatherForecast(**kwargs)
weather.create()
client_id = self.get_client_id()
if client_id:
weather.grant_client(client_id)
weather.grant_client(client_id)
weather.add_to_manifest(self... | Creates an instance of the Asset Service. |
19,899 | def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE):
logging.info(u"Downloading: %s to: %s", file_obj.urn, target_path)
target_file = open(target_path, "wb")
file_obj.Seek(0)
count = 0
data_buffer = file_obj.Read(buffer_size)
while data_buffer:
target_file.write(data_buffer)
data_b... | Download an aff4 file to the local filesystem overwriting it if it exists.
Args:
file_obj: An aff4 object that supports the file interface (Read, Seek)
target_path: Full path of file to write to.
buffer_size: Read in chunks this size. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.