Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
351,700 | def _compute_global_interested_rts(self):
interested_rts = set()
for rtfilter in self._peer_to_rtfilter_map.values():
interested_rts.update(rtfilter)
interested_rts.update(self._vrfs_conf.vrf_interested_rts)
interested_rts.add(RouteTargetMembership... | Computes current global interested RTs for global tables.
Computes interested RTs based on current RT filters for peers. This
filter should be used to check if for RTs on a path that is installed
in any global table (expect RT Table). |
351,701 | def start(self):
if self.worker is None:
raise DaemonError()
if os.environ.get():
self._emit_message(.format(prog=self.prog))
self._orphan_this_process(wait_for_parent=True)
pid = self._read_pidfile()
... | Start the daemon. |
351,702 | def wait_ready(self, *types, **kwargs):
timeout = kwargs.get(, 30)
raise_exception = kwargs.get(, True)
if list(types) == [True] or list(types) == []:
types = self._default_ready_attrs
if not all(isinstance(item, basestring) for item in types):
... | Waits for specified attributes to be populated from the vehicle (values are initially ``None``).
This is typically called "behind the scenes" to ensure that :py:func:`connect` does not return until
attributes have populated (via the ``wait_ready`` parameter). You can also use it after connecting to
... |
351,703 | def formula_sections(self):
if self.dtree is not None:
return self.dtree.order
else:
return [s for s in self.manifest.sections() if s != "config"] | Return all sections related to a formula, re-ordered according to the "depends" section. |
351,704 | def read_config(self):
config_file = os.path.join(self.config_dir, )
self.config = configparser.ConfigParser()
}
self.write_config() | Read a previous configuration file or create a new with default values. |
351,705 | def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config):
https://hdl.handle.net
if handle_server_url is None and not in config.keys():
raise TypeError( + \
)
inst = EUDATHandleClient(
handle_serve... | Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.handle.net' is used).
:param reverselookup_username: The username to authenticate at the
reverse lookup servlet.
... |
351,706 | def parse_path(path):
/localhost/./localhost/localhost:30000/manager/comp0.rtclocalhost:30000managercomp0.rtclocalhost/manager/comp0.rtc:inlocalhostmanagercomp0.rtcin/localhost/manager/comp0.rtc/localhostmanagercomp0.rtc/localhost/manager/comp0.rtc:in/localhostmanagercomp0.rtcinmanager/comp0.rtcmanagercomp0.rtccom... | Parses an address into directory and port parts.
The last segment of the address will be checked to see if it matches a port
specification (i.e. contains a colon followed by text). This will be
returned separately from the directory parts.
If a leading / is given, that will be returned as the fi... |
351,707 | def get_response_handler_params(self, **params):
params = super(KimEndpoint, self).get_response_handler_params(**params)
params[] = self.mapper_class
params[] = self.serialize_role
if self._is_marshal_request():
req_params = self... | Return a config object that will be used to configure the KimResponseHandler
:returns: a dictionary of config options
:rtype: dict |
351,708 | def _frank_help(alpha, tau):
def debye(t):
return t / (np.exp(t) - 1)
debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha
return 4 * (debye_value - 1) / alpha + 1 - tau | Compute first order debye function to estimate theta. |
351,709 | def once(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not hasattr(wrapper, ):
wrapper.saved_result = func(*args, **kwargs)
return wrapper.saved_result
wrapper.reset = lambda: vars(wrapper).__delitem__()
return wrapper | Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3)
>>> add_three(3)
6
>>> add_three(9)
6
>>> add_three('12')
6
To reset the stored valu... |
351,710 | def mkdir(path, create_parent=True, check_if_exists=False):
cmd = _format_cmd(, path, _p=create_parent)
if check_if_exists:
return .format(path, cmd)
return cmd | Generates a unix command line for creating a directory.
:param path: Directory path.
:type path: unicode | str
:param create_parent: Create parent directories, if necessary. Default is ``True``.
:type create_parent: bool
:param check_if_exists: Prepend a check if the directory exists; in that case,... |
351,711 | def logpdf(self, p):
x2 = self.p2x(p) ** 2
return -0.5 * numpy.sum(x2) - self.log_gnorm | Logarithm of the probability density function evaluated at ``p``. |
351,712 | def make_multi_lagger(lags, groupby_kwargs=None):
laggers = [SingleLagger(l, groupby_kwargs=groupby_kwargs) for l in lags]
feature_union = FeatureUnion([
(repr(lagger), lagger) for lagger in laggers
])
return feature_union | Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby |
351,713 | def splunk_version(self):
if self._splunk_version is None:
self._splunk_version = tuple([int(p) for p in self.info[].split()])
return self._splunk_version | Returns the version of the splunkd instance this object is attached
to.
The version is returned as a tuple of the version components as
integers (for example, `(4,3,3)` or `(5,)`).
:return: A ``tuple`` of ``integers``. |
351,714 | def transform(self, data=None):
if data is None:
return self.xform_data
else:
formatted = format_data(
data,
semantic=self.semantic,
vectorizer=self.vectorizer,
corpus=self.corpus,
p... | Return transformed data, or transform new data using the same model
parameters
Parameters
----------
data : numpy array, pandas dataframe or list of arrays/dfs
The data to transform. If no data is passed, the xform_data from
the DataGeometry object will be retur... |
351,715 | def syscall(self, state, allow_unsupported=True):
abi = self.syscall_abi(state)
if state.os_name in SYSCALL_CC[state.arch.name]:
cc = SYSCALL_CC[state.arch.name][state.os_name](state.arch)
else:
_l.warning("No syscall calling convention available fo... | Given a state, return the procedure corresponding to the current syscall.
This procedure will have .syscall_number, .display_name, and .addr set.
:param state: The state to get the syscall number from
:param allow_unsupported: Whether to return a "dummy" sycall instead of raisin... |
351,716 | def put(self, user_name: str) -> User:
current = current_user()
if current.name == user_name or current.is_admin:
user = self._get_or_abort(user_name)
self.update(user)
session.commit()
session.add(user)
return user
else:
... | Updates the User Resource with the
name. |
351,717 | def listed(self):
print("\nPackages in the queue:\n")
for pkg in self.packages():
if pkg:
print("{0}{1}{2}".format(self.meta.color["GREEN"], pkg,
self.meta.color["ENDC"]))
self.quit = True
if self.quit:... | Print packages from queue |
351,718 | def _get_container(self):
if not hasattr(self, "_container"):
if self.use_pyrax:
self._container = self.connection.create_container(self.container_name)
else:
self._container = None
return self._container | Gets or creates the container. |
351,719 | def process_node_search(self, node, q, **kwargs):
priority
if isinstance(q, PriorityQueue):
self.get_node(node).set_attr(, q.get_priority(node)) | API: process_node_search(self, node, q, **kwargs)
Description:
Used by search() method. Process nodes along the search. Should not be
called by user directly.
Input:
node: Name of the node being processed.
q: Queue data structure.
kwargs: Keyword argum... |
351,720 | def _update_container_host_config(self, service):
if not isinstance(service, Service):
raise TypeError("service must be an instance of Service")
if service.dependencies:
self._load_dependency_containers(service)
if service.host_config.links:
... | :param service:
:return None: |
351,721 | def report_progress(self):
percent = self.calc_percent()
total = format_bytes(self._total)
speed = self.calc_speed()
total_speed_report = .format(total, speed)
report = .format(percent, total_speed_report)
if self._finished:
print(report)
e... | Report download progress. |
351,722 | def _set_directories(self):
if self._dirs[] == None:
self._dirs[] = discover_base_dir(self._dirs[])
else:
self._dirs[] = discover_base_dir(self._dirs[])
self._update_dirs_on_base()
self._tree_ready = verify_dir_stru... | Initialize variables based on evidence about the directories. |
351,723 | def available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == ] | List of GPU device names detected by TensorFlow. |
351,724 | def _match_modes(self, remote_path, l_st):
self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode))
self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime))
if self.chown:
self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gid) | Match mod, utime and uid/gid with locals one. |
351,725 | def putmask(self, mask, new, align=True, inplace=False, axis=0,
transpose=False):
inplace = validate_bool_kwarg(inplace, )
new_values = self.values if inplace else self.copy().values
new_values, new = self._try_coerce_args(new_values, new)
if ... | putmask the data to the block; we must be a single block and not
generate other blocks
return the resulting block
Parameters
----------
mask : the condition to respect
new : a ndarray/object
align : boolean, perform alignment on other/cond, default is True
... |
351,726 | def PopTask(self):
try:
_, task = heapq.heappop(self._heap)
except IndexError:
return None
self._task_identifiers.remove(task.identifier)
return task | Retrieves and removes the first task from the heap.
Returns:
Task: the task or None if the heap is empty. |
351,727 | def comicDownloaded(self, comic, filename, text=None):
for handler in _handlers:
handler.comicDownloaded(comic, filename, text=text) | Emit comic downloaded events for handlers. |
351,728 | def _HashRow(cls, row):
values = []
for value in row:
try:
value = .format(value)
except UnicodeDecodeError:
value = repr(value)
values.append(value)
return hash(.join(values)) | Hashes the given row.
Args:
row (sqlite3.Row): row.
Returns:
int: hash value of the given row. |
351,729 | def _sanitize_entity(self, entity):
aliases = {
"current_state": "state",
"is_flapping": "flapping",
"scheduled_downtime_depth": "in_downtime",
"has_been_checked": "checked",
"should_be_scheduled": "scheduled",
"active_checks_enabl... | Make given entity 'sane' for further use. |
351,730 | def compute_differential_operator(self):
r
sources, targets, weights = self.get_edge_list()
n = self.n_edges
rows = np.concatenate([sources, targets])
columns = np.concatenate([np.arange(n), np.arange(n)])
values = np.empty(2*n)
if self.lap_type == :
... | r"""Compute the graph differential operator (cached).
The differential operator is the matrix :math:`D` such that
.. math:: L = D D^\top,
where :math:`L` is the graph Laplacian (combinatorial or normalized).
It is used to compute the gradient and the divergence of graph
signal... |
351,731 | def get_deviation(self, deviationid):
response = self._req(.format(deviationid))
d = Deviation()
d.from_dict(response)
return d | Fetch a single deviation
:param deviationid: The deviationid you want to fetch |
351,732 | def image_from_console(console: tcod.console.Console) -> tcod.image.Image:
return tcod.image.Image._from_cdata(
ffi.gc(
lib.TCOD_image_from_console(_console(console)),
lib.TCOD_image_delete,
)
) | Return an Image with a Consoles pixel data.
This effectively takes a screen-shot of the Console.
Args:
console (Console): Any Console instance. |
351,733 | def set_host_power(self, power):
power = power.upper()
if (power is not None) and (power not in POWER_STATE):
msg = ("Invalid input . "
"The expected input is ON or OFF." %
{: power})
raise exception.IloInvalidInputError(msg)
... | Toggle the power button of server.
:param power: 'ON' or 'OFF'
:raises: IloError, on an error from iLO. |
351,734 | def list_channels(self, collection_name, experiment_name):
dont_care =
chan = ChannelResource(
name=, collection_name=collection_name,
experiment_name=experiment_name, type=dont_care)
return self._list_resource(chan) | List all channels belonging to the named experiment that is part
of the named collection.
Args:
collection_name (string): Name of the parent collection.
experiment_name (string): Name of the parent experiment.
Returns:
(list)
Raises:
req... |
351,735 | def setRootJob(self, rootJobStoreID):
with self.writeSharedFileStream(self.rootJobStoreIDFileName) as f:
f.write(rootJobStoreID.encode()) | Set the root job of the workflow backed by this job store
:param str rootJobStoreID: The ID of the job to set as root |
351,736 | def calculate_bbh(blast_results_1, blast_results_2, r_name=None, g_name=None, outdir=):
cols = [, , , , , , , ,
, , , ]
if not r_name and not g_name:
r_name = op.basename(blast_results_1).split()[0]
g_name = op.basename(blast_results_1).split()[1].replace(, )
r_n... | Calculate the best bidirectional BLAST hits (BBH) and save a dataframe of results.
Args:
blast_results_1 (str): BLAST results for reference vs. other genome
blast_results_2 (str): BLAST results for other vs. reference genome
r_name: Name of reference genome
g_name: Name of other gen... |
351,737 | def search_credit():
sid = request.jws_payload[].get()
address = request.jws_payload[].get()
currency = request.jws_payload[].get()
network = request.jws_payload[].get()
ref_id = request.jws_payload[].get()
page = request.jws_payload[].get() or 0
credsq = ses.query(wm.Credit).filt... | Get one to ten credit(s) for a single User.
---
parameters:
- name: searchcd
in: body
description: The Credit(s) you'd like to get.
required: false
schema:
$ref: '#/definitions/SearchCD'
responses:
'200':
description: the User's credit(s)
... |
351,738 | def to_gremlin(self):
self.validate()
mark_name, _ = self.location.get_location_name()
return u.format(safe_quoted_string(mark_name)) | Return a unicode object with the Gremlin representation of this block. |
351,739 | def porthistory(port_number, start_date=None, end_date=None, return_format=None):
uri = .format(port=port_number)
if not start_date:
start_date = datetime.datetime.now() - datetime.timedelta(days=30)
try:
uri = .join([uri, start_date.strftime("%Y-%m-%d")])
except Attribut... | Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or d... |
351,740 | def multipart(body, content_length=0, **header_params):
header_params.setdefault(, content_length)
if header_params and in header_params:
if type(header_params[]) is str:
header_params[] = header_params[].encode()
form = parse_multipart((body.stream if hasattr(body, ) else body), ... | Converts multipart form data into native Python objects |
351,741 | def create_cash_on_delivery_payment(cls, cash_on_delivery_payment, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._create_cash_on_delivery_payment_with_http_info(cash_on_delivery_payment, **kwargs)
else:
(data) = cls._create_cash_on_delivery_payment_with_... | Create CashOnDeliveryPayment
Create a new CashOnDeliveryPayment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_cash_on_delivery_payment(cash_on_delivery_payment, async=True)
>>> result... |
351,742 | def resizeEvent(self, event):
if self.resizeMode() == self.Adjust:
self.scheduleDelayedItemsLayout()
return super(ListLevel, self).resizeEvent(event) | Schedules an item layout if resize mode is \"adjust\". Somehow this is
needed for correctly scaling down items.
The reason this was reimplemented was the CommentDelegate.
:param event: the resize event
:type event: QtCore.QEvent
:returns: None
:rtype: None
:rais... |
351,743 | def json_numpy_obj_hook(dct):
if isinstance(dct, dict) and in dct:
data = np.asarray(dct[], dtype=dct[])
return data.reshape(dct[])
return dct | Decodes a previously encoded numpy ndarray with proper shape and dtype.
Parameters
----------
dct : :obj:`dict`
The encoded dictionary.
Returns
-------
:obj:`numpy.ndarray`
The ndarray that `dct` was encoding. |
351,744 | def add_component(self, component):
if component not in self._components:
self._components.append(component)
else:
self._components[self._components.index(component)] = component | Adds a Component to an Entity |
351,745 | def is_turbo_boost_enabled():
try:
if os.path.exists(_TURBO_BOOST_FILE):
boost_enabled = int(util.read_file(_TURBO_BOOST_FILE))
if not (0 <= boost_enabled <= 1):
raise ValueError(.format(boost_enabled))
return boost_enabled != 0
if os.path.exi... | Check whether Turbo Boost (scaling CPU frequency beyond nominal frequency)
is active on this system.
@return: A bool, or None if Turbo Boost is not supported. |
351,746 | def clear(self, pat=None):
if pat is None:
return self.__dict__.clear()
expr = re.compile(fnmatch.translate(pat))
for key in tuple(self.keys()):
if isinstance(key, string_types):
if expr.match(key):
del self.__dic... | Minor diversion with built-in dict here; clear can take a glob
style expression and remove keys based on that expression. |
351,747 | def check_unique(self):
result = yield views.repository_name.values(key=self.name)
repo_id = getattr(self, , None)
repos = {x for x in result if x != repo_id and x}
if repos:
raise exceptions.ValidationError(
"Repository with name already exists".fo... | Check the repository's name is unique |
351,748 | async def put(self, public_key):
if settings.SIGNATURE_VERIFICATION:
super().verify()
try:
body = json.loads(self.request.body)
except:
self.set_status(400)
self.write({"error":400, "reason":"Unexpected data format. JSON required"})
raise tornado.web.Finish
if isinstance(body["message"... | Reject offer and unfreeze balance
Accepts:
- cid
- buyer public key
- buyer address |
351,749 | def addfield(self, name, type, width=10):
fieldDefn = ogr.FieldDefn(name, type)
if type == ogr.OFTString:
fieldDefn.SetWidth(width)
self.layer.CreateField(fieldDefn) | add a field to the vector layer
Parameters
----------
name: str
the field name
type: int
the OGR Field Type (OFT), e.g. ogr.OFTString.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
width: int
the width of the n... |
351,750 | def _compute_output_layer_expected(self):
expected = [
layer_purpose_exposure_summary[],
layer_purpose_aggregate_hazard_impacted[],
layer_purpose_aggregation_summary[],
layer_purpose_analysis_impacted[],
layer_purpose_exposure... | Compute output layers expected that the IF will produce.
Be careful when you call this function. It's a private function, better
to use the public function `output_layers_expected()`.
:return: List of expected layer keys.
:rtype: list |
351,751 | def run(self):
"sets up the desired services and runs the requested action"
self.addServices()
self.catalogServers(self.hendrix)
action = self.action
fd = self.options[]
if action.startswith():
chalk.blue(self._listening_message())
getattr(self, a... | sets up the desired services and runs the requested action |
351,752 | def make_array_access(id_, lineno, arglist):
return symbols.ARRAYACCESS.make_node(id_, arglist, lineno) | Creates an array access. A(x1, x2, ..., xn).
This is an RVALUE (Read the element) |
351,753 | def read_configuration(config=):
_, conf = read_latoolscfg()
if config == :
config = conf[][]
conf = dict(conf[config])
conf[] = config
return conf | Read LAtools configuration file, and return parameters as dict. |
351,754 | def _create_single_feature_method(feature):
fx_name = feature.name.lower()
if "detection" in fx_name:
fx_doc = "Perform {0}.".format(fx_name.replace("_", " "))
else:
fx_doc = "Return {desc} information.".format(desc=fx_name.replace("_", " "))
fx_doc +=
fea... | Return a function that will detect a single feature.
Args:
feature (enum): A specific feature defined as a member of
:class:`~enums.Feature.Type`.
Returns:
function: A helper function to detect just that feature. |
351,755 | def _InvokeImportCallbackBySuffix(names):
def GetModuleFromName(name, path):
if not os.path.isabs(mod_root):
mod_root = os.path.join(os.curdir, mod_root)
if module_utils2.IsPathSuffix(mod_root, root):
for callback in callbac... | Invokes import callbacks for newly loaded modules.
Uses a path suffix match to identify whether a loaded module matches the
file path provided by the user.
Args:
names: A set of names for modules that are loaded by the current import.
The set may contain some superfluous entries that were already... |
351,756 | def to_dict(self):
d = {: self.id, : self.classes}
d.update(self.kvs)
return d | Returns attributes formatted as a dictionary. |
351,757 | def sum_mags(mags, weights=None):
flux = 10**(-np.asarray(mags) / 2.5)
if weights is None:
return -2.5 * np.log10(np.sum(flux))
else:
return -2.5 * np.log10(np.sum(weights*flux)) | Sum an array of magnitudes in flux space.
Parameters:
-----------
mags : array of magnitudes
weights : array of weights for each magnitude (i.e. from a pdf)
Returns:
--------
sum_mag : the summed magnitude of all the stars |
351,758 | def watermark(self, image, options):
watermark_img = options.get("watermark", settings.THUMBNAIL_WATERMARK)
if not watermark_img:
raise AttributeError("No THUMBNAIL_WATERMARK defined or set on tag.")
watermark_path = find(watermark_img)
if not watermark_path:
... | Wrapper for ``_watermark``
Takes care of all the options handling. |
351,759 | def map_data(self):
with open(self.src_file, "r") as f:
for line in f:
cols = line.split()
print(cols) | provides a mapping from the CSV file to the
aikif data structures. |
351,760 | def keys(self, *args, **kwargs):
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_keys(*args, **kwargs) | Show the available formatoptions in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s |
351,761 | def groups_set_read_only(self, room_id, read_only, **kwargs):
return self.__call_api_post(, roomId=room_id, readOnly=bool(read_only), kwargs=kwargs) | Sets whether the group is read only or not. |
351,762 | def charts_slug_pollster_chart_poll_questions_tsv_get(self, slug, **kwargs):
kwargs[] = True
if kwargs.get():
return self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_pollster_chart_poll_question... | One row per poll plotted on a Chart
Derived data presented on a Pollster Chart. Rules for which polls and responses are plotted on a chart can shift over time. Here are some examples of behaviors Pollster has used in the past: * We've omitted \"Registered Voters\" from a chart when \"Likely Voters\" respond... |
351,763 | def on_sanji_message(self, client, userdata, msg):
try:
message = Message(msg.payload)
except (TypeError, ValueError) as e:
_logger.error(e, exc_info=True)
return
if message.type() == MessageType.UNKNOWN:
_logger.debug("Got an UNKNOWN mes... | This function will recevie all message from mqtt
client
the client instance for this callback
userdata
the private user data as set in Client() or userdata_set()
message
an instance of MQTTMessage. This is a class with members topic,
payload, qos, ... |
351,764 | def _write_header(self):
self._ostream.write(len(self._header) * "-" + "\n")
self._ostream.write(self._header)
self._ostream.write("\n")
self._ostream.write(len(self._header) * "-" + "\n") | Write out the table header |
351,765 | def _batch_insert(self, inserts, intervals, **kwargs):
if in kwargs:
pipe = kwargs.get()
own_pipe = False
else:
pipe = self._client.pipeline(transaction=False)
kwargs[] = pipe
own_pipe = True
ttl_batch = set()
for timestamp,names in inserts.iteritems():
for nam... | Specialized batch insert |
351,766 | def find_source(self, source):
if not is_valid_url(source):
try:
source = self.get_source(name=source)
except SourceNotFound:
source = self.get_source(url=source)
else:
source = self.get_source(url=source)
return source | Given a source, find it.
source can be a url or an index name. |
351,767 | def run(self, timeout = 0):
ptimeout = int(
timeout.days * 86400000 +
timeout.microseconds / 1000 +
timeout.seconds * 1000
if timeout else (self.m_resolution if timeout is None else 0)
)
if self.tokens:
schedu... | Calls GetQueuedCompletionStatus and handles completion via
IOCPProactor.process_op. |
351,768 | def get_queryset(self):
cohort = get_object_or_404(Cohort, slug=self.kwargs[])
animals = cohort.animals.all()
return Measurement.objects.filter(animal=animals) | The queryset is filtered by measurements of animals which are part of that strain. |
351,769 | def _highlight_block(self, block):
scope = FoldScope(block)
if (self._current_scope is None or
self._current_scope.get_range() != scope.get_range()):
self._current_scope = scope
self._clear_scope_decos()
start, end = scope.get_ran... | Highlights the current fold scope.
:param block: Block that starts the current fold scope. |
351,770 | def _get_master_uri(master_ip,
master_port,
source_ip=None,
source_port=None):
from salt.utils.zeromq import ip_bracket
master_uri = .format(
master_ip=ip_bracket(master_ip), master_port=master_port)
if source_ip or source_... | Return the ZeroMQ URI to connect the Minion to the Master.
It supports different source IP / port, given the ZeroMQ syntax:
// Connecting using a IP address and bind to an IP address
rc = zmq_connect(socket, "tcp://192.168.1.17:5555;192.168.1.1:5555"); assert (rc == 0);
Source: http://api.zeromq.org/4-1... |
351,771 | def deflections_from_grid(self, grid):
def calculate_deflection_component(npow, index):
einstein_radius_rescaled = self.einstein_radius_rescaled
deflection_grid = self.axis_ratio * grid[:, index]
deflection_grid *= quad_grid(self.deflection_func, 0.0, 1.0,
... | Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on. |
351,772 | def coupl_model5(self):
self.Coupl = -0.2*self.Adj
self.Coupl[2,0] *= -1
self.Coupl[3,0] *= -1
self.Coupl[4,1] *= -1
self.Coupl[5,1] *= -1 | Toggle switch. |
351,773 | def confidential_login(credentials=None, client_id=None, client_secret=None, services=None,
make_clients=True, token_dir=DEFAULT_CRED_PATH):
DEFAULT_CRED_FILENAME = "confidential_globus_login.json"
if credentials:
if type(credentials) is str:
try:
... | Log in to Globus services as a confidential client
(a client with its own login information).
Arguments:
credentials (str or dict): A string filename, string JSON, or dictionary
with credential and config information.
By default, uses the ``DEFAULT_CRED_FILENAME`` and to... |
351,774 | def does_not_contain_key(self, *keys):
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.does_not_contain(*keys) | Asserts the val is a dict and does not contain the given key or keys. Alias for does_not_contain(). |
351,775 | def add_child(self, **kwargs):
if not self.is_leaf():
if self.node_order_by:
pos =
else:
pos =
last_child = self.get_last_child()
last_child._cached_parent_obj = self
return last_child.add_sibling... | Adds a child to the node. |
351,776 | def count_comments_handler(sender, **kwargs):
comment = kwargs[]
if comment.is_public:
entry = comment.content_object
if isinstance(entry, Entry):
entry.comment_count = F() + 1
entry.save(update_fields=[]) | Update Entry.comment_count when a public comment was posted. |
351,777 | def main(argv=None):
parser = argparse.ArgumentParser(
prog="pelix.shell.remote",
parents=[make_common_parser()],
description="Pelix Remote Shell ({} SSL support)".format(
"with" if ssl is not None else "without"
),
)
group = parser.add_argument_gr... | Script entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None |
351,778 | def fix_out_stanza(self, stanza):
StreamBase.fix_out_stanza(self, stanza)
if self.initiator:
if stanza.from_jid:
stanza.from_jid = None
else:
if not stanza.from_jid:
stanza.from_jid = self.me | Fix outgoing stanza.
On a client clear the sender JID. On a server set the sender
address to the own JID if the address is not set yet. |
351,779 | def set_loglevel(self, level):
self.log_level = level
log_manager.config_stdio(default_level=level) | Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels |
351,780 | def set_trace_cond(*args, **kw):
for key, val in kw.items():
Epdb.set_trace_cond(key, val)
for arg in args:
Epdb.set_trace_cond(arg, True) | Sets a condition for set_trace statements that have the
specified marker. A condition can either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which case the break will
only be calle... |
351,781 | def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False):
params = {
"date": date,
"page": page,
"pagesize": page_size,
"orderfield": order_field,
"orderdirection": ... | Gets the active subscribers in this segment. |
351,782 | def assertFileSizeNotEqual(self, filename, size, msg=None):
!=
fsize = self._get_file_size(filename)
self.assertNotEqual(fsize, size, msg=msg) | Fail if ``filename`` has the given ``size`` as determined
by the '!=' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard message will ... |
351,783 | def riseset(self, crd, ev="5deg"):
a = self.rise(crd, ev)
if isinstance(a[], str):
return {"rise": {"last": a[0], "utc": a[0]},
"set": {"last": a[1], "utc": a[1]},
"solved": False}
ofe = self.measure(self._framestack["epoch"], "utc")
... | This will give the rise/set times of a source. It needs the
position in the frame, and a time. If the latter is not set, the
current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or string
:returns: The returned value is a `dict`... |
351,784 | def bump(self, filter_requirements, required=False, show_summary=True, show_detail=False, **kwargs):
found_targets = [target for target in self.targets if os.path.exists(target)]
if not found_targets:
raise BumpAccident( % .join(self.targets))
bump_reqs = RequirementsManag... | Bump dependency requirements using filter.
:param list filter_requirements: List of dependency filter requirements.
:param bool required: Require the filter_requirements to be met (by adding if possible).
:param bool show_summary: Show summary for each bump made.
:param bool show_detail... |
351,785 | def _get_replacement_token(msg):
return (
None
if not re.search(r"\*\[[\w|\W]+\]\*", msg)
else re.search(r"\*\[[\w|\W]+\]\*", msg).group()[2:-2]
) | Extract replacement token from exception message. |
351,786 | def _is_retryable_exception(e):
if isinstance(e, urllib3.exceptions.ProtocolError):
e = e.args[1]
if isinstance(e, (socket.gaierror, socket.herror)):
return True
if isinstance(e, socket.error) and e.errno in _RETRYABLE_SOCKET_ERRORS:
return True
if isinstance(e, urllib3.exce... | Returns True if the exception is always safe to retry.
This is True if the client was never able to establish a connection
to the server (for example, name resolution failed or the connection
could otherwise not be initialized).
Conservatively, if we can't tell whether a network connection could
h... |
351,787 | def create(self, secret_type, value=None):
if secret_type is ObjectType.CERTIFICATE:
return self._create_certificate(value)
elif secret_type is ObjectType.SYMMETRIC_KEY:
return self._create_symmetric_key(value)
elif secret_type is ObjectType.PUBLIC_KEY:
... | Create a secret object of the specified type with the given value.
Args:
secret_type (ObjectType): An ObjectType enumeration specifying the
type of secret to create.
value (dict): A dictionary containing secret data. Optional,
defaults to None.
R... |
351,788 | def losing_name(self):
if self.winner == HOME:
if not in str(self._away_name):
return str(self._away_name)
return self._away_name.text()
if not in str(self._home_name):
return str(self._home_name)
return self._home_name.text() | Returns a ``string`` of the losing team's name, such as 'Indiana'
Hoosiers'. |
351,789 | def get_user_roles(self):
if self.is_anonymous_user():
return []
current_user = ploneapi.user.get_current()
return ploneapi.user.get_roles(user=current_user) | Returns a list of roles for the current user |
351,790 | def open_gsr(self):
gsr_path = self.gsr_path
if not gsr_path:
if self.status == self.S_OK:
logger.critical("%s reached S_OK but didn't produce a GSR file in %s" % (self, self.outdir))
return None
from abipy.electrons.gsr import GsrFile
... | Open the GSR file located in the in self.outdir.
Returns :class:`GsrFile` object, None if file could not be found or file is not readable. |
351,791 | def downloadFile(self, from_path, to_path = ):
if to_path == :
file_name = os.path.basename(from_path)
to_path = os.path.join(os.getcwd(), file_name)
url = nurls[] + from_path
data = {:2,
: self.user_id,
: self.useridx,
... | Download a file.
>>> nd.downloadFile('/Picture/flower.png', '~/flower.png')
:param from_path: The full path to download the file to, *including the file name*. If the destination directory does not yet exist, it will be created.
:param to_path: The full path of a file to be saved in local ... |
351,792 | def sizeHint(self, option, index):
component = index.internalPointer()
width = self.component.duration() * self.pixelsPerms*1000
return QtCore.QSize(width, 50) | Size based on component duration and a fixed height |
351,793 | def array(self) -> numpy.ndarray:
array = numpy.full(self.shape, fillvalue, dtype=float)
idx0 = 0
idxs: List[Any] = [slice(None)]
for seq, subarray in zip(self.sequences.values(),
self.arrays.values()):
for prod in self._product(seq.s... | The series data of all logged |IOSequence| objects contained in
one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. The first example
confirms that, under default configuration (`timeaxis=1`), the
... |
351,794 | def create_inspect_template(
self,
parent,
inspect_template=None,
template_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "create_inspect_template" not in ... | Creates an InspectTemplate for re-using frequently used configuration
for inspecting content, images, and storage.
See https://cloud.google.com/dlp/docs/creating-templates to learn more.
Example:
>>> from google.cloud import dlp_v2
>>>
>>> client = dlp_v2.Dlp... |
351,795 | def derivative(self, vs=None):
r
return functools.reduce(operator.xor, self.iter_cofactors(vs)) | r"""Return the derivative of a function over a sequence of N variables.
The *vs* argument is a sequence of :math:`N` Boolean variables.
The *derivative* of :math:`f(x_1, x_2, \dots, x_i, \dots, x_n)` with
respect to variable :math:`x_i` is:
:math:`\frac{\partial}{\partial x_i} f = f_{x... |
351,796 | def convert_lstm(builder, layer, input_names, output_names, keras_layer):
hidden_size = keras_layer.output_dim
input_size = keras_layer.input_shape[-1]
if keras_layer.consume_less not in [, ]:
raise ValueError( % keras_layer.consume_less)
output_all = keras_layer.return_sequences
reve... | Convert an LSTM layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. |
351,797 | def unpause(self, id):
return self.service.post(self.base+str(id)+) | Unpause a running result.
:param id: Result ID as an int. |
351,798 | def move_to_global_scope(self, id_):
if id_ in self.table[self.current_scope].keys(filter_by_opt=False) and len(self.table) > 1:
symbol = self.table[self.current_scope][id_]
symbol.offset = None
symbol.scope = SCOPE.global_
if symbol.class_ != CL... | If the given id is in the current scope, and there is more than
1 scope, move the current id to the global scope and make it global.
Labels need this. |
351,799 | def validate_string_param(s, valid, param_name="param"):
if s.lower() not in valid:
raise YellowbrickValueError(
"unknown {} , chose from ".format(
param_name, s, ", ".join(valid)
)
) | Raises a well formatted exception if s is not in valid, otherwise does not
raise an exception. Uses ``param_name`` to identify the parameter. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.