Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
18,600 | def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg):
info = []
if error_object != "unknown":
info.append("obj=" + error_object)
if error_subject != "unknown":
info.append("subject=" + error_subject)
if msg.strip():
info.append("msg=" + ms... | Auxiliary method. It overrides the default xmlsec debug message. |
18,601 | def set_metadata(self, obj, metadata, clear=False, prefix=None):
if prefix is None:
prefix = OBJECT_META_PREFIX
massaged = _massage_metakeys(metadata, prefix)
cname = utils.get_name(self.container)
oname = utils.get_name(obj)
new_meta = {}
... | Accepts a dictionary of metadata key/value pairs and updates the
specified object metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the object's metadata.
By default, the s... |
18,602 | def get_library(path=None, root=None, db=None):
import ambry.library as _l
rc = config(path=path, root=root, db=db )
return _l.new_library(rc) | Return the default library for this installation. |
18,603 | def _cache_ops_associate(protocol, msgtype):
ops = cache_ops
while ops:
if ops.co_protocol == protocol:
for co_msgtype in ops.co_msgtypes:
if co_msgtype.mt_id == msgtype:
return ops
ops = ops.co_next
return None | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L111.
Positional arguments:
protocol -- Netlink protocol (integer).
msgtype -- Netlink message type (integer).
Returns:
nl_cache_ops instance with matching protocol containing matching msgtype or None. |
18,604 | def set_position(self, key, latlon, layer=None, rotation=0):
self.object_queue.put(SlipPosition(key, latlon, layer, rotation)) | move an object on the map |
18,605 | def _check_accept_keywords(approved, flag):
if flag in approved:
return False
elif (flag.startswith() and flag[1:] in approved) \
or (+flag in approved):
return False
else:
return True | check compatibility of accept_keywords |
18,606 | def _get_gpu():
system = platform.system()
if system == "Linux":
libcudart = ct.cdll.LoadLibrary("libcudart.so")
elif system == "Darwin":
libcudart = ct.cdll.LoadLibrary("libcudart.dylib")
elif system == "Windows":
libcudart = ct.windll.LoadLibrary("libcudart.dll")
else:
raise NotImpleme... | *DEPRECATED*. Allocates first available GPU using cudaSetDevice(), or returns 0 otherwise. |
18,607 | def _is_contiguous(positions):
previous = positions[0]
for current in positions[1:]:
if current != previous + 1:
return False
previous = current
return True | Given a non-empty list, does it consist of contiguous integers? |
18,608 | def merge_overlaps(self, threshold=0.0):
updated_labels = []
all_intervals = self.label_tree.copy()
def recursive_overlaps(interval):
range_start = interval.begin - threshold
range_end = interval.end + threshold
direct_overlaps = all_inter... | Merge overlapping labels with the same value.
Two labels are considered overlapping,
if ``l2.start - l1.end < threshold``.
Args:
threshold (float): Maximal distance between two labels
to be considered as overlapping.
(def... |
18,609 | def polite_string(a_string):
if is_py3() and hasattr(a_string, ):
try:
return a_string.decode()
except UnicodeDecodeError:
return a_string
return a_string | Returns a "proper" string that should work in both Py3/Py2 |
18,610 | def _get_block_matches(self, attributes_a, attributes_b, filter_set_a=None, filter_set_b=None, delta=(0, 0, 0),
tiebreak_with_block_similarity=False):
if filter_set_a is None:
filtered_attributes_a = {k: v for k, v in attributes_a.items()}
else:
... | :param attributes_a: A dict of blocks to their attributes
:param attributes_b: A dict of blocks to their attributes
The following parameters are optional.
:param filter_set_a: A set to limit attributes_a to the blocks in this set.
:param filter_set_b: A set to limit attribu... |
18,611 | def openflow_controller_connection_address_connection_method(self, **kwargs):
config = ET.Element("config")
openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow")
controller_name_key = ET.SubElement(openflow_controller, "control... | Auto Generated Code |
18,612 | def patch(self, nml_patch):
for sec in nml_patch:
if sec not in self:
self[sec] = Namelist()
self[sec].update(nml_patch[sec]) | Update the namelist from another partial or full namelist.
This is different from the intrinsic `update()` method, which replaces
a namelist section. Rather, it updates the values within a section. |
18,613 | def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
_check_x(x)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueError("Number of input examples and labels do not match.")
factory = _CorrectFactory(model, attack, attack_params)
... | Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: ... |
18,614 | def request(self, path, method=, params=None):
if params is None: params = {}
url = urljoin(self.endpoint, path)
headers = {
: ,
: + self.access_key,
: self.user_agent,
:
}
if method == :
response = requests... | Builds a request and gets a response. |
18,615 | def clean_password(self, password, user=None):
min_length = app_settings.PASSWORD_MIN_LENGTH
if min_length and len(password) < min_length:
raise forms.ValidationError(_("Password must be a minimum of {0} "
"characters.").format(min_length))
... | Validates a password. You can hook into this if you want to
restric the allowed password choices. |
18,616 | def status_codes_by_date_stats():
def date_counter(queryset):
return dict(Counter(map(
lambda dt: ms_since_epoch(datetime.combine(
make_naive(dt), datetime.min.time())),
list(queryset.values_list(, flat=True)))))
codes = {low: date_counter(
RequestL... | Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. |
18,617 | def _write_frames(self, handle):
assert handle.tell() == 512 * (self.header.data_block - 1)
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_dtype = [np.int16, np.float32][is_float]
point_scale = [scale, 1][is_float]
point_format = [is_float]
... | Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. |
18,618 | def auto(cls, syslog=None, stderr=None, level=None, extended=None,
server=None):
level = norm_level(level) or logging.INFO
if syslog is None and stderr is None:
if sys.stderr.isatty() or syslog_path() is None:
log.info()
syslog, stderr = ... | Tries to guess a sound logging configuration. |
18,619 | def trace_buffer_capacity(self):
cmd = enums.JLinkTraceCommand.GET_CONF_CAPACITY
data = ctypes.c_uint32(0)
res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
if (res == 1):
raise errors.JLinkException()
return data.value | Retrieves the trace buffer's current capacity.
Args:
self (JLink): the ``JLink`` instance.
Returns:
The current capacity of the trace buffer. This is not necessarily
the maximum possible size the buffer could be configured with. |
18,620 | def keyrelease(self, data):
try:
window = self._get_front_most_window()
except (IndexError,):
window = self._get_any_window()
key_release_action = KeyReleaseAction(window, data)
return 1 | Release key. NOTE: keypress should be called before this
@param data: data to type.
@type data: string
@return: 1 on success.
@rtype: integer |
18,621 | def SRem(a: BitVec, b: BitVec) -> BitVec:
return _arithmetic_helper(a, b, z3.SRem) | Create a signed remainder expression.
:param a:
:param b:
:return: |
18,622 | def store_node_label_meta(self, x, y, tx, ty, rot):
self.node_label_coords["x"].append(x)
self.node_label_coords["y"].append(y)
self.node_label_coords["tx"].append(tx)
self.node_label_coords["ty"].append(ty)
if x == 0:
self.node_label_alig... | This function stored coordinates-related metadate for a node
This function should not be called by the user
:param x: x location of node label or number
:type x: np.float64
:param y: y location of node label or number
:type y: np.float64
:param tx: text location x of n... |
18,623 | def _mulf16(ins):
op1, op2 = tuple(ins.quad[2:])
if _f_ops(op1, op2) is not None:
op1, op2 = _f_ops(op1, op2)
if op2 == 1:
output = _f16_oper(op1)
output.append()
output.append()
return output
if op2 == -1:
return _neg... | Multiplies 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack. |
18,624 | def scan(self,
proxy_scanner,
expected_num=20,
val_thr_num=4,
queue_timeout=3,
val_timeout=5,
out_file=):
try:
proxy_scanner.scan()
self.logger.info(
.format(val_thr_num))
... | Scan and validate proxies
Firstly, call the `scan` method of `proxy_scanner`, then using multiple
threads to validate them.
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
val_thr_num: Number of threads us... |
18,625 | def identify_misfeatured_regions(st, filter_size=5, sigma_cutoff=8.):
r = st.residuals
weights = np.ones([filter_size]*len(r.shape), dtype=)
weights /= weights.sum()
f = np.sqrt(nd.filters.convolve(r*r, weights, mode=))
if sigma_cutoff == :
max_ok = initializers.otsu_threshol... | Identifies regions of missing/misfeatured particles based on the
residuals' local deviation from uniform Gaussian noise.
Parameters
----------
st : :class:`peri.states.State`
The state in which to identify mis-featured regions.
filter_size : Int, best if odd.
The size of the filter... |
18,626 | def _put (self, url_data):
if self.shutdown or self.max_allowed_urls == 0:
return
log.debug(LOG_CACHE, "queueing %s", url_data.url)
key = url_data.cache_url
cache = url_data.aggregate.result_cache
if url_data.has_result or cache.has_result(key):
s... | Put URL in queue, increase number of unfished tasks. |
18,627 | def _abs_pow_ufunc(self, fi, out, p):
if p == 0.5:
fi.ufuncs.absolute(out=out)
out.ufuncs.sqrt(out=out)
elif p == 2.0 and self.base_space.field == RealNumbers():
fi.multiply(fi, out=out)
else:
fi.ufuncs.absolute(out=out)
... | Compute |F_i(x)|^p point-wise and write to ``out``. |
18,628 | def get_user_invitation_by_id(self, id):
return self.db_adapter.get_object(self.UserInvitationClass, id=id) | Retrieve a UserInvitation object by ID. |
18,629 | def parse_bibliography(source, loc, tokens):
bib = structures.Bibliography()
for entry in tokens:
bib.add(entry)
return bib | Combines the parsed entries into a Bibliography instance. |
18,630 | def push(self, values: np.ndarray):
n = len(values)
if len(self) + n > self.size:
raise ValueError("Too much data to push to RingBuffer")
slide_1 = np.s_[self.right_index:min(self.right_index + n, self.size)]
slide_2 = np.s_[:max(self.right_index + n - self.size, 0)... | Push values to buffer. If buffer can't store all values a ValueError is raised |
18,631 | def get_pplan(self, topologyName, callback=None):
isWatching = False
ret = {
"result": None
}
if callback:
isWatching = True
else:
def callback(data):
ret["result"] = data
self._get_pplan_with_watch(topologyName, callback, isWatching)
... | get physical plan |
18,632 | async def _watch(self, node, conn, names):
"Watches the values at keys ``names``"
for name in names:
slot = self._determine_slot(, name)
dist_node = self.connection_pool.get_node_by_slot(slot)
if node.get() != dist_node[]:
if len(node)... | Watches the values at keys ``names`` |
18,633 | def _process_worker(call_queue, result_queue):
while True:
call_item = call_queue.get(block=True)
if call_item is None:
result_queue.put(None)
return
try:
r = call_item.fn(*call_item.args, **call_item.kwargs)
except BaseException:... | Evaluates calls from call_queue and places the results in result_queue.
This worker is run in a separate process.
Args:
call_queue: A multiprocessing.Queue of _CallItems that will be read and
evaluated by the worker.
result_queue: A multiprocessing.Queue of _ResultItems that will w... |
18,634 | def get_template(self, template, def_name=None):
try:
return MakoTemplateAdapter(self.get_mako_template(template), def_name)
except (TopLevelLookupException, TemplateLookupException) as e:
tdne = TemplateDoesNotExist( % (template, self.template_search_dirs... | Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper around it so you can use it the same as any Django template.
... |
18,635 | def load(name):
global __tile_maps
TileMapManager.unload()
TileMapManager.active_map = __tile_maps[name]
TileMapManager.active_map.parse_tilemap()
TileMapManager.active_map.parse_collisions()
TileMapManager.active_map.parse_objects()
world = Ra... | Parse the tile map and add it to the world. |
18,636 | def on_error(self, ex):
if self._d:
self._d.errback()
self._d = None | Reimplemented from :meth:`~AsyncViewBase.on_error` |
18,637 | def init(self, request, paypal_request, paypal_response):
if request is not None:
from paypal.pro.helpers import strip_ip_port
self.ipaddress = strip_ip_port(request.META.get(, ))
if (hasattr(request, "user") and request.user.is_authenticated):
self.u... | Initialize a PayPalNVP instance from a HttpRequest. |
18,638 | def _default_template_args(self, content_template):
def include(text, args):
template_name = pystache.render(text, args)
return self._renderer.render_name(template_name, args)
ret = {: content_template}
ret[] = lambda text: include(text, ret)
return ret | Initialize template args. |
18,639 | def to_sequence_field(cls):
class SequenceConverter(object):
def __init__(self, cls):
self._cls = cls
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, values):
values = values or []
args = [to_model(se... | Returns a callable instance that will convert a value to a Sequence.
:param cls: Valid class type of the items in the Sequence.
:return: instance of the SequenceConverter. |
18,640 | def _queue_declare_ok(self, args):
queue = args.read_shortstr()
message_count = args.read_long()
consumer_count = args.read_long()
return queue, message_count, consumer_count | confirms a queue definition
This method confirms a Declare method and confirms the name of
the queue, essential for automatically-named queues.
PARAMETERS:
queue: shortstr
Reports the name of the queue. If the server generated
a queue name, this fie... |
18,641 | def extract(code, tree, prefix=[]):
if isinstance(tree, list):
l, r = tree
prefix.append()
extract(code, l, prefix)
prefix.pop()
prefix.append()
extract(code, r, prefix)
prefix.pop()
else:
code[tree] = .join(prefix) | Extract Huffman code from a Huffman tree
:param tree: a node of the tree
:param prefix: a list with the 01 characters encoding the path from
the root to the node `tree`
:complexity: O(n) |
18,642 | def objects_copy(self, source_bucket, source_key, target_bucket, target_key):
url = Api._ENDPOINT + (Api._OBJECT_COPY_PATH % (source_bucket, Api._escape_key(source_key),
target_bucket, Api._escape_key(target_key)))
return datalab.utils.Http.request(url, m... | Updates the metadata associated with an object.
Args:
source_bucket: the name of the bucket containing the source object.
source_key: the key of the source object being copied.
target_bucket: the name of the bucket that will contain the copied object.
target_key: the key of the copied objec... |
18,643 | def add(self, actors):
if utils.isSequence(actors):
for a in actors:
if a not in self.actors:
self.actors.append(a)
return None
else:
self.actors.append(actors)
return actors | Append input object to the internal list of actors to be shown.
:return: returns input actor for possible concatenation. |
18,644 | def remove_highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]]=None) -> None:
for node in graph if nodes is None else nodes:
if is_node_highlighted(graph, node):
del graph.node[node][NODE_HIGHLIGHT] | Removes the highlight from the given nodes, or all nodes if none given.
:param graph: A BEL graph
:param nodes: The list of nodes to un-highlight |
18,645 | def _strip_postfix(req):
match = re.search(r, req)
if match:
req = match.group(1)
return req | Strip req postfix ( -dev, 0.2, etc ) |
18,646 | def _process_resp(request_id, response, is_success_func):
if response.status != 200:
raise DataFailureException(request_id,
response.status,
response.reason
)
if response.data is None:
r... | :param request_id: campus url identifying the request
:param response: the GET method response object
:param is_success_func: the name of the function for
verifying a success code
:return: True if successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if t... |
18,647 | def shlex_quote(s):
if is_py3: | Return a shell-escaped version of the string *s*.
Backported from Python 3.3 standard library module shlex. |
18,648 | def register_dataset(self,
dataset,
expr,
deltas=None,
checkpoints=None,
odo_kwargs=None):
expr_data = ExprData(
expr,
deltas,
checkpoints,
... | Explicitly map a datset to a collection of blaze expressions.
Parameters
----------
dataset : DataSet
The pipeline dataset to map to the given expressions.
expr : Expr
The baseline values.
deltas : Expr, optional
The deltas for the data.
... |
18,649 | def needs_to_auth(self, dbname):
log_debug("Checking if server needs to auth on db ...." %
(self.id, dbname))
try:
client = self.get_mongo_client()
db = client.get_database(dbname)
db.collection_names()
result = False
e... | Determines if the server needs to authenticate to the database.
NOTE: we stopped depending on is_auth() since its only a configuration
and may not be accurate |
18,650 | def dataset(directory, images_file, labels_file):
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
image = tf.decode_raw(image, tf.uint8)
image = ... | Download and parse MNIST dataset. |
18,651 | def dt_cluster(dt_list, dt_thresh=16.0):
if not isinstance(dt_list[0], float):
o_list = dt2o(dt_list)
else:
o_list = dt_list
o_list_sort = np.sort(o_list)
o_list_sort_idx = np.argsort(o_list)
d = np.diff(o_list_sort)
b = np.nonzero(d > dt_thresh)[0] + 1
b... | Find clusters of similar datetimes within datetime list |
18,652 | def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=.0, dx_max=.0,
check_callable=False, check_indexing=False, **kwargs):
jac = _ensure_5args(jac)
if check_callable:
_check_callable(rhs, jac, x0, y0)
if check_indexing:
_check_indexing(rhs, jac, x0... | Integrates a system of ordinary differential equations.
Parameters
----------
rhs: callable
Function with signature f(t, y, fout) which modifies fout *inplace*.
jac: callable
Function with signature j(t, y, jmat_out, dfdx_out) which modifies
jmat_out and dfdx_out *inplace*.
... |
18,653 | def clone(self):
args = {k: getattr(self, k) for k in self.CLONE_ATTRS}
args[] = copy.copy(self.color_list)
return self.__class__([], **args) | Return an independent copy of this layout with a completely separate
color_list and no drivers. |
18,654 | def DirEntryScanner(**kw):
kw[] = SCons.Node.FS.Entry
kw[] = None
return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) | Return a prototype Scanner instance for "scanning"
directory Nodes for their in-memory entries |
18,655 | def build_single(scheme_file, templates, base_output_dir):
scheme = get_yaml_dict(scheme_file)
scheme_slug = slugify(scheme_file)
format_scheme(scheme, scheme_slug)
scheme_name = scheme[]
print(.format(scheme_name))
for temp_group in templates:
for _, sub in temp_group.templates.i... | Build colorscheme for a single $scheme_file using all TemplateGroup
instances in $templates. |
18,656 | def __create_db_and_container(self):
db_id = self.config.database
container_name = self.config.container
self.db = self.__get_or_create_database(self.client, db_id)
self.container = self.__get_or_create_container(
self.client, container_name
) | Call the get or create methods. |
18,657 | def get(self, sid):
return EventContext(self._version, workspace_sid=self._solution[], sid=sid, ) | Constructs a EventContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext |
18,658 | def metadata_add_description(self):
service_description = {}
if (self.args.json):
service_description = json.loads(self.args.json)
if (self.args.url):
if "url" in service_description:
raise Exception("json service description already contains url ... | Metadata: add description |
18,659 | def parse_subdomain_missing_zonefiles_record(cls, rec):
txt_entry = rec[]
if isinstance(txt_entry, list):
raise ParseError("TXT entry too long for a missing zone file list")
try:
return [int(i) for i in txt_entry.split()] if txt_entry is not None and len(txt_ent... | Parse a missing-zonefiles vector given by the domain.
Returns the list of zone file indexes on success
Raises ParseError on unparseable records |
18,660 | def json2value(json_string, params=Null, flexible=False, leaves=False):
if not is_text(json_string):
Log.error("only unicode json accepted")
try:
if flexible:
json_string = re.sub(r"\"\"\".*?\"\"\"", r"\n", json_string, flags=re.MULTILINE)
... | :param json_string: THE JSON
:param params: STANDARD JSON PARAMS
:param flexible: REMOVE COMMENTS
:param leaves: ASSUME JSON KEYS ARE DOT-DELIMITED
:return: Python value |
18,661 | def validate(instance, schema, cls=None, *args, **kwargs):
if cls is None:
cls = validator_for(schema)
cls.check_schema(schema)
cls(schema, *args, **kwargs).validate(instance) | Validate an instance under the given schema.
>>> validate([2, 3, 4], {"maxItems" : 2})
Traceback (most recent call last):
...
ValidationError: [2, 3, 4] is too long
:func:`validate` will first verify that the provided schema is itself
valid, since not doing so can lead to l... |
18,662 | def param_changed_to(self, key, to_value, from_value=None):
last_value = getattr(self.last_manifest, key)
current_value = self.current_manifest.get(key)
if from_value is not None:
return last_value == from_value and current_value == to_value
return last_value != to_v... | Returns true if the given parameter, with name key, has transitioned to the given value. |
18,663 | def main(args):
EXNAME = os.path.basename(__file__ if WIN32 else sys.argv[0])
for ext in (".py", ".pyc", ".exe", "-script.py", "-script.pyc"):
if EXNAME.endswith(ext):
EXNAME = EXNAME[:-len(ext)]
break
USAGE = % {"exname": EXNAME}
HELP = % {"exname": EXNA... | Entrypoint of the whole commandline application |
18,664 | def create(cls, name, engines, policy=None, comment=None, **kwargs):
json = {
: name,
: [eng.href for eng in engines],
: policy.href if policy is not None else policy,
: comment}
if kwargs:
json.update(policy_validation_settin... | Create a new validate policy task.
If a policy is not specified, the engines existing policy will
be validated. Override default validation settings as kwargs.
:param str name: name of task
:param engines: list of engines to validate
:type engines: list(Engine)
:... |
18,665 | def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
return self._query(f, ) | Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/d... |
18,666 | def get_time_objects_from_model_timesteps(cls, times, start):
modelTimestep = []
newtimes = []
for i in xrange(0, len(times)):
try:
modelTimestep.append(times[i+1] - times[i])
except StandardError:
modelTimestep.append(times[i] - ... | Calculate the datetimes of the model timesteps
times should start at 0 and be in seconds |
18,667 | def legend_title_header_element(feature, parent):
_ = feature, parent
header = legend_title_header[]
return header.capitalize() | Retrieve legend title header string from definitions. |
18,668 | def _drop_indices(self):
self._logger.info()
self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL)
self._logger.info() | Drops the database indices relating to n-grams. |
18,669 | def run():
parser = OptionParser(
version=__version__, description=__doc__,
)
parser.add_option(
, , dest=,
help=,
)
parser.add_option(
, , dest=, default=,
choices=[, ],
help=,
)
parser.add_option(
, , dest=, action=,
h... | Command for reflection database objects |
18,670 | def monthly_build_list_regex(self):
return r % {
: self.date.year,
: str(self.date.month).zfill(2)} | Return the regex for the folder containing builds of a month. |
18,671 | def execute(self, conn, block_name, origin_site_name, transaction=False):
if not conn:
dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Block/UpdateStatus. \
Expects db connection from upper layer.", self.logger.exception)
binds = {"block_name": block_name, "origin_si... | Update origin_site_name for a given block_name |
18,672 | def echo_warnings_via_pager(warnings: List[WarningTuple], sep: str = ) -> None:
if not warnings:
click.echo()
sys.exit(0)
max_line_width = max(
len(str(exc.line_number))
for _, exc, _ in warnings
)
max_warning_width = max(
len(exc.__class__.__name__)
... | Output the warnings from a BEL graph with Click and the system's pager. |
18,673 | def create_matcher(dispatcher, parsers, apptags, matcher=, hosts=tuple(), time_range=None,
time_period=(None, None), patterns=tuple(), invert=False, count=False,
files_with_match=None, max_count=0, only_matching=False, quiet=False,
thread=False, name_cache=None):... | Create a matcher engine.
:return: A matcher function. |
18,674 | def set_password(self, service, username, password):
password = self._encrypt(password or )
keyring_working_copy = copy.deepcopy(self._keyring)
service_entries = keyring_working_copy.get(service)
if not service_entries:
service_entries = {}
keyring_workin... | Set password for the username of the service |
18,675 | def _add_child(self, collection, set, child):
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
if added:
self._children_reset() | Adds 'child' to 'collection', first checking 'set' to see if it's
already present. |
18,676 | def resolve_inputs(self, layers):
resolved = {}
for name, shape in self._input_shapes.items():
if shape is None:
name, shape = self._resolve_shape(name, layers)
resolved[name] = shape
self._input_shapes = resolved | Resolve the names of inputs for this layer into shape tuples.
Parameters
----------
layers : list of :class:`Layer`
A list of the layers that are available for resolving inputs.
Raises
------
theanets.util.ConfigurationError :
If an input cannot ... |
18,677 | def _document_structure(self):
logger.debug("Documenting dataset structure")
key = self.get_structure_key()
text = json.dumps(self._structure_parameters, indent=2, sort_keys=True)
self.put_text(key, text)
key = self.get_dtool_readme_key()
self.put_text(key, self... | Document the structure of the dataset. |
18,678 | def ip_address_list(ips):
try:
return ip_address(ips)
except ValueError:
pass
return list(ipaddress.ip_network(u(ips)).hosts()) | IP address range validation and expansion. |
18,679 | def cov_error(self, comp_cov, score_metric="frobenius"):
if not isinstance(self.precision_, list):
return _compute_error(
comp_cov, self.covariance_, self.precision_, score_metric
)
path_errors = []
for lidx, lam in enumerate(self.path_):
... | Computes the covariance error vs. comp_cov.
May require self.path_
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normally be the test sample covariance/precision.
scaling : bool
... |
18,680 | def _get_trailing_whitespace(marker, s):
suffix =
start = s.index(marker) + len(marker)
i = start
while i < len(s):
if s[i] in :
suffix += s[i]
elif s[i] in :
suffix += s[i]
if s[i] == and i + 1 < len(s) and s[i + 1] == :
suffix ... | Return the whitespace content trailing the given 'marker' in string 's',
up to and including a newline. |
18,681 | async def ehlo(self, from_host=None):
if from_host is None:
from_host = self.fqdn
code, message = await self.do_cmd("EHLO", from_host)
self.last_ehlo_response = (code, message)
extns, auths = SMTP.parse_esmtp_extensions(message)
self.esmtp_extensions = ext... | Sends a SMTP 'EHLO' command. - Identifies the client and starts the
session.
If given ``from`_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host (str or None): Name to use to identify the client.
... |
18,682 | def get_identity(identity):
if isinstance(identity, AnonymousUser):
return identity, None
if isinstance(identity, get_user_model()):
return identity, None
elif isinstance(identity, Group):
return None, identity
else:
raise NotUserNorGroup(
... | Returns a (user_obj, None) tuple or a (None, group_obj) tuple depending on the considered
instance. |
18,683 | def template_filter(self, param=None):
def deco(func):
name = param or func.__name__
self.filters[name] = func
return func
return deco | Returns a decorator that adds the wrapped function to dictionary of template filters.
The wrapped function is keyed by either the supplied param (if supplied)
or by the wrapped functions name.
:param param: Optional name to use instead of the name of the function to be wrapped
:return:... |
18,684 | def put(self, request, bot_id, id, format=None):
return super(TelegramChatStateDetail, self).put(request, bot_id, id, format) | Update existing Telegram chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
18,685 | def add_schema(self, database, schema):
self.schemas.add((_lower(database), _lower(schema))) | Add a schema to the set of known schemas (case-insensitive)
:param str database: The database name to add.
:param str schema: The schema name to add. |
18,686 | def load_lists(keys=[], values=[], name=):
mapping = dict(zip(keys, values))
return mapper(mapping, _nt_name=name) | Map namedtuples given a pair of key, value lists. |
18,687 | def from_etree(cls, etree_element):
ins = SaltElement.from_etree(etree_element)
ins.__class__ = SaltLayer.mro()[0]
for element in (, ):
elem_list = []
xpath_result = etree_element.xpath(+element)
if xpath_result:
... | creates a ``SaltLayer`` instance from the etree representation of an
<layers> element from a SaltXMI file. |
18,688 | def pattern_filter(items, whitelist=None, blacklist=None, key=None):
key = key or __return_self
if whitelist:
whitelisted = _filter(items, whitelist, key)
if blacklist:
blacklisted = _filter(items, blacklist, key)
whitelisted.difference_update(blacklist... | This filters `items` by a regular expression `whitelist` and/or
`blacklist`, with the `blacklist` taking precedence. An optional `key`
function can be provided that will be passed each item. |
18,689 | def body(self, value):
self.__body = value
if value is not None:
body_length = getattr(
self.__body, , None) or len(self.__body)
self.headers[] = str(body_length)
else:
self.headers.pop(, None)
| Sets the request body; handles logging and length measurement. |
18,690 | def get_user_config_dir():
user_home = os.getenv()
if user_home is None or not user_home:
config_path = os.path.expanduser(os.path.join(, , ))
else:
config_path = os.path.join(user_home, )
return config_path | Return the path to the user s-tui config directory |
18,691 | def draw_on_image(self,
image,
color=(0, 255, 0), color_face=None,
color_lines=None, color_points=None,
alpha=1.0, alpha_face=None,
alpha_lines=None, alpha_points=None,
size=1, size_lines=... | Draw all polygons onto a given image.
Parameters
----------
image : (H,W,C) ndarray
The image onto which to draw the bounding boxes.
This image should usually have the same shape as set in
``PolygonsOnImage.shape``.
color : iterable of int, optional
... |
18,692 | def send_highspeed(self, data, progress_callback):
if not self.connected:
raise HardwareError("Cannot send a script if we are not in a connected state")
if isinstance(data, str) and not isinstance(data, bytes):
raise ArgumentError("You must send bytes or bytearray to _... | Send a script to a device at highspeed, reporting progress.
This method takes a binary blob and downloads it to the device as fast
as possible, calling the passed progress_callback periodically with
updates on how far it has gotten.
Args:
data (bytes): The binary blob that ... |
18,693 | def solve_mbar(u_kn_nonzero, N_k_nonzero, f_k_nonzero, solver_protocol=None):
if solver_protocol is None:
solver_protocol = DEFAULT_SOLVER_PROTOCOL
for protocol in solver_protocol:
if protocol[] is None:
protocol[] = DEFAULT_SOLVER_METHOD
all_results = []
for k, options... | Solve MBAR self-consistent equations using some sequence of equation solvers.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
for the nonempty states
N_k_nonzero : np.ndarray... |
18,694 | def _get_config(config_file):
parser = ConfigParser.SafeConfigParser()
if os.path.lexists(config_file):
try:
log.info(, config_file)
inp = open(config_file)
parser.readfp(inp)
return parser
except (IOError, ConfigParser.ParsingError), err:
... | find, read and parse configuraton. |
18,695 | def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
handles = []
handle_args = ()
if isinstance(address, six.string_types):
handle_type = pyuv.Pipe
handle_args = (ipc,)
addresses = [address]
elif isinstance(address... | Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments. |
18,696 | def _spectrogram_mono(self, x):
x = K.permute_dimensions(x, [0, 2, 1])
x = K.expand_dims(x, 3)
subsample = (self.n_hop, 1)
output_real = K.conv2d(x, self.dft_real_kernels,
strides=subsample,
padding=self.padding,
... | x.shape : (None, 1, len_src),
returns 2D batch of a mono power-spectrogram |
18,697 | def _check_branching(X,Xsamples,restart,threshold=0.25):
check = True
if restart == 0:
Xsamples.append(X)
else:
for Xcompare in Xsamples:
Xtmax_diff = np.absolute(X[-1,:] - Xcompare[-1,:])
... | \
Check whether time series branches.
Parameters
----------
X (np.array): current time series data.
Xsamples (np.array): list of previous branching samples.
restart (int): counts number of restart trials.
threshold (float, optional): sets threshold for attractor
identification.
... |
18,698 | def findHotspot( self, name ):
for hotspot in self._hotspots:
if ( hotspot.name() == name ):
return hotspot
return None | Finds the hotspot based on the inputed name.
:param name | <str>
:return <XNodeHotspot> || None |
18,699 | def main(inputstructs, inputpdbids):
pdbid, pdbpath = None, None
title = "* Protein-Ligand Interaction Profiler v%s *" % __version__
write_message( + * len(title) + )
write_message(title)
write_message( + * len(title) + )
outputprefix = config.OUTPUTFILENAME
if inputstructs... | Main function. Calls functions for processing, report generation and visualization. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.