Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
16,500 | def check_exclamations_ppm(text):
err = "leonard.exclamation.30ppm"
msg = u"More than 30 ppm of exclamations. Keep them under control."
regex = r"\w!"
count = len(re.findall(regex, text))
num_words = len(text.split(" "))
ppm = (count*1.0 / num_words) * 1e6
if ppm > 30 and count > 1:... | Make sure that the exclamation ppm is under 30. |
16,501 | def sign_more(self, bucket, cos_path, expired):
return self.app_sign(bucket, cos_path, expired) | 多次签名(针对上传文件,创建目录, 获取文件目录属性, 拉取目录列表)
:param bucket: bucket名称
:param cos_path: 要操作的cos路径, 以'/'开始
:param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒
:return: 签名字符串 |
16,502 | def recommend(self, client_data, limit, extra_data={}):
preinstalled_addon_ids = client_data.get("installed_addons", [])
extended_limit = limit + len(preinstalled_addon_ids)
ensemble_suggestions = self._ensemble_recommender.recommend(
client_data, extend... | Hybrid recommendations simply select half recommendations from
the ensemble recommender, and half from the curated one.
Duplicate recommendations are accomodated by rank ordering
by weight. |
16,503 | def populate(self, priority, address, rtr, data):
assert isinstance(data, bytes)
self.needs_high_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
tmp = (data[0] >> 1) & 0x03
... | :return: None |
16,504 | def _add_video_timing(self, pic):
sld = self._spTree.xpath()[0]
childTnLst = sld.get_or_add_childTnLst()
childTnLst.add_video(pic.shape_id) | Add a `p:video` element under `p:sld/p:timing`.
The element will refer to the specified *pic* element by its shape
id, and cause the video play controls to appear for that video. |
16,505 | def new_evaluation_result(self, has_improved: bool) -> bool:
if self.lr is None:
assert self.base_lr is not None
self.lr = self.base_lr
if has_improved:
self.num_not_improved = 0
else:
self.num_not_improved += 1
if self.num_not... | Returns true if the parameters should be reset to the ones with the best validation score.
:param has_improved: Whether the model improved on held-out validation data.
:return: True if parameters should be reset to the ones with best validation score. |
16,506 | def getFlaskResponse(responseString, httpStatus=200):
return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE) | Returns a Flask response object for the specified data and HTTP status. |
16,507 | def which(program, ignore_own_venv=False):
if not program:
return None
if os.path.isabs(program):
return program if is_executable(program) else None
for p in os.environ.get("PATH", "").split(":"):
fp = os.path.join(p, program)
if (not ignore_own_venv or not fp.startswith... | :param str|None program: Program name to find via env var PATH
:param bool ignore_own_venv: If True, do not resolve to executables in current venv
:return str|None: Full path to program, if one exists and is executable |
16,508 | def trim(self, lower=None, upper=None):
if lower is None:
lower = getattr(self.subpars.eqi2, , None)
if upper is None:
upper = getattr(self.subpars.eqb, , None)
super().trim(lower, upper) | Trim upper values in accordance with
:math:`EQI2 \\leq EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqb.value = 3.0
>>> eqi2.value = 1.0
>>> eqi1(0.0)
>>> eqi1
eqi1(1.0)
>>> eqi1(1.0)
>>> eqi1
e... |
16,509 | def _build_biomart_gene_query(self, taxid, cols_to_fetch):
taxid = str(taxid)
if taxid != :
cols_to_fetch = [x for x in cols_to_fetch if x != ]
query_attributes = {
"virtualSchemaName": "default", "formatter": "TSV", "header": "0",
... | Building url to fetch equivalent identifiers via Biomart Restful API.
Documentation at
http://uswest.ensembl.org/info/data/biomart/biomart_restful.html
:param taxid:
:param array of ensembl biomart attributes to include
:return: |
16,510 | def parse_command_line_parameters():
usage =
version =
parser = OptionParser(usage=usage, version=version)
parser.add_option(, , action=,
dest=, default=False,
help=
)
parser.add_option(, , action=, type=,
... | Parses command line arguments |
16,511 | def fit_left_censoring(
self,
durations,
event_observed=None,
timeline=None,
label=None,
alpha=None,
ci_labels=None,
show_progress=False,
entry=None,
weights=None,
):
self.durations = np.asarray(pass_for_numeric_dtyp... | Fit the model to a left-censored dataset
Parameters
----------
durations: an array, or pd.Series
length n, duration subject was observed for
event_observed: numpy array or pd.Series, optional
length n, True if the the death was observed, False if the event was lost (... |
16,512 | def _absorb_z_into_w(moment_index: int,
op: ops.Operation,
state: _OptimizerState) -> None:
t = cast(float, _try_get_known_z_half_turns(op))
q = op.qubits[0]
state.held_w_phases[q] = cast(float, state.held_w_phases[q]) + t / 2
state.deletions.append((moment... | Absorbs a Z^t gate into a W(a) flip.
[Where W(a) is shorthand for PhasedX(phase_exponent=a).]
Uses the following identity:
───W(a)───Z^t───
≡ ───W(a)───────────Z^t/2──────────Z^t/2─── (split Z)
≡ ───W(a)───W(a)───Z^-t/2───W(a)───Z^t/2─── (flip Z)
≡ ───W(a)───W(a)──────────W(a+t... |
16,513 | def make_subscriber(self, my_args=None):
LOGGER.debug("zeromq.Driver.make_subscriber")
if my_args is None:
raise exceptions.ArianeConfError()
if not self.configuration_OK or self.connection_args is None:
raise exceptions.ArianeConfError()
subscriber = Sub... | not implemented
:return: |
16,514 | def apply_filter(self, strings):
result = strings
for filt in self.filters:
result = filt.apply_filter(result)
self.log([u"Applying regex: => ", strings, result])
return result | Apply the text filter filter to the given list of strings.
:param list strings: the list of input strings |
16,515 | def _get_login_manager(self,
app: FlaskUnchained,
anonymous_user: AnonymousUser,
) -> LoginManager:
login_manager = LoginManager()
login_manager.anonymous_user = anonymous_user or AnonymousUser
login_manage... | Get an initialized instance of Flask Login's
:class:`~flask_login.LoginManager`. |
16,516 | def set_end_date(self, date):
if date is None:
raise NullArgument()
if self.get_end_date_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_date_time(date, self.get_end_date_metadata()):
raise InvalidArgument()
... | Sets the end date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null``
*compliance: mandatory -- This method must be implemented.... |
16,517 | def example_exc_handler(tries_remaining, exception, delay):
print >> stderr, "Caught , {1} tries remaining, \
sleeping for {2} seconds".format(exception, tries_remaining, delay) | Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised. |
16,518 | def build_notification_message(template_context, template_configuration=None):
if (
template_configuration is not None and
template_configuration.html_template and
template_configuration.plaintext_template
):
plain_msg, html_msg = template_configuration.render_al... | Create HTML and plaintext message bodies for a notification.
We receive a context with data we can use to render, as well as an optional site
template configration - if we don't get a template configuration, we'll use the
standard, built-in template.
Arguments:
template_context (dict): A set o... |
16,519 | def scan_file(self, filename, apikey):
url = self.base_url + "file/scan"
params = {: apikey}
scanfile = {"file": open(filename, )}
response = requests.post(url, files=scanfile, params=params)
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
i... | Sends a file to virus total for assessment |
16,520 | def check_docstring(cls):
docstring = inspect.getdoc(cls)
if not docstring:
breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1])
msg = "docstring required for plugin (%s, defined in %s)"
args = (cls.__name__, breadcrumbs, cls.__modul... | Asserts that the class has a docstring, returning it if successful. |
16,521 | def schunk(string, size):
return [string[i:i+size] for i in range(0, len(string), size)] | Splits string into n sized chunks. |
16,522 | def __get_favorites(self, favorite_type, start=0, max_items=100):
if favorite_type not in (RADIO_SHOWS, RADIO_STATIONS):
favorite_type = SONOS_FAVORITES
response = self.contentDirectory.Browse([
(,
if favorite_type is SONOS_FAVORITES
else .for... | Helper method for `get_favorite_radio_*` methods.
Args:
favorite_type (str): Specify either `RADIO_STATIONS` or
`RADIO_SHOWS`.
start (int): Which number to start the retrieval from. Used for
paging.
max_items (int): The total number of results... |
16,523 | def get_fetch_headers(self, method, headers):
all_headers = self.headers.copy()
if headers:
all_headers.update(headers)
return Headers(all_headers) | merge class headers with passed in headers
:param method: string, (eg, GET or POST), this is passed in so you can customize
headers based on the method that you are calling
:param headers: dict, all the headers passed into the fetch method
:returns: passed in headers merged with glo... |
16,524 | def reinterpretBits(self, sigOrVal, toType):
if isinstance(sigOrVal, Value):
return reinterpretBits__val(self, sigOrVal, toType)
elif isinstance(toType, Bits):
return fitTo_t(sigOrVal, toType)
elif sigOrVal._dtype.bit_length() == toType.bit_length():
if isinstance(toType, HStruc... | Cast object of same bit size between to other type
(f.e. bits to struct, union or array) |
16,525 | def coord_pyramids(coords, zoom_start, zoom_stop):
for coord in coords:
for child in coord_pyramid(coord, zoom_start, zoom_stop):
yield child | generate full pyramid for coords
Generate the full pyramid for the list of coords. Note that zoom_stop is
exclusive. |
16,526 | def _filter_properties(obj, property_list):
if property_list is not None:
property_list = [p.lower() for p in property_list]
for pname in obj.properties.keys():
if pname.lower() not in property_list:
del obj.properties[pname] | Remove properties from an instance or class that aren't in the
plist parameter
obj(:class:`~pywbem.CIMClass` or :class:`~pywbem.CIMInstance):
The class or instance from which properties are to be filtered
property_list(list of :term:`string`):
List of properties which a... |
16,527 | def simulated_annealing(objective_function,
initial_array,
initial_temperature=10 ** 4,
cooldown_rate=0.7,
acceptance_criteria=None,
lower_bound=-float(),
max_iterations=10 ** ... | Implement a simulated annealing algorithm with exponential cooling
Has two stopping conditions:
1. Maximum number of iterations;
2. A known lower bound, a none is passed then this is not used.
Note that starting with an initial_temperature corresponds to a hill
climbing algorithm |
16,528 | def configure(self, options, conf):
super(ProgressivePlugin, self).configure(options, conf)
if (getattr(options, , 0) > 1 and
getattr(options, , False)):
print (
)
if options.with_bar:
options.with_s... | Turn style-forcing on if bar-forcing is on.
It'd be messy to position the bar but still have the rest of the
terminal capabilities emit ''. |
16,529 | async def set_mode(self, mode, timeout=OTGW_DEFAULT_TIMEOUT):
cmd = OTGW_CMD_MODE
status = {}
ret = await self._wait_for_cmd(cmd, mode, timeout)
if ret is None:
return
if mode is OTGW_MODE_RESET:
self._protocol.status = {}
await self.g... | Set the operating mode to either "Gateway" mode (:mode: =
OTGW_MODE_GATEWAY or 1) or "Monitor" mode (:mode: =
OTGW_MODE_MONITOR or 0), or use this method to reset the device
(:mode: = OTGW_MODE_RESET).
Return the newly activated mode, or the full renewed status
dict after a reset... |
16,530 | def could_scope_out(self):
return not self.waiting_for or \
isinstance(self.waiting_for, callable.EndOfStory) or \
self.is_breaking_a_loop() | could bubble up from current scope
:return: |
16,531 | def toDict(self):
dRet = super(Parent,self).toDict()
for k,v in iteritems(self._nodes):
dRet[k] = v.toDict()
return dRet | To Dict
Returns the Parent as a dictionary in the same format as is used in
constructing it
Returns:
dict |
16,532 | def remove_unit_rules(grammar, inplace=False):
if inplace is False:
grammar = copy(grammar)
res = find_nonterminals_reachable_by_unit_rules(grammar)
for rule in grammar.rules.copy():
if _is_unit(rule):
grammar.rules.remove(rule)
conti... | Remove unit rules from the grammar.
:param grammar: Grammar where remove the rules.
:param inplace: True if transformation should be performed in place. False by default.
:return: Grammar without unit rules. |
16,533 | def semantic_similarity(go_id1, go_id2, godag, branch_dist=None):
dist = semantic_distance(go_id1, go_id2, godag, branch_dist)
if dist is not None:
return 1.0 / float(dist) | Finds the semantic similarity (inverse of the semantic distance)
between two GO terms. |
16,534 | def model_performance(self, test_data=None, train=False, valid=False, xval=False):
if test_data is None:
if not train and not valid and not xval: train = True
if train: return self._model_json["output"]["training_metrics"]
if valid: return self._model_json["output"... | Generate model metrics for this model on test_data.
:param H2OFrame test_data: Data set for which model metrics shall be computed against. All three of train,
valid and xval arguments are ignored if test_data is not None.
:param bool train: Report the training metrics for the model.
... |
16,535 | def _smixins(self, name):
return (self._mixins[name] if name in self._mixins else False) | Inner wrapper to search for mixins by name. |
16,536 | def get_hostfirmware(self,callb=None):
if self.host_firmware_version is None:
mypartial=partial(self.resp_set_hostfirmware)
if callb:
mycallb=lambda x,y:(mypartial(y),callb(x,y))
else:
mycallb=lambda x,y:mypartial(y)
respon... | Convenience method to request the device firmware info from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that callb be executed when a response ... |
16,537 | def add_host(kwargs=None, call=None):
DOMAIN\\userverybadpassvcenter01.domain.comrootmyhostpassword12:A3:45:B6:CD:7E:F8:90:A1:BC:23:45:D6:78:9E:FA:01:2B:34:CD
if call != :
raise SaltCloudSystemExit(
)
host_name = kwargs.get() if kwargs and in kwargs else None
... | Add a host system to the specified cluster or datacenter in this VMware environment
.. note::
To use this function, you need to specify ``esxi_host_user`` and
``esxi_host_password`` under your provider configuration set up at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/v... |
16,538 | def plotOptMod(verNObg3gray, VERgray):
if VERgray is None and verNObg3gray is None:
return
fg = figure()
ax2 = fg.gca()
if VERgray is not None:
z = VERgray.alt_km
Ek = VERgray.energy_ev.values
props = {: , : , : 0.5}
fgs, axs = fg.subplots(6, 6, sharex=... | called from either readTranscar.py or hist-feasibility/plotsnew.py |
16,539 | def remover(self, id_interface):
if not is_valid_int_param(id_interface):
raise InvalidParameterError(
u)
url = + str(id_interface) +
code, xml = self.submit(None, , url)
return self.response(code, xml) | Remove an interface by its identifier.
:param id_interface: Interface identifier.
:return: None
:raise InterfaceNaoExisteError: Interface doesn't exist.
:raise InterfaceError: Interface is linked to another interface.
:raise InvalidParameterError: The interface identifier is i... |
16,540 | def parse(self, text):
if isinstance(text, bytes):
text = text.decode("ascii")
text = re.sub("\s+", " ", unidecode(text))
return self.communicate(text + "\n") | Call the server and return the raw results. |
16,541 | def _scale(x, min_x_value, max_x_value, output_min, output_max):
if round(min_x_value - max_x_value, 7) == 0:
raise ValueError()
def _scale(x):
min_x_valuef = tf.to_float(min_x_value)
max_x_valuef = tf.to_float(max_x_value)
output_minf = tf.to_float(output_min)
output_maxf = tf.to... | Scale a column to [output_min, output_max].
Assumes the columns's range is [min_x_value, max_x_value]. If this is not
true at training or prediction time, the output value of this scale could be
outside the range [output_min, output_max].
Raises:
ValueError: if min_x_value = max_x_value, as the column is ... |
16,542 | def get_scripts():
proc = Popen([, ], stdout=PIPE)
should_yeild = False
for line in proc.stdout.readlines():
line = line.decode()
if in line:
should_yeild = True
continue
if should_yeild and re.match(r, line):
yield line.strip().split()[0] | Get custom npm scripts. |
16,543 | def DeserializeUnsignedWithoutType(self, reader):
self.Version = reader.ReadByte()
self.DeserializeExclusiveData(reader)
self.Attributes = reader.ReadSerializableArray(,
max=self.MAX_TX_ATTRIBUTES)
self.inputs = reader.ReadS... | Deserialize object without reading transaction type data.
Args:
reader (neo.IO.BinaryReader): |
16,544 | def _tp_finder(self, dcycle):
last_cycle = int(self.se.cycles[len(self.se.cycles)-1])
cyc_tp = list(range(1,last_cycle + dcycle, dcycle))
all_data = array(self.get(cyc_tp,[,,,,]))
c_nf = np.zeros(len(all_data))
o_nf = np.zeros(len(all_data))
for i in ... | Routine to find thermal pulses in given star and returns an
index vector that gives the cycle number in which the thermal
pulse occure.
The routine looks for the C/O ratio jumping up and up, so only
useful in TP-AGB star. A vector is given back that indicates
the position of th... |
16,545 | def getBlock(self, block_identifier, full_transactions=False):
method = select_method_for_block_identifier(
block_identifier,
if_predefined=,
if_hash=,
if_number=,
)
result = self.web3.manager.request_blocking(
method,
... | `eth_getBlockByHash`
`eth_getBlockByNumber` |
16,546 | def get_summary(self):
func_summaries = [f.get_summary() for f in self.functions]
modif_summaries = [f.get_summary() for f in self.modifiers]
return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries) | Return the function summary
Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries) |
16,547 | async def reset_webhook(self, check=True) -> bool:
if check:
wh = await self.bot.get_webhook_info()
if not wh.url:
return False
return await self.bot.delete_webhook() | Reset webhook
:param check: check before deleting
:return: |
16,548 | def MobileDeviceProvisioningProfile(self, data=None, subset=None):
return self.factory.get_object(
jssobjects.MobileDeviceProvisioningProfile, data, subset) | {dynamic_docstring} |
16,549 | def convert_uuid(self, in_uuid: str = str, mode: bool = 0):
if not isinstance(in_uuid, str):
raise TypeError(" expected a str value.")
else:
pass
if not checker.check_is_uuid(in_uuid):
raise ValueError("{} is not a correct UUID".format(in_uui... | Convert a metadata UUID to its URI equivalent. And conversely.
:param str in_uuid: UUID or URI to convert
:param int mode: conversion direction. Options:
* 0 to HEX
* 1 to URN (RFC4122)
* 2 to URN (Isogeo specific style) |
16,550 | def url_defaults(self, fn):
self._defer(lambda bp: bp.url_defaults(fn))
return fn | Callback function for URL defaults for this bundle. It's called
with the endpoint and values and should update the values passed
in place. |
16,551 | def readB1header(filename):
return hed | Read beamline B1 (HASYLAB, Hamburg) header data
Input
-----
filename: string
the file name. If ends with ``.gz``, it is fed through a ``gunzip``
filter
Output
------
A header dictionary.
Examples
--------
read header data from 'ORG000123.DAT'::
header=read... |
16,552 | def extract_entry(self, e, decompress=):
self.fileobj.seek(e.offset)
stream = file_iter(self.fileobj)
stream = takeexactly(stream, e.size)
if decompress == :
stream = auto_decompress_stream(stream)
elif decompress == :
stream = bz2_decompress_stre... | Yield blocks of data for this entry from this MAR file.
Args:
e (:obj:`mardor.format.index_entry`): An index_entry object that
refers to this file's size and offset inside the MAR file.
path (str): Where on disk to extract this file to.
decompress (str, optio... |
16,553 | def category(self, category_id, country=None, locale=None):
route = Route(, , category_id=category_id)
payload = {}
if country:
payload[] = country
if locale:
payload[] = locale
return self.request(route, params=payload) | Get a single category used to tag items in Spotify.
Parameters
----------
category_id : str
The Spotify category ID for the category.
country : COUNTRY_TP
COUNTRY
locale : LOCALE_TP
LOCALE |
16,554 | def read_config(self):
self.ssl = self.get_option("ssl")
self.tank_type = self.get_option("tank_type")
self.gatling = .join(self.get_option().split("\n"))
self.method_prefix = self.get_option("method_prefix")
self.method_options = self... | reads config |
16,555 | def arrow_get(string):
if in string:
string = string.replace(, )
if in string:
return arrow.get(string)
string = string.rstrip()
return arrow.get(string, DATE_FORMATS[len(string)]) | this function exists because ICS uses ISO 8601 without dashes or
colons, i.e. not ISO 8601 at all. |
16,556 | def _process_diseasegene(self, limit):
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
line_counter = 0
model = Model(graph)
myfile = .join((self.rawdir, self.files[][]))
for event, elem in ET.iterparse(myfile):
... | :param limit:
:return: |
16,557 | def filter(self, data, collection, **kwargs):
if not data or self.filters is None:
return None, collection
filters = {}
for f in self.filters:
if f.name not in data:
continue
ops, collection = f.filter(collection, data, **kwargs)
... | Filter given collection. |
16,558 | def is_valid_python(tkn: str) -> bool:
try:
root = ast.parse(tkn)
except SyntaxError:
return False
return len(root.body) == 1 and isinstance(root.body[0], ast.Expr) and isinstance(root.body[0].value, ast.Name) | Determine whether tkn is a valid python identifier
:param tkn:
:return: |
16,559 | def _convert_connected_app(self):
if self.services and "connected_app" in self.services:
return
connected_app = self.get_connected_app()
if not connected_app:
return
self.logger.warning(
"Reading Connected App info fr... | Convert Connected App to service |
16,560 | def _handle_upsert(self, parts, unwritten_lobs=()):
self.description = None
self._received_last_resultset_part = True
for part in parts:
if part.kind == part_kinds.ROWSAFFECTED:
self.rowcount = part.values[0]
elif part.kind in (part_kinds.TRANS... | Handle reply messages from INSERT or UPDATE statements |
16,561 | def get_form(self, **kwargs):
if not hasattr(self, "form_class"):
raise AttributeError(_("You must define a form_class"))
return self.form_class(**kwargs) | Returns the form for registering or inviting a user |
16,562 | def _selection_by_callable(self, view, num_slices, non_empty_slices):
selected = [sl for sl in non_empty_slices
if self._sampler(self._get_axis(self._image, view, sl))]
return selected[:num_slices] | Returns all the slices selected by the given callable. |
16,563 | def transform(self, X):
iclustup = []
dims = self.n_components
if hasattr(self, ):
if X.shape[1] == self.v.shape[0]:
X = X @ self.v
nclust = self.n_X
AtS = self.A.T @ self.S
vnorm = np.sum(sel... | if already fit, can add new points and see where they fall |
16,564 | def resize(self, dims):
width, height = dims[:2]
self.dims = (width, height)
self.logger.debug("renderer reconfigured to %dx%d" % (
width, height))
depth = len(self.rgb_order)
self.surface = np.zeros((height, width, depth), dtype=np.uint8) | Resize our drawing area to encompass a space defined by the
given dimensions. |
16,565 | def database_caller_creator(self, host, port, name=None):
name = name or 0
client = redis.StrictRedis(host=host, port=port, db=name)
pipe = client.pipeline(transaction=False)
return client, pipe | creates a redis connection object
which will be later used to modify the db |
16,566 | def get_mac_address_table(self):
RE_MACTABLE_DEFAULT = r"^" + MAC_REGEX
RE_MACTABLE_6500_1 = r"^\*\s+{}\s+{}\s+".format(
VLAN_REGEX, MAC_REGEX
)
RE_MACTABLE_6500_2 = r"^{}\s+{}\s+".format(VLAN_REGEX, MAC_REGEX)
RE_MACTABLE_6500_3 = r"^\s{51}\S+"
... | Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address
Table, having the following keys
* mac (string)
* interface (string)
* vlan (int)
* active (boolean)
* static (boolean)
* moves (int)
* last... |
16,567 | def image_member(self):
uri = "/%s/member" % self.uri_base
resp, resp_body = self.api.method_get(uri)
return resp_body | Returns a json-schema document that represents an image member entity.
(a container of member entities). |
16,568 | def _get_route_args(self, namespace, route, tag=False):
data_type, _ = unwrap_nullable(route.arg_data_type)
if is_struct_type(data_type):
arg_list = []
for field in data_type.all_fields:
arg_list.append((fmt_var(field.name), fmt_type(
... | Returns a list of name / value string pairs representing the arguments for
a particular route. |
16,569 | def _parse_action(action):
i_open = action.find()
if i_open is -1:
return {: action, : [], : False}
i_close = action.rfind()
if i_close is -1:
raise Exception()
action_name = action[:i_open]
arglist = action[i_open+1:i_close].strip()
if not arglist:
... | Parses a single action item, for instance one of the following:
m; m(); m(True); m(*)
The brackets must match. |
16,570 | def findattr(self, name, resolved=True):
name = % name
parent = self.top().resolved
if parent is None:
result, ancestry = self.query(name, node)
else:
result, ancestry = self.getchild(name, parent)
if result is None:
return result
... | Find an attribute type definition.
@param name: An attribute name.
@type name: basestring
@param resolved: A flag indicating that the fully resolved type should
be returned.
@type resolved: boolean
@return: The found schema I{type}
@rtype: L{xsd.sxbase.SchemaO... |
16,571 | def _preprocess_Y(self, Y, k):
Y = Y.clone()
if Y.dim() == 1 or Y.shape[1] == 1:
Y = pred_to_prob(Y.long(), k=k)
return Y | Convert Y to prob labels if necessary |
16,572 | def get_totals_by_payee(self, account, start_date=None, end_date=None):
qs = Transaction.objects.filter(account=account, parent__isnull=True)
qs = qs.values().annotate(models.Sum())
qs = qs.order_by()
return qs | Returns transaction totals grouped by Payee. |
16,573 | def get_response_object(self, service_id, version_number, name):
content = self._fetch("/service/%s/version/%d/response_object/%s" % (service_id, version_number, name))
return FastlyResponseObject(self, content) | Gets the specified Response Object. |
16,574 | def tv_to_rdf(infile_name, outfile_name):
parser = Parser(Builder(), StandardLogger())
parser.build()
with open(infile_name) as infile:
data = infile.read()
document, error = parser.parse(data)
if not error:
with open(outfile_name, mode=) as outfile:
... | Convert a SPDX file from tag/value format to RDF format.
Return True on sucess, False otherwise. |
16,575 | def from_mongo(cls, doc):
if doc is None:
return None
if isinstance(doc, Document):
return doc
if cls.__type_store__ and cls.__type_store__ in doc:
cls = load(doc[cls.__type_store__], )
instance = cls(_prepare_defaults=False)
instance.__data__ = doc
instance._prepare_def... | Convert data coming in from the MongoDB wire driver into a Document instance. |
16,576 | def reload_configuration(self, event):
if event.target == self.uniquename:
self.log()
self._read_config() | Event triggered configuration reload |
16,577 | def setValue(self, newText):
newText = str(newText)
if self.text == newText:
return
self.text = newText
textLines = self.text.splitlines()
nLines = len(textLines)
surfacesList = []
actualWidth = 0
for line in textL... | Sets a text value (string) into the text field. |
16,578 | def select(self, key=None, val=None, touch=None, log=, out=int):
assert out in [int,bool]
assert log in [,,]
C = [key is None,touch is None]
assert np.sum(C)>=1
if np.sum(C)==2:
ind = np.ones((self.nRays,),dtype=bool)
else:
if key is not N... | Return the indices of the rays matching selection criteria
The criterion can be of two types:
- a key found in self.dchans, with a matching value
- a touch tuple (indicating which element in self.config is touched
by the desired rays)
Parameters
--------... |
16,579 | def read_detections(fname):
f = open(fname, )
detections = []
for index, line in enumerate(f):
if index == 0:
continue
if line.rstrip().split()[0] == :
continue
detection = line.rstrip().split()
detection[1] = UTCDateTime(detection[1])
... | Read detections from a file to a list of Detection objects.
:type fname: str
:param fname: File to read from, must be a file written to by \
Detection.write.
:returns: list of :class:`eqcorrscan.core.match_filter.Detection`
:rtype: list
.. note::
:class:`eqcorrscan.core.match_filt... |
16,580 | def set_role(username, role):
*
try:
sendline()
role_line = .format(username, role)
ret = sendline(role_line)
sendline()
sendline()
return .join([role_line, ret])
except TerminalException as e:
log.error(e)
return | Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin |
16,581 | def _sanity_check_block_pairwise_constraints(ir_blocks):
for first_block, second_block in pairwise(ir_blocks):
if isinstance(first_block, MarkLocation) and isinstance(second_block, Filter):
raise AssertionError(u.format(ir_blocks))
| Assert that adjacent blocks obey all invariants. |
16,582 | def _select_next_server(self):
while True:
if len(self._server_pool) == 0:
self._current_server = None
raise ErrNoServers
now = time.monotonic()
s = self._server_pool.pop(0)
if self.options["max_reconnect_attempts"] > 0:
... | Looks up in the server pool for an available server
and attempts to connect. |
16,583 | def getLVstats(self, *args):
if not len(args) in (1, 2):
raise TypeError("The getLVstats must be called with either "
"one or two arguments.")
if self._vgTree is None:
self._initDMinfo()
if len(args) == 1:
dmdev = self._map... | Returns I/O stats for LV.
@param args: Two calling conventions are implemented:
- Passing two parameters vg and lv.
- Passing only one parameter in 'vg-lv' format.
@return: Dict of stats. |
16,584 | def add_to_env(self, content):
if not self.rewrite_config:
raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.")
if not self.env_file:
self.env_path, self.env_file = self.__get_env_handle(self.root_dir)
self.env_file.write(content + ) | add content to the env script. |
16,585 | def CreateTask(self, session_identifier):
task = tasks.Task(session_identifier)
logger.debug(.format(task.identifier))
with self._lock:
self._tasks_queued[task.identifier] = task
self._total_number_of_tasks += 1
self.SampleTaskStatus(task, )
return task | Creates a task.
Args:
session_identifier (str): the identifier of the session the task is
part of.
Returns:
Task: task attribute container. |
16,586 | def coge(args):
p = OptionParser(coge.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
cogefile, = args
fp = must_open(cogefile)
cogefile = cogefile.replace(".gz", "")
ksfile = cogefile + ".ks"
anchorsfile = cogefile + ".anchors"
... | %prog coge cogefile
Convert CoGe file to anchors file. |
16,587 | def on_step_end(self, **kwargs):
"Put the LR back to its value if necessary."
if not self.learn.gan_trainer.gen_mode: self.learn.opt.lr /= self.mult_lr | Put the LR back to its value if necessary. |
16,588 | def compute_xy(
self, projection: Union[pyproj.Proj, crs.Projection, None] = None
):
if isinstance(projection, crs.Projection):
projection = pyproj.Proj(projection.proj4_init)
if projection is None:
projection = pyproj.Proj(
proj="lcc",
... | Computes x and y columns from latitudes and longitudes.
The source projection is WGS84 (EPSG 4326).
The default destination projection is a Lambert Conformal Conical
projection centered on the data inside the dataframe.
For consistency reasons with pandas DataFrame, a new Traffic struc... |
16,589 | def generate_documentation(schema):
documentation_title = "Configuration documentation"
documentation = documentation_title + "\n"
documentation += "=" * len(documentation_title) +
for section_name in schema:
section_created = False
for option_name in schema[section_name]:
... | Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation. |
16,590 | def add_ospf_area(self, ospf_area, ospf_interface_setting=None, network=None,
communication_mode=, unicast_ref=None):
communication_mode = communication_mode.upper()
destinations=[] if not ospf_interface_setting else [ospf_interface_setting]
if communication_mode =... | Add OSPF Area to this routing node.
Communication mode specifies how the interface will interact with the
adjacent OSPF environment. Please see SMC API documentation for more
in depth information on each option.
If the interface has multiple networks nested below, all networks
... |
16,591 | def create_mosaic(tiles, nodata=0):
if isinstance(tiles, GeneratorType):
tiles = list(tiles)
elif not isinstance(tiles, list):
raise TypeError("tiles must be either a list or generator")
if not all([isinstance(pair, tuple) for pair in tiles]):
raise TypeError("tiles items must b... | Create a mosaic from tiles. Tiles must be connected (also possible over Antimeridian),
otherwise strange things can happen!
Parameters
----------
tiles : iterable
an iterable containing tuples of a BufferedTile and an array
nodata : integer or float
raster nodata value to initialize... |
16,592 | def get_loc_level(self, key, level=0, drop_level=True):
def maybe_droplevels(indexer, levels, drop_level):
if not drop_level:
return self[indexer]
orig_index = new_index = self[indexer]
levels = [self._get_level_number(i) for i in levels... | Get both the location for the requested label(s) and the
resulting sliced index.
Parameters
----------
key : label or sequence of labels
level : int/level name or list thereof, optional
drop_level : bool, default True
if ``False``, the resulting index will no... |
16,593 | def to_dict(self, omit=()):
result = dict(self)
for key in omit:
if key in result:
del result[key]
return result | Return a (shallow) copy of self cast to a dictionary,
optionally omitting some key/value pairs. |
16,594 | def pickle_load(cls, filepath):
if os.path.isdir(filepath):
for dirpath, dirnames, filenames in os.walk(filepath):
fnames = [f for f in filenames if f == cls.PICKLE_FNAME]
if fnames:
if len(fnames) == 1:
... | Loads the object from a pickle file.
Args:
filepath: Filename or directory name. It filepath is a directory, we
scan the directory tree starting from filepath and we
read the first pickle database. Raise RuntimeError if multiple
databases are found. |
16,595 | def get_stream(self, session_id, stream_id):
endpoint = self.endpoints.get_stream_url(session_id, stream_id)
response = requests.get(
endpoint, headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout
)
if response.status_code == 200:
retu... | Returns an Stream object that contains information of an OpenTok stream:
-id: The stream ID
-videoType: "camera" or "screen"
-name: The stream name (if one was set when the client published the stream)
-layoutClassList: It's an array of the layout classes for the stream |
16,596 | def get_service_inspect(self, stack, service):
url = .format(self.host, stack, service)
return self.__get(url) | 查看服务
查看指定名称服务的属性。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回服务信息,失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息 |
16,597 | def should_we_load(kls):
if kls.__name__.endswith("AbstractCheck"):
return False
if not kls.__name__.endswith("Check"):
return False
mro = kls.__mro__
for m in mro:
if m.__name__ == "AbstractCheck":
return True
return False | should we load this class as a check? |
16,598 | def _set_show_zoning_enabled_configuration(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=show_zoning_enabled_configuration.show_zoning_enabled_configuration, is_leaf=True, yang_name="show-zoning-enabled-configuration", rest_name="show-zoning-enabled... | Setter method for show_zoning_enabled_configuration, mapped from YANG variable /brocade_zone_rpc/show_zoning_enabled_configuration (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_zoning_enabled_configuration is considered as a private
method. Backends looking to p... |
16,599 | def score(self, X, y=None, sample_weight=None):
Xt, yt, swt = self._transform(X, y, sample_weight)
self.N_test = len(yt)
score_params = {}
if swt is not None:
score_params[] = swt
if self.scorer is None:
return self._final_estimator.score(Xt, ... | Apply transforms, and score with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : iterable, default=None
Targets used for scoring. Must fulfill label requirem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.