Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
357,300 | def dispatch(self, request, *args, **kwargs):
return super(SkillAdapter, self).dispatch(request) | Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in the input request and delegate it to the
corresponding method in the view. The only allowed method on
th... |
357,301 | def get_nicknames(self):
nicknames = []
for child in self.vcard.getChildren():
if child.name == "NICKNAME":
nicknames.append(child.value)
return sorted(nicknames) | :rtype: list(list(str)) |
357,302 | async def _on_message(self, update):
name = update[]
message_obj = update[]
if name not in self.services:
return
with self._state_lock:
self.services[name].post_message(message_obj[], message_obj[]) | Receive a message from a service. |
357,303 | def update_in_ioloop(update):
@wraps(update)
def wrapped_update(self, sensor, reading):
if get_thread_ident() == self._ioloop_thread_id:
update(self, sensor, reading)
else:
self.ioloop.add_callback(update, self, sensor, reading)
return wrapped_update | Decorator that ensures an update() method is run in the tornado ioloop.
Does this by checking the thread identity. Requires that the object to
which the method is bound has the attributes :attr:`_ioloop_thread_id`
(the result of thread.get_ident() in the ioloop thread) and :attr:`ioloop`
(the ioloop in... |
357,304 | def spawn_process(self, target, *args):
p = Process(target=target, args=args)
p.daemon = True
if target == worker:
p.daemon = Conf.DAEMONIZE_WORKERS
p.timer = args[2]
self.pool.append(p)
p.start()
return p | :type target: function or class |
357,305 | def check_for_usable_environment(self):
if os.geteuid() == 0:
utils.error("Running Mackup as a superuser is useless and"
" dangerous. Don't do it!")
if not os.path.isdir(self._config.path):
utils.error("Unable to find the storag... | Check if the current env is usable and has everything's required. |
357,306 | def save_bookmarks(self, filename, bookmarks):
filename = to_text_string(filename)
bookmarks = to_text_string(bookmarks)
filename = osp.normpath(osp.abspath(filename))
bookmarks = eval(bookmarks)
save_bookmarks(filename, bookmarks) | Receive bookmark changes and save them. |
357,307 | def pre_dispatch(self, request, path_args):
secret_key = self.get_secret_key(request, path_args)
if not secret_key:
raise PermissionDenied()
try:
signing.verify_url_path(request.path, request.GET, secret_key)
except SigningError as ex:
raise ... | Pre dispatch hook |
357,308 | def __evaluation_error(self, result, condition, throw):
self.log.error("Result does not match condition, dropping item. "
"Result %s; Condition: %s; Throw: %s",
result, condition, throw)
return False | Helper-method for easy error-logging |
357,309 | def current(self):
rv = _local.get(None)
if rv is None:
rv = Hub(GLOBAL_HUB)
_local.set(rv)
return rv | Returns the current instance of the hub. |
357,310 | def find_surface_sites_by_height(self, slab, height=0.9, xy_tol=0.05):
m_projs = np.array([np.dot(site.coords, self.mvec)
for site in slab.sites])
mask = (m_projs - np.amax(m_projs)) >= -height
surf_sites = [slab.sites[n] for n in np.where... | This method finds surface sites by determining which sites are within
a threshold value in height from the topmost site in a list of sites
Args:
site_list (list): list of sites from which to select surface sites
height (float): threshold in angstroms of distance from topmost
... |
357,311 | def lcumsum (inlist):
newlist = copy.deepcopy(inlist)
for i in range(1,len(newlist)):
newlist[i] = newlist[i] + newlist[i-1]
return newlist | Returns a list consisting of the cumulative sum of the items in the
passed list.
Usage: lcumsum(inlist) |
357,312 | def keyPressEvent(self, event):
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
if self.add_current_text_if_valid():
self.selected()
self.hide_completer()
elif event.key() == Qt.Key_Escape:
self.set_current_text(self... | Qt Override.
Handle key press events. |
357,313 | def g_subset(g, atwts, atwt,
digits=_DEF.SYMM_ATWT_ROUND_DIGITS):
import numpy as np
g = make_nd_vec(g, nd=None, t=np.float64, norm=False)
atwts = make_nd_vec(atwts, nd=None, t=np.float64, norm=False)
if not (len(g) == 3*len(atwts)):
raise ValueError("Dim misma... | Extract a subset of a geometry matching a desired atom.
.. todo:: Complete g_subset docstring |
357,314 | def plan_first_phase(N1, N2):
N = N1*N2
vin = pycbc.types.zeros(N, dtype=numpy.complex64)
vout = pycbc.types.zeros(N, dtype=numpy.complex64)
f = float_lib.fftwf_plan_many_dft
f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p,
... | Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
The plan for performing the first phase ... |
357,315 | def ner_net(source, destinations, width, height, wrap_around=False, radius=10):
route = {source: RoutingTree(source)}
for destination in sorted(destinations,
key=(lambda destination:
shortest_mesh_path_length(
... | Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y), ...])
The coordinates of destination vertices.
width : int
Width ... |
357,316 | def get_df_ilocs(self, band, date):
df = self.df_layers.copy()
df["index"] = range(df.shape[0])
idx_layers = []
if isinstance(band, str) and isinstance(date, str):
idx_layers = df[(df["date"] == date) & (df["band"] == band)]["index"].values[0]
if isinstanc... | Get positions of rows matching specific band(s) and date(s).
The method supports three typical queries:
* one band and one date (both given as strings)
* one band and of several dates (band given as strings, date as list of strings)
* several band and of one date (date given as strin... |
357,317 | def check_prerequisites(
prerequisites,
checker,
msg_tmpl=
):
def wrap(func):
@functools.wraps(func)
def wrapped_func(*args, **kwargs):
requirements = [prerequisites] if isinstance(
prerequisites, str) else prerequisites
... | A decorator factory to check if prerequisites are satisfied.
Args:
prerequisites (str of list[str]): Prerequisites to be checked.
checker (callable): The checker method that returns True if a
prerequisite is meet, False otherwise.
msg_tmpl (str): The message template with two va... |
357,318 | def retry(self, timeout=RETRY_SAME_TIMEOUT):
if timeout is None:
return self.timedOutFunction(*(self.timedOutArgs), **self.timedOutKwargs)
from .dafunc import func_timeout
if timeout == RETRY_SAME_TIMEOUT:
timeout = self.timedOutAfter
return fu... | retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
If a float/int : Will retry the function same args wit... |
357,319 | def train(cls, data, lambda_=1.0):
first = data.first()
if not isinstance(first, LabeledPoint):
raise ValueError("`data` should be an RDD of LabeledPoint")
labels, pi, theta = callMLlibFunc("trainNaiveBayesModel", data, lambda_)
return NaiveBayesModel(labels.toArray(... | Train a Naive Bayes model given an RDD of (label, features)
vectors.
This is the Multinomial NB (U{http://tinyurl.com/lsdw6p}) which
can handle all kinds of discrete data. For example, by
converting documents into TF-IDF vectors, it can be used for
document classification. By m... |
357,320 | def validate_environment(self):
environment = os.environ.get()
if environment:
if not same_directories(sys.prefix, environment):
raise EnvironmentMismatchError(, environment=environment, prefix=sys.prefix) | Make sure :data:`sys.prefix` matches ``$VIRTUAL_ENV`` (if defined).
This may seem like a strange requirement to dictate but it avoids hairy
issues like `documented here <https://github.com/paylogic/pip-accel/issues/5>`_.
The most sneaky thing is that ``pip`` doesn't have this problem
(... |
357,321 | def from_rtm(cls, raw_event: MutableMapping) -> "Event":
if raw_event["type"].startswith("message"):
return Message(raw_event)
else:
return Event(raw_event) | Create an event with data coming from the RTM API.
If the event type is a message a :class:`slack.events.Message` is returned.
Args:
raw_event: JSON decoded data from the RTM API
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message` |
357,322 | def indxByRange(self, valu):
if not isinstance(valu, (list, tuple)):
raise s_exc.BadCmprValu(valu=valu, cmpr=)
if len(valu) != 2:
raise s_exc.BadCmprValu(valu=valu, cmpr=)
tick, tock = self.getTickTock(valu)
if tick > tock:
re... | Override default ``*range=`` handler to account for relative computation. |
357,323 | def QA_SU_save_index_min(client=DATABASE, ui_log=None, ui_progress=None):
__index_list = QA_fetch_get_stock_list()
coll = client.index_min
coll.create_index(
[
(,
pymongo.ASCENDING),
(,
pymongo.ASCENDING),
(,
pymongo.AS... | save index_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) |
357,324 | def create_link_button(self, text="None", uri="None"):
link_btn = Gtk.LinkButton(uri, text)
return link_btn | Function creates a link button with corresponding text and
URI reference |
357,325 | def init_db(self):
if self.database == :
db_path = os.path.join(EXPFACTORY_DATA, % EXPFACTORY_SUBID)
self.database = % db_path
bot.info("Database located at %s" % self.database)
self.engine = create_engine(self.database, convert_unicode=True)
self.session = scoped_session(s... | initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db |
357,326 | def paintEvent( self, event ):
super(XMenu, self).paintEvent(event)
if self.showTitle():
with XPainter(self) as painter:
palette = self.palette()
painter.setBrush(palette.color(palette.Button))
painter.setPen(... | Overloads the paint event for this menu to draw its title based on its \
show title property.
:param event | <QPaintEvent> |
357,327 | def get_gradebooks_by_grade_system(self, grade_system_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_gradebook_lookup_session(proxy=self._proxy)
return lookup_session.get_gradebooks_by_ids(
self.get_gradebook_ids_by_grade_syste... | Gets the list of ``Gradebooks`` mapped to a ``GradeSystem``.
arg: grade_system_id (osid.id.Id): ``Id`` of a
``GradeSystem``
return: (osid.grading.GradebookList) - list of gradebooks
raise: NotFound - ``grade_system_id`` is not found
raise: NullArgument - ``grade_sys... |
357,328 | def solve(self,b):
x = b.copy()
self.mumps.set_rhs(x)
self.mumps.run(job=3)
return x | Solves system Ax=b.
Parameters
----------
b : ndarray
Returns
-------
x : ndarray |
357,329 | def rev_parse(repo, rev):
if rev.startswith():
raise NotImplementedError("commit by message search ( regex )")
obj = None
ref = None
output_type = "commit"
start = 0
parsed_to = 0
lr = len(rev)
while start < lr:
if rev[start] not in "^~:@":
... | :return: Object at the given revision, either Commit, Tag, Tree or Blob
:param rev: git-rev-parse compatible revision specification as string, please see
http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html
for details
:raise BadObject: if the given revision could not be found
... |
357,330 | def sha1(self):
if self._sha1 is None:
self._sha1 = hashlib.sha1(byte_cls(self[])).digest()
return self._sha1 | :return:
The SHA1 hash of the DER-encoded bytes of this public key info |
357,331 | def info(self, message):
return self._log(
message=message.upper(),
stream=sys.stdout
) | Logs an informational message to stdout.
This method should only be used by the Runner. |
357,332 | def _hash_the_file(hasher, filename):
BUF_SIZE = 65536
with open(filename, ) as f:
buf = f.read(BUF_SIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BUF_SIZE)
return hasher | Helper function for creating hash functions.
See implementation of :func:`dtoolcore.filehasher.shasum`
for more usage details. |
357,333 | def iter_next(self) -> bool:
sources_sentences = [[] for x in self.sources_sentences]
target_sentences = []
num_read = 0
for num_read, (sources, target) in enumerate(parallel_iterate(self.sources_iters, self.target_iter, skip_blanks=False), 1):
source_l... | True if the iterator can return another batch. |
357,334 | def add_filters(self, filterer, filters):
for f in filters:
try:
filterer.addFilter(self.config[][f])
except StandardError as e:
raise ValueError( % (f, e)) | Add filters to a filterer from a list of names. |
357,335 | def tokenize_conf_stream(conf_handle):
for line in conf_handle:
if line.startswith("
continue
tokens = line.split("=")
if len(tokens) != 2:
continue
yield (tokens[0].strip(), tokens[1].strip()) | convert the key=val pairs in a LSF config stream to tuples of tokens |
357,336 | def _set_default__configuration_options(app):
app.config.setdefault(, "token")
app.config.setdefault(, "refresh_token")
app.config.setdefault(, datetime.timedelta(minutes=15))
app.config.setdefault(, datetime.timedelta(days=30))
app.config.setdefault(, None)
... | Sets the default configuration options used by this extension |
357,337 | def evaluate(self, eval_iter: data_io.BaseParallelSampleIter, eval_metric: mx.metric.EvalMetric):
for eval_batch in eval_iter:
self.module.forward(eval_batch, is_train=False)
self.module.update_metric(eval_metric, eval_batch.label) | Resets and recomputes evaluation metric on given data iterator. |
357,338 | def text_filter_changed(self, text):
text = text.strip() if text else None
if text is not None:
self.__text_filter = ListModel.TextFilter("text_for_filter", text)
else:
self.__text_filter = None
self.__update_filter() | Called to handle changes to the text filter.
:param text: The text for the filter. |
357,339 | def has_cjk(self):
cjk_codepoint_ranges = [
(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215),
(63744, 64255), (65072, 65103), (65381, 65500), (131072, 196607)]
for char in self.word:
if any([start <= ord(char) <= end
for start, end in cjk_codepoint_ranges]):
... | Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character. |
357,340 | def setup_jukebox_logger():
log = logging.getLogger("jb")
log.propagate = False
handler = logging.StreamHandler(sys.stdout)
fmt = "%(levelname)-8s:%(name)s: %(message)s"
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
log.addHandler(handler)
level = DEFAULT_LOGGIN... | Setup the jukebox top-level logger with handlers
The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox.
It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output.
The logger default level is defined in the co... |
357,341 | def Main():
multiprocessing.freeze_support()
input_reader = cli_tools.StdinInputReader()
tool = psort_tool.PsortTool(input_reader=input_reader)
if not tool.ParseArguments():
return False
have_list_option = False
if tool.list_analysis_plugins:
tool.ListAnalysisPlugins()
have_list_option = T... | The main function. |
357,342 | def add_record(self, msg_id, rec):
rec = self._binary_buffers(rec)
self._records.insert(rec) | Add a new Task Record, by msg_id. |
357,343 | def matrix_params_from_table(table, transpose=False):
classes = sorted(table.keys())
map_dict = {k: 0 for k in classes}
TP_dict = map_dict.copy()
TN_dict = map_dict.copy()
FP_dict = map_dict.copy()
FN_dict = map_dict.copy()
for i in classes:
TP_dict[i] = table[i][i]
sum_... | Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN] |
357,344 | def _connect(self):
if self._ec2_connection:
return self._ec2_connection
if not self._vpc:
vpc_connection = None
try:
log.debug("Connecting to ec2 host %s", self._ec2host)
region = ec2.regioninfo.RegionInfo(name=self._region_nam... | Connects to the ec2 cloud provider
:return: :py:class:`boto.ec2.connection.EC2Connection`
:raises: Generic exception on error |
357,345 | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
self.fileExtension = extension
KEYWORDS = (,
,
,
,
)
with ope... | Link Node Dataset File Read from File Method |
357,346 | def _weaken_key(flags, key):
if flags & NegotiateFlag.NTLMSSP_KEY_128:
return key
if flags & NegotiateFlag.NTLMSSP_NEGOTIATE_56:
return key[:7]
else:
return key[:5] | NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or
secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under
NTLM2. In this case, the master key is used directly in the generation of subkeys ... |
357,347 | def _add_header_domains_xml(self, document):
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
)
header_element.setAttribute(, domain)
header_element.setAttribute(, .join(attrs[]))
if n... | Generates the XML elements for allowed header domains. |
357,348 | def _get_binary_replacement(first, second, cls):
expr = ProtoExpr([first, second], {})
if LOG:
logger = logging.getLogger()
for key, rule in cls._binary_rules.items():
pat, replacement = rule
match_dict = match_pattern(pat, expr)
if match_dict:
try:
... | Helper function for match_replace_binary |
357,349 | def facets_by_halfspace(self):
if self._fbh_out is None:
output = qhalf(, self.halfspaces, self.interior_point)
facets = []
for l in output[1:]:
facets.append([int(i) for i in l.split()[1:]])
self._fbh_out = facets
return self._fbh... | Returns a list of vertex indices for each halfspace
e.g: facets_by_halfspace[0] is the list of indices ov vertices
incident to halfspace 0 |
357,350 | def _dump_crawl_stats(self):
extras = {}
spiders = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys()
for key in keys:
elements = key.split(":")
spider = elements[3]
if spider not in spid... | Dumps flattened crawling stats so the spiders do not have to |
357,351 | def trim_trailing_silence(obj):
_check_supported(obj)
copied = deepcopy(obj)
length = copied.get_active_length()
copied.pianoroll = copied.pianoroll[:length]
return copied | Return a copy of the object with trimmed trailing silence of the
piano-roll(s). |
357,352 | def folders(self):
if self._folders is None :
self.__init()
if self._folders is not None and isinstance(self._folders, list):
if len(self._folders) == 0:
self._loadFolders()
return self._folders | gets the property value for folders |
357,353 | def get_by_identifier(self, identifier):
params = {: identifier}
return self.client.get(self._url(), params=params) | Gets blocks by identifier
Args:
identifier (str): Should be any of: username, phone_number, email.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks |
357,354 | def state_machine_change_after(self, model, prop_name, info):
if in info and info[] == :
method_name, model, result, arguments, instance = self._extract_info_data(info[])
if self.model.ongoing_complex_actions:
return
if (isinstance(re... | Called on any change within th state machine
This method is called, when any state, transition, data flow, etc. within the state machine changes. This
then typically requires a redraw of the graphical editor, to display these changes immediately.
:param rafcon.gui.models.state_machine.StateMac... |
357,355 | def angle_v2_rad(vec_a, vec_b):
return math.acos(vec_a.dot(vec_b) / (vec_a.length() * vec_b.length())) | Returns angle between vec_a and vec_b in range [0, PI]. This does not
distinguish if a is left of or right of b. |
357,356 | def stop_transmit(self, *ports):
port_list = self.set_ports_list(*ports)
self.api.call_rc(.format(port_list))
time.sleep(0.2) | Stop traffic on ports.
:param ports: list of ports to stop traffic on, if empty start on all ports. |
357,357 | def AddEnumDescriptor(self, enum_desc):
if not isinstance(enum_desc, descriptor.EnumDescriptor):
raise TypeError()
self._enum_descriptors[enum_desc.full_name] = enum_desc
self.AddFileDescriptor(enum_desc.file) | Adds an EnumDescriptor to the pool.
This method also registers the FileDescriptor associated with the message.
Args:
enum_desc: An EnumDescriptor. |
357,358 | def add_point_labels(self, points, labels, italic=False, bold=True,
font_size=None, text_color=,
font_family=None, shadow=False,
show_points=True, point_color=, point_size=5,
name=None):
if font_family i... | Creates a point actor with one label from list labels assigned to
each point.
Parameters
----------
points : np.ndarray
n x 3 numpy array of points.
labels : list
List of labels. Must be the same length as points.
italic : bool, optional
... |
357,359 | def p_stmt_cmp_eq(p):
p[0] = ast.EqNode(ast.VariableNode(p[1]), ast.CmpExprNode(p[4], p[3], p[5])) | stmt : VAR EQUALS value comparison_op value |
357,360 | def check(qpi_or_h5file, checks=["attributes", "background"]):
if isinstance(checks, str):
checks = [checks]
for ch in checks:
if ch not in ["attributes", "background"]:
raise ValueError("Unknown check: {}".format(check))
if isinstance(qpi_or_h5file, QPImage):
qpi =... | Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to perform ("attributes" and/or "background")
Raises
------
Int... |
357,361 | def run(self):
client = None
if self.cmd_args.subcommand in self.API_SUBCOMMAND:
email, api_key = TagCubeCLI.get_credentials(self.cmd_args)
client = TagCubeClient(email, api_key, verbose=self.cmd_args.verbose)
subcommands = {: do_auth_test,
... | This method handles the user's command line arguments, for example, if
the user specified a path file we'll open it and read the contents.
Finally it will run the scan using TagCubeClient.scan(...)
:return: The exit code for our process |
357,362 | def find( self, flags = 0 ):
if ( not (self._textEdit or self._webView) ):
fg = QColor()
bg = QColor().lighter(180)
palette = self.palette()
palette.setColor(palette.Text, fg)
palette.setColor(palette.Base, bg)
... | Looks throught the text document based on the current criteria. The \
inputed flags will be merged with the generated search flags.
:param flags | <QTextDocument.FindFlag>
:return <bool> | success |
357,363 | def sort(x, axis=-1, reverse=False, with_index=False, only_index=False):
from .function_bases import sort as sort_base
n_outputs = 2 if with_index and not only_index else 1
return sort_base(x, axis, reverse, with_index, only_index, n_outputs) | Sorts the elements of `x` along a given `axis` in ascending order
by value. A negative `axis` counts from the last dimension of `x`,
so the default of -1 sorts along the last dimension. If `reverse`
is True, then the elements are soreted in descending order.
If `with_index` is True, result is a tuple `... |
357,364 | def _sub_ms_char(self, match):
orig = match.group(1)
if self.smart_quotes_to == :
sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
else:
sub = self.MS_CHARS.get(orig)
if type(sub) == tuple:
if self.smart_quotes_to == :
... | Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character. |
357,365 | def afw_word_acceptance(afw: dict, word: list) -> bool:
return __recursive_acceptance(afw, afw[], word) | Checks if a **word** is accepted by input AFW, returning
True/False.
The word w is accepted by a AFW if exists at least an
accepting run on w. A run for AFWs is a tree and
an alternating automaton can have multiple runs on a given
input.
A run is accepting if all the leaf nodes are accepting st... |
357,366 | def obj_in_list_always(target_list, obj):
for item in set(target_list):
if item is not obj:
return False
return True | >>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False |
357,367 | def _get_tag(self, url, tag, print_warn=True):
complete_url = urljoin(self.base_url, url)
if requests.get( + complete_url).ok:
if tag == :
return .format(complete_url)
elif tag == :
return .format(complete_ur... | Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable |
357,368 | def stroke_opacity(value):
if value.value:
_assert_is_type(, value.value,
(float, int))
if value.value < 0 or value.value > 1:
raise ValueError(
) | ValueRef : number, opacity of the stroke (0 to 1) |
357,369 | def duplicates(base, items):
for item in items:
if item.similarity(base) and not item.equality(base):
yield item | Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base |
357,370 | def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False,
region=None, key=None, keyid=None, profile=None):
acl-5fb85d36myacl
if disassociate:
network_acl = _get_resource(, name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile)
... | Delete a network acl based on the network_acl_id or network_acl_name provided.
CLI Examples:
.. code-block:: bash
salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\
disassociate=false
.. code-block:: bash
salt myminion boto_vpc.delete_network_acl ... |
357,371 | def validate_voicing(ref_voicing, est_voicing):
if ref_voicing.size == 0:
warnings.warn("Reference voicing array is empty.")
if est_voicing.size == 0:
warnings.warn("Estimated voicing array is empty.")
if ref_voicing.sum() == 0:
warnings.warn("Reference melody has no voiced fram... | Checks that voicing inputs to a metric are in the correct format.
Parameters
----------
ref_voicing : np.ndarray
Reference boolean voicing array
est_voicing : np.ndarray
Estimated boolean voicing array |
357,372 | def set_authorization_password(self, password):
self.authorization_password = password
self.changed_event.emit(self) | Changes the authorization password of the account.
:type password: string
:param password: The new authorization password. |
357,373 | def make_session(self):
with connect_lock:
if self._sf_session is None:
sf_session = requests.Session()
sf_session.auth = SalesforcePasswordAuth(db_alias=self.alias,
settings_dict=self.... | Authenticate and get the name of assigned SFDC data server |
357,374 | def has_printout(
state, index, not_printed_msg=None, pre_code=None, name=None, copy=False
):
extra_msg = "If you want to check printouts done in e.g. a for loop, you have to use a `check_function()` chain instead."
state.assert_root("has_printout", extra_msg=extra_msg)
if not_printed_msg is None... | Check if the right printouts happened.
``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
the solution process, capture its output, and verify whether the output is present in the output of the student.
This ... |
357,375 | def set_call_back(self, func):
self.timer.add_callback(func)
self.timer.start() | sets callback function for updating the plot.
in the callback function implement the logic of reading of serial input
also the further processing of the signal if necessary has to be done
in this
callbak function. |
357,376 | def nside_to_npix(nside):
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return 12 * nside ** 2 | Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map. |
357,377 | def _sequence(self, i):
result = []
end_range = 0
escape_hyphen = -1
removed = False
last_posix = False
c = next(i)
if c in (, ):
result.append()
c = next(i)
if c == :
last_posix = self._handle_po... | Handle character group. |
357,378 | def volatility(data, period):
volatility = sd(data, period) / sv(data, period)
return volatility | Volatility.
Formula:
SDt / SVt |
357,379 | def _set_interface_fe(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=interface_fe.interface_fe, is_container=, presence=False, yang_name="interface-fe", rest_name="", parent=self, choice=(u, u), path_helper=self._path_helper, extmethods=self._extmeth... | Setter method for interface_fe, mapped from YANG variable /rule/command/interface_fe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_fe is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._s... |
357,380 | def to_json(self, filename, indent=2):
d = self.to_dicts()
if hasattr(filename, "write"):
json.dump(d, filename, indent=indent)
elif isinstance(filename, string_types):
with open(os.path.expanduser(filename), "w") as f:
json.dump(d, f, indent=inde... | Return a JSON string of all model inputs and outputs.
Parameters
----------
filename : str or file
Either the file name (string) or an open file (file-like object)
where the data will be saved.
indent : int, optional
Indentation level for JSON output.... |
357,381 | def update_variable_group(self, group, project, group_id):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if group_id is not None:
route_values[] = self._serialize.url(, group_id, )
content = self._serialize.bo... | UpdateVariableGroup.
[Preview API] Update a variable group.
:param :class:`<VariableGroupParameters> <azure.devops.v5_1.task_agent.models.VariableGroupParameters>` group: Variable group to update.
:param str project: Project ID or project name
:param int group_id: Id of the variable grou... |
357,382 | def get_chromosome_lengths(fasta_file, fancy_sort=True):
chromlen = []
with gzip.open(fasta_file, , encoding=) as fh:
fasta = SeqIO.parse(fh, )
for i, f in enumerate(fasta):
chromlen.append((f.id, len(f.seq)))
_LOGGER.info(, f.id)
... | Extract chromosome lengths from genome FASTA file. |
357,383 | def create_subnetwork(kwargs=None, call=None):
if call != :
raise SaltCloudSystemExit(
)
if not kwargs or not in kwargs:
log.error(
)
return False
if not in kwargs:
log.errror(
)
return False
... | ... versionadded:: 2017.7.0
Create a GCE Subnetwork. Must specify name, cidr, network, and region.
CLI Example:
.. code-block:: bash
salt-cloud -f create_subnetwork gce name=mysubnet network=mynet1 region=us-west1 cidr=10.0.0.0/24 description=optional |
357,384 | def run(self):
while True:
self.connect_lock.acquire()
if self.stopped():
return
self.__connect()
self.connect_lock.release()
self.ws.run_forever() | If the connection drops, then run_forever will terminate and a
reconnection attempt will be made. |
357,385 | def convert(self, argument):
if isinstance(argument, str):
if argument.lower() in [, , ]:
return True
elif argument.lower() in [, , ]:
return False
bool_argument = bool(argument)
if argument == bool_argument:
return bool_argument
raise ValueError(, ... | Converts the argument to a boolean; raise ValueError on errors. |
357,386 | def get(self, name):
resolvable, packages, parent, constraint_only = self._collapse().get(
self.normalize(name), _ResolvedPackages.empty())
return packages | Get the set of compatible packages given a resolvable name. |
357,387 | def aks_versions_table_format(result):
from jmespath import compile as compile_jmes, Options
parsed = compile_jmes()
results = parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions()))
return sorted(results, key=lambda x: version_to_tuple(x.get()), revers... | Format get-versions results as a summary for display with "-o table". |
357,388 | def verify_signature(self, signature_filename, data_filename,
keystore=None):
if not self.gpg:
raise DistlibException(
)
cmd = self.get_verify_command(signature_filename, data_filename,
... | Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which... |
357,389 | def adj_par_names(self):
adj_names = []
for t,n in zip(self.parameter_data.partrans,
self.parameter_data.parnme):
if t.lower() not in ["tied","fixed"]:
adj_names.append(n)
return adj_names | get the adjustable (not fixed or tied) parameter names
Returns
-------
adj_par_names : list
list of adjustable (not fixed or tied) parameter names |
357,390 | def connect(self, address):
tout = _timeout(self.gettimeout())
while 1:
self._wait_event(tout.now, write=True)
err = self._connect(address, tout.now)
if err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
continue
if err... | connects to the address and wraps the connection in an SSL context |
357,391 | def cosbetas(self):
coords = self.coords_for_computations
norms = self.normals_for_computations
cosbetas = libphoebe.scalproj_cosangle(
np.ascontiguousarray(coords),
np.ascontiguousarray(norms)
)
return ComputedColumn(sel... | TODO: add documentation
(ComputedColumn) |
357,392 | def zoning_defined_configuration_zone_member_entry_entry_name(self, **kwargs):
config = ET.Element("config")
zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone")
defined_configuration = ET.SubElement(zoning, "defined-configuration")
zone = ET.SubEl... | Auto Generated Code |
357,393 | def _xml_escape(data):
from_symbols = &;' for s in "amp gt lt quot apos".split())
for from_,to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
return data | Escape &, <, >, ", ', etc. in a string of data. |
357,394 | def _generateForServerTokenSecurity(self,
serverURL,
token,
tokenUrl,
referer,
expiration=None
... | generates a token for a feature service |
357,395 | def referenceframe(self, event):
self.log("Got a reference frame update! ", event, lvl=verbose)
self.referenceframe = event.data | Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message |
357,396 | def mpl_palette(name, n_colors=6):
brewer_qual_pals = {"Accent": 8, "Dark2": 8, "Paired": 12,
"Pastel1": 9, "Pastel2": 8,
"Set1": 9, "Set2": 8, "Set3": 12}
if name.endswith("_d"):
pal = ["
pal.extend(color_palette(name.replace("_d", "_r"), 2)... | Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
n... |
357,397 | def _imm_init_setattr(self, name, value):
s initial setattr allows only param
params = _imm_param_data(self)
if name in params:
tx_fn = params[name][1]
value = value if tx_fn is None else tx_fn(value)
object.__getattribute__(self, )[name] = value
| An immutable's initial setattr allows only param's to be set and does not run checks on the new
parameters until a full parameter-set has been specified, at which point it runs all checks and
switches over to a normal setattr and getattr method. |
357,398 | def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, verifier_name, template):
command_args = {
: dependency_name,
: driver_name,
: lint_name,
: provisioner_name,
: role_name,
: command_base.MOLECULE_DEFAULT_SCENARIO_NAME... | Initialize a new role for use with Molecule. |
357,399 | def new_closure(vals):
args = .join( % i for i in range(len(vals)))
f = eval("lambda %s:lambda:(%s)" % (args, args))
if sys.version_info[0] >= 3:
return f(*vals).__closure__
return f(*vals).func_closure | Build a new closure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.