Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
374,300 | def create_api_integration(restApiId, resourcePath, httpMethod, integrationType, integrationHttpMethod,
uri, credentials, requestParameters=None, requestTemplates=None,
region=None, key=None, keyid=None, profile=None):
{}{}
try:
credentials = _get_ro... | Creates an integration for a given method in a given API.
If integrationType is MOCK, uri and credential parameters will be ignored.
uri is in the form of (substitute APIGATEWAY_REGION and LAMBDA_FUNC_ARN)
"arn:aws:apigateway:APIGATEWAY_REGION:lambda:path/2015-03-31/functions/LAMBDA_FUNC_ARN/invocations"
... |
374,301 | def find_all_checks(self, **kwargs):
checks = self._check_manager.find_all_checks(**kwargs)
for check in checks:
check.set_entity(self)
return checks | Finds all checks for this entity with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side. |
374,302 | def setFlag(self, flag, state=True):
has_flag = self.testFlag(flag)
if has_flag and not state:
self.setFlags(self.flags() ^ flag)
elif not has_flag and state:
self.setFlags(self.flags() | flag) | Sets whether or not the given flag is enabled or disabled.
:param flag | <XExporter.Flags> |
374,303 | def _get_face2(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2):
if shape is None:
shape = [32, 32]
center = (np.asarray(shape) - 1) / 2.0
r = np.min(center) * face_r
x, y = np.meshgrid(range(shape[1]), range(shape[0]))
head = (x - center[0]) ** 2 +... | Create 2D binar face
:param shape:
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return: |
374,304 | def init(self, projectname=None, description=None, **kwargs):
self.app_main(**kwargs)
experiments = self.config.experiments
experiment = self._experiment
if experiment is None and not experiments:
experiment = self.name +
elif experiment is None:
... | Initialize a new experiment
Parameters
----------
projectname: str
The name of the project that shall be used. If None, the last one
created will be used
description: str
A short summary of the experiment
``**kwargs``
Keyword argum... |
374,305 | def problem_id(self, value):
if value == self._defaults[] and in self._values:
del self._values[]
else:
self._values[] = value | The problem_id property.
Args:
value (string). the property value. |
374,306 | def separation(sources, fs=22050, labels=None, alpha=0.75, ax=None, **kwargs):
ax, new_axes = __get_axes(ax=ax)
sources = np.atleast_2d(sources)
if labels is None:
labels = [.format(_) for _ in range(len(sources))]
kwargs.setdefault(, )
cumspec = None
s... | Source-separation visualization
Parameters
----------
sources : np.ndarray, shape=(nsrc, nsampl)
A list of waveform buffers corresponding to each source
fs : number > 0
The sampling rate
labels : list of strings
An optional list of descriptors corresponding to each source
... |
374,307 | def install_package_to_venv(self):
try:
self.env.install(self.name, force=True, options=["--no-deps"])
except (ve.PackageInstallationException,
ve.VirtualenvReadonlyException):
raise VirtualenvFailException(
)
self.dirs_after_insta... | Installs package given as first argument to virtualenv without
dependencies |
374,308 | def product(pc, service, attrib, sku):
pc.service = service.lower()
pc.sku = sku
pc.add_attributes(attribs=attrib)
click.echo("Service Alias: {0}".format(pc.service_alias))
click.echo("URL: {0}".format(pc.service_url))
click.echo("Region: {0}".format(pc.region))
click.echo("Product Term... | Get a list of a service's products.
The list will be in the given region, matching the specific terms and
any given attribute filters or a SKU. |
374,309 | def generate_blob(self, container_name, blob_name, permission=None,
expiry=None, start=None, id=None, ip=None, protocol=None,
cache_control=None, content_disposition=None,
content_encoding=None, content_language=None,
conte... | Generates a shared access signature for the blob.
Use the returned signature with the sas_token parameter of any BlobService.
:param str container_name:
Name of container.
:param str blob_name:
Name of blob.
:param BlobPermissions permission:
The perm... |
374,310 | def _get_svc_list(service_status):
prefix =
ret = set()
lines = glob.glob(.format(prefix))
for line in lines:
svc = _get_svc(line, service_status)
if svc is not None:
ret.add(svc)
return sorted(ret) | Returns all service statuses |
374,311 | def modify_fk_constraint(apps, schema_editor):
model = apps.get_model("message_sender", "OutboundSendFailure")
table = model._meta.db_table
with schema_editor.connection.cursor() as cursor:
constraints = schema_editor.connection.introspection.get_constraints(
cursor, table
... | Delete's the current foreign key contraint on the outbound field, and adds
it again, but this time with an ON DELETE clause |
374,312 | def inner(a,b):
if sps.issparse(a): return a.dot(b)
else: a = np.asarray(a)
if len(a.shape) == 0: return a*b
if sps.issparse(b):
if len(a.shape) == 1: return b.T.dot(a)
else: return b.T.dot(a.T).T
else: b = np.asarray(b)
if len(b.shape) == 0: return a*b
... | inner(a,b) yields the dot product of a and b, doing so in a fashion that respects sparse
matrices when encountered. This does not error check for bad dimensionality.
If a or b are constants, then the result is just the a*b; if a and b are both vectors or both
matrices, then the inner product is dot(a,b);... |
374,313 | def train_model(params: Params,
serialization_dir: str,
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
cache_directory: str = None,
cache_prefix: str = None) -> Model:
prepare_envir... | Trains the model specified in the given :class:`Params` object, using the data and training
parameters also specified in that object, and saves the results in ``serialization_dir``.
Parameters
----------
params : ``Params``
A parameter object specifying an AllenNLP Experiment.
serialization... |
374,314 | def set_euk_hmm(self, args):
if hasattr(args, ):
pass
elif not hasattr(args, ):
setattr(args, , os.path.join(os.path.dirname(inspect.stack()[-1][1]),,, ))
else:
raise Exception() | Set the hmm used by graftM to cross check for euks. |
374,315 | def send(self, request, headers=None, content=None, **kwargs):
if headers:
request.headers.update(headers)
if not request.files and request.data is None and content is not None:
request.add_content(content)
response = None
kwargs.setdef... | Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the request.
:param config: Any specific config overrides |
374,316 | def cursor_position_changed(self):
if self.bracepos is not None:
self.__highlight(self.bracepos, cancel=True)
self.bracepos = None
cursor = self.textCursor()
if cursor.position() == 0:
return
cursor.movePosition(QTextCursor.PreviousCha... | Brace matching |
374,317 | def convertMzml(mzmlPath, outputDirectory=None):
outputDirectory = outputDirectory if outputDirectory is not None else os.path.dirname(mzmlPath)
msrunContainer = importMzml(mzmlPath)
msrunContainer.setPath(outputDirectory)
msrunContainer.save() | Imports an mzml file and converts it to a MsrunContainer file
:param mzmlPath: path of the mzml file
:param outputDirectory: directory where the MsrunContainer file should be written
if it is not specified, the output directory is set to the mzml files directory. |
374,318 | def page(self, recurring=values.unset, trigger_by=values.unset,
usage_category=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
params = values.of({
: recurring,
: trigger_by,
: usage_category,
... | Retrieve a single page of TriggerInstance records from the API.
Request is executed immediately
:param TriggerInstance.Recurring recurring: The frequency of recurring UsageTriggers to read
:param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read
:pa... |
374,319 | def sort(self, *sorting, **kwargs):
sorting_ = []
for name, desc in sorting:
field = self.meta.model._meta.fields.get(name)
if field is None:
continue
if desc:
field = field.desc()
sorting_.append(field)
if ... | Sort resources. |
374,320 | def get_destination(self, filepath, targetdir=None):
dst = self.change_extension(filepath, )
if targetdir:
dst = os.path.join(targetdir, dst)
return dst | Return destination path from given source file path.
Destination is allways a file with extension ``.css``.
Args:
filepath (str): A file path. The path is allways relative to
sources directory. If not relative, ``targetdir`` won't be
joined.
abso... |
374,321 | def copy_function(func, name=None):
code = func.__code__
newname = name or func.__name__
newcode = CodeType(
code.co_argcount,
code.co_kwonlyargcount,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
code.co_consts,
code.co... | Copy a function object with different name.
Args:
func (function): Function to be copied.
name (string, optional): Name of the new function.
If not spacified, the same name of `func` will be used.
Returns:
newfunc (function): New function with different name. |
374,322 | def _set_system_mode(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 0}, u: {: 1}},), is... | Setter method for system_mode, mapped from YANG variable /hardware/system_mode (system-mode-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_mode is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._s... |
374,323 | def _wpad(l, windowsize, stepsize):
if l <= windowsize:
return windowsize
nsteps = ((l // stepsize) * stepsize)
overlap = (windowsize - stepsize)
if overlap:
return nsteps + overlap
diff = (l - nsteps)
left = max(0, windowsize - diff)
return l + left if diff else l | Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that no samples are leftover |
374,324 | def read(self, gpio):
res = yield from self._pigpio_aio_command(_PI_CMD_READ, gpio, 0)
return _u2i(res) | Returns the GPIO level.
gpio:= 0-53.
...
yield from pi.set_mode(23, pigpio.INPUT)
yield from pi.set_pull_up_down(23, pigpio.PUD_DOWN)
print(yield from pi.read(23))
0
yield from pi.set_pull_up_down(23, pigpio.PUD_UP)
print(yield from pi.read(23))
1
... |
374,325 | def update_asset_browser(self, project, releasetype):
if project is None:
self.assetbrws.set_model(None)
return
assetmodel = self.create_asset_model(project, releasetype)
self.assetbrws.set_model(assetmodel) | update the assetbrowser to the given project
:param releasetype: the releasetype for the model
:type releasetype: :data:`djadapter.RELEASETYPES`
:param project: the project of the assets
:type project: :class:`djadapter.models.Project`
:returns: None
:rtype: None
... |
374,326 | def construct_graph(sakefile, settings):
verbose = settings["verbose"]
sprint = settings["sprint"]
G = nx.DiGraph()
sprint("Going to construct Graph", level="verbose")
for target in sakefile:
if target == "all":
matches = check_for_dep_in_outputs(dep, verbose, G... | Takes the sakefile dictionary and builds a NetworkX graph
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The settings dictionary
Returns:
A NetworkX graph |
374,327 | def report(ctx, board, done, output):
ctx.obj[] = board
ts = TrelloStats(ctx.obj)
ct = cycle_time(ts, board, done)
env = get_env()
if target.startswith("render_") and
target.endswith(output)]
for render_func in render_functions:
print... | Reporting mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done |
374,328 | def VerifyRow(self, parser_mediator, row):
if row[] != and not self._MD5_RE.match(row[]):
return False
for column_name in (
, , , , , , ):
column_value = row.get(column_name, None)
if not column_value:
continue
try:
int(column_value, 1... | Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between
parsers and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified in COLUMNS.
Returns:
bool: True if thi... |
374,329 | def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None,
numeric=True, convention=1):
ur
magnetic_states = make_list_of_states(fine_states, , verbose=0)
aux = calculate_boundaries(fine_states, magnetic_states)
index_list_fine, index_list_hyperfine = aux
Ne = l... | ur"""Calculate the matrix elements of the electric dipole (in the helicity
basis).
We calculate all matrix elements for the D2 line in Rb 87.
>>> from sympy import symbols, pprint
>>> red = symbols("r", positive=True)
>>> reduced_matrix_elements = [[0, -red], [red, 0]]
>>> g = State("Rb", 87, ... |
374,330 | def download_file(save_path, file_url):
r = requests.get(file_url)
with open(save_path, ) as f:
f.write(r.content)
return save_path | Download file from http url link |
374,331 | def _on(on_signals, callback, max_calls=None):
if not callable(callback):
raise AssertionError()
if not isinstance(on_signals, (list, tuple)):
on_signals = [on_signals]
callback._max_calls = max_calls
for signal in on_signals:
receivers[signal].add(callback)
... | Proxy for `smokesignal.on`, which is compatible as both a function call and
a decorator. This method cannot be used as a decorator
:param signals: A single signal or list/tuple of signals that callback should respond to
:param callback: A callable that should repond to supplied signal(s)
:param max_cal... |
374,332 | def _get_model_fitting(self, mf_id):
for model_fitting in self.model_fittings:
if model_fitting.activity.id == mf_id:
return model_fitting
raise Exception("Model fitting activity with id: " + str(mf_id) +
" not found.") | Retreive model fitting with identifier 'mf_id' from the list of model
fitting objects stored in self.model_fitting |
374,333 | def upload_files(self, abspaths, relpaths, remote_objects):
for relpath in relpaths:
abspath = [p for p in abspaths if p[len(self.file_root):] == relpath][0]
cloud_datetime = remote_objects[relpath] if relpath in remote_objects else None
local_datetime = datetime.dat... | Determines files to be uploaded and call ``upload_file`` on each. |
374,334 | def is_BF_hypergraph(self):
for hyperedge_id in self._hyperedge_attributes:
tail = self.get_hyperedge_tail(hyperedge_id)
head = self.get_hyperedge_head(hyperedge_id)
if len(tail) > 1 and len(head) > 1:
return False
return True | Indicates whether the hypergraph is a BF-hypergraph.
A BF-hypergraph consists of only B-hyperedges and F-hyperedges.
See "is_B_hypergraph" or "is_F_hypergraph" for more details.
:returns: bool -- True iff the hypergraph is an F-hypergraph. |
374,335 | def as_sql(self, *args, **kwargs):
CTEQuery._remove_cte_where(self.query)
return super(self.__class__, self).as_sql(*args, **kwargs) | Overrides the :class:`SQLUpdateCompiler` method in order to remove any
CTE-related WHERE clauses, which are not necessary for UPDATE queries,
yet may have been added if this query was cloned from a CTEQuery.
:return:
:rtype: |
374,336 | def diffusion_correlated(diffusion_constant=0.2, exposure_time=0.05,
samples=40, phi=0.25):
radius = 5
psfsize = np.array([2.0, 1.0, 3.0])/2
pos, rad, tile = nbody.initialize_particles(N=50, phi=phi, polydispersity=0.0)
sim = nbody.BrownianHardSphereSimulation(
pos, rad, tile, D=di... | Calculate the (perhaps) correlated diffusion effect between particles
during the exposure time of the confocal microscope. diffusion_constant is
in terms of seconds and pixel sizes exposure_time is in seconds
1 micron radius particle:
D = kT / (6 a\pi\eta)
for 80/20 g/w (60 mPas), 3600 nm^2... |
374,337 | def tmpdir():
target = None
try:
with _tmpdir_extant() as target:
yield target
finally:
if target is not None:
shutil.rmtree(target, ignore_errors=True) | Create a tempdir context for the cwd and remove it after. |
374,338 | def get_workflow_status_of(brain_or_object, state_var="review_state"):
workflow = get_tool("portal_workflow")
obj = get_object(brain_or_object)
return workflow.getInfoFor(ob=obj, name=state_var) | Get the current workflow status of the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param state_var: The name of the state variable
:type state_var: string
:returns: Status
:rtype... |
374,339 | def gaussian(data, mean, covariance):
dimension = float(len(data[0]))
if dimension != 1.0:
inv_variance = numpy.linalg.pinv(covariance)
else:
inv_variance = 1.0 / covariance
divider = (pi * 2.0) ** (dimension / 2.0) * numpy.sqrt(numpy.linalg.norm(covariance))
if... | !
@brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case
multi-dimensional data.
@param[in] data (list): Data that is used for gaussian calculation.
@param[in] mean (float|numpy.array): Mathematical expectation used for... |
374,340 | def remove_field(self, name):
field = self.get_field(name)
if field:
predicat = lambda field: field.get() != name
self.__current_descriptor[] = filter(
predicat, self.__current_descriptor[])
self.__build()
return field | https://github.com/frictionlessdata/tableschema-py#schema |
374,341 | def _parse_xmatch_catalog_header(xc, xk):
catdef = []
if xc.endswith():
infd = gzip.open(xc,)
else:
infd = open(xc,)
for line in infd:
if line.decode().startswith():
catdef.append(
line.decode().replace(,).strip().rstrip()
... | This parses the header for a catalog file and returns it as a file object.
Parameters
----------
xc : str
The file name of an xmatch catalog prepared previously.
xk : list of str
This is a list of column names to extract from the xmatch catalog.
Returns
-------
tuple
... |
374,342 | async def retract(self, mount: top_types.Mount, margin: float):
smoothie_ax = Axis.by_mount(mount).name.upper()
async with self._motion_lock:
smoothie_pos = self._backend.fast_home(smoothie_ax, margin)
self._current_position = self._deck_from_smoothie(smoothie_pos) | Pull the specified mount up to its home position.
Works regardless of critical point or home status. |
374,343 | def record_iterator(xml):
if hasattr(xml, "read"):
xml = xml.read()
dom = None
try:
dom = dhtmlparser.parseString(xml)
except UnicodeError:
dom = dhtmlparser.parseString(xml.encode("utf-8"))
for record_xml in dom.findB("record"):
yield MARCXMLRecord(record... | Iterate over all ``<record>`` tags in `xml`.
Args:
xml (str/file): Input string with XML. UTF-8 is prefered encoding,
unicode should be ok.
Yields:
MARCXMLRecord: For each corresponding ``<record>``. |
374,344 | def set(self, key, val, time=0, min_compress_len=0):
s objects
on the same memcache server, so you could use the usert ever try to compress.
'
return self._set("set", key, val, time, min_compress_len) | Unconditionally sets a key to a given value in the memcache.
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all o... |
374,345 | def pick_frequency_line(self, filename, frequency, cumulativefield=):
if resource_exists(, filename):
with closing(resource_stream(, filename)) as b:
g = codecs.iterdecode(b, )
return self._pick_frequency_line(g, frequency, cumulativefield)
else:
... | Given a numeric frequency, pick a line from a csv with a cumulative frequency field |
374,346 | def add_deviation(self, dev, td=None):
self.deviation = dev
try:
self.compute_position_log(td=td)
except:
self.position = None
return | Add a deviation survey to this instance, and try to compute a position
log from it. |
374,347 | def publish(self, value):
value = super(Float, self).publish(value)
if isinstance(value, int):
value = float(value)
return value | Accepts: float
Returns: float |
374,348 | def _set_ipv6_track(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=ipv6_track.ipv6_track, is_container=, presence=False, yang_name="ipv6-track", rest_name="track", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path... | Setter method for ipv6_track, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_local_anycast_gateway/ipv6_track (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_track is considered as a private
method. Backends looking to populate this variable sh... |
374,349 | def ctc_symbol_loss(top_out, targets, model_hparams, vocab_size, weight_fn):
del model_hparams, vocab_size
logits = top_out
with tf.name_scope("ctc_loss", values=[logits, targets]):
targets_shape = targets.get_shape().as_list()
assert len(targets_shape) == 4
assert targets_shape[2] == 1
... | Compute the CTC loss. |
374,350 | def addVariantFeature(self,variantFeature):
if isinstance(variantFeature, Feature):
self.features.append(variantFeature)
else:
raise(TypeError,
% type(
variantFeature)
) | Appends one VariantFeature to variantFeatures |
374,351 | def child_object(self):
from . import types
child_klass = types.get(self.task_type.split()[1])
return child_klass.retrieve(self.task_id, client=self._client) | Get Task child object class |
374,352 | def Si_to_pandas_dict(S_dict):
problem = S_dict.problem
total_order = {
: S_dict[],
: S_dict[]
}
first_order = {
: S_dict[],
: S_dict[]
}
idx = None
second_order = None
if in S_dict:
names = problem[]
idx = list(combi... | Convert Si information into Pandas DataFrame compatible dict.
Parameters
----------
S_dict : ResultDict
Sobol sensitivity indices
See Also
----------
Si_list_to_dict
Returns
----------
tuple : of total, first, and second order sensitivities.
Total... |
374,353 | def configure_logger(glob, multi_level,
relative=False, logfile=None, syslog=False):
levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] \
if multi_level else [logging.INFO, logging.DEBUG]
try:
verbose = min(int(glob[].verbose), 3)
except Att... | Logger configuration function for setting either a simple debug mode or a
multi-level one.
:param glob: globals dictionary
:param multi_level: boolean telling if multi-level debug is to be considered
:param relative: use relative time for the logging messages
:param logfile: log ... |
374,354 | def reciprocal_rank(
model,
test_interactions,
train_interactions=None,
user_features=None,
item_features=None,
preserve_rows=False,
num_threads=1,
check_intersections=True,
):
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
ranks = m... | Measure the reciprocal rank metric for a model: 1 / the rank of the highest
ranked positive example. A perfect score is 1.0.
Parameters
----------
model: LightFM instance
the fitted model to be evaluated
test_interactions: np.float32 csr_matrix of shape [n_users, n_items]
Non-zer... |
374,355 | def xack(self, stream, group_name, id, *ids):
return self.execute(b, stream, group_name, id, *ids) | Acknowledge a message for a given consumer group |
374,356 | def filter(self, value, model=None, context=None):
value = str(value)
return bleach.clean(text=value, **self.bleach_params) | Filter
Performs value filtering and returns filtered result.
:param value: input value
:param model: parent model being validated
:param context: object, filtering context
:return: filtered value |
374,357 | def shorten_duplicate_content_url(url):
if in url:
url = url.split(, 1)[0]
if url.endswith():
return url[:-10]
if url.endswith():
return url[:-9]
return url | Remove anchor part and trailing index.html from URL. |
374,358 | def select_data(db_file, slab=None, facet=None):
con = sql.connect(db_file)
cur = con.cursor()
if slab and facet:
select_command = \
+str(facet)++slab+
elif slab and not facet:
select_command = \
+slab+
else:
select_command =
cur.... | Gathers relevant data from SQL database generated by CATHUB.
Parameters
----------
db_file : Path to database
slab : Which metal (slab) to select.
facet : Which facets to select.
Returns
-------
data : SQL cursor output. |
374,359 | def visit_dictcomp(self, node, parent):
newnode = nodes.DictComp(node.lineno, node.col_offset, parent)
newnode.postinit(
self.visit(node.key, newnode),
self.visit(node.value, newnode),
[self.visit(child, newnode) for child in node.generators],
)
... | visit a DictComp node by returning a fresh instance of it |
374,360 | def pot_to_requiv_contact(pot, q, sma, compno=1):
return ConstraintParameter(pot._bundle, "pot_to_requiv_contact({}, {}, {}, {})".format(_get_expr(pot), _get_expr(q), _get_expr(sma), compno)) | TODO: add documentation |
374,361 | def _get_es_version(self, config):
try:
data = self._get_data(config.url, config, send_sc=False)
self.log.debug("Elasticsearch version is %s" % version)
return version | Get the running version of elasticsearch. |
374,362 | def connect(self):
if (self.__ser is not None):
serial = importlib.import_module("serial")
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ONE
elif self.__stopbits == 1:
self.__ser.stopbits = serial.STOPBITS_TWO
... | Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters |
374,363 | def search(self):
self.q(css=).click()
GitHubSearchResultsPage(self.browser).wait_for_page() | Click on the Search button and wait for the
results page to be displayed |
374,364 | def exact_anniversaries(frequency, anniversary, start, finish):
if frequency != DATE_FREQUENCY_MONTHLY:
raise DateFrequencyError("Only monthly date frequency is supported - not " % (frequency))
if start.day != anniversary:
return False
periods = 0
current = start
while cur... | Returns the number of exact anniversaries if start and finish represent an anniversary.
ie..
exact_anniversaries(DATE_FREQUENCY_MONTHLY, 10, date(2012, 2, 10), date(2012, 3, 9)) returns 1
exact_anniversaries(DATE_FREQUENCY_MONTHLY, 10, date(2012, 2, 10), date(2012, 4, 9)) returns 2 |
374,365 | def list_scheduled_queries(self):
url = .format(
account_id=self.account_id)
return self._api_get(url=url).get() | List all scheduled_queries
:return: A list of all scheduled query dicts
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from Logentries |
374,366 | def write_records(records, output_file, split=False):
if split:
for record in records:
with open(
"{}{}.fa".format(output_file, record.id), "w"
) as record_handle:
SeqIO.write(record, record_handle, "fasta")
else:
SeqIO.write(records... | Write FASTA records
Write a FASTA file from an iterable of records.
Parameters
----------
records : iterable
Input records to write.
output_file : file, str or pathlib.Path
Output FASTA file to be written into.
split : bool, optional
If True, each record is written into... |
374,367 | def dendrogram(adata: AnnData, groupby: str,
n_pcs: Optional[int]=None,
use_rep: Optional[str]=None,
var_names: Optional[List[str]]=None,
use_raw: Optional[bool]=None,
cor_method: Optional[str]=,
linkage_method: Optional[str]=,
... | \
Computes a hierarchical clustering for the given `groupby` categories.
By default, the PCA representation is used unless `.X` has less than 50 variables.
Alternatively, a list of `var_names` (e.g. genes) can be given.
Average values of either `var_names` or components are used to compute a correlat... |
374,368 | def conditions_list(self, conkey):
L = []
keys = [k for k in self.conditions if k.startswith(conkey)]
if not keys:
raise KeyError(conkey)
for k in keys:
if self.conditions[k] is None:
continue
raw = self.conditions[k]
... | Return a (possibly empty) list of conditions based on
conkey. The conditions are returned raw, not parsed.
conkey: str
for cond<n>, startcond<n> or stopcond<n>, specify only the
prefix. The list will be filled with all conditions. |
374,369 | def less(x, y):
x = BigFloat._implicit_convert(x)
y = BigFloat._implicit_convert(y)
return mpfr.mpfr_less_p(x, y) | Return True if x < y and False otherwise.
This function returns False whenever x and/or y is a NaN. |
374,370 | def remove_regex(urls, regex):
if not regex:
return urls
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls | Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex |
374,371 | def result(self) -> workflow.IntervalGeneratorType:
config = cast(SentenceSegementationConfig, self.config)
index = -1
labels = None
while True:
start = -1
while True:
if labels is None:
... | Generate intervals indicating the valid sentences. |
374,372 | def _parse_file(self, file_obj):
byte_data = file_obj.read(self.size)
self._parse_byte_data(byte_data) | Directly read from file handler.
Note that this will move the file pointer. |
374,373 | def on_frame(self, frame_in):
if frame_in.name not in self._request:
return False
uuid = self._request[frame_in.name]
if self._response[uuid]:
self._response[uuid].append(frame_in)
else:
self._response[uuid] = [frame_in]
return True | On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return: |
374,374 | def isPairTag(self):
if self.isComment() or self.isNonPairTag():
return False
if self.isEndTag():
return True
if self.isOpeningTag() and self.endtag:
return True
return False | Returns:
bool: True if this is pair tag - ``<body> .. </body>`` for example. |
374,375 | def convert_to_equivalent(self, unit, equivalence, **kwargs):
conv_unit = Unit(unit, registry=self.units.registry)
if self.units.same_dimensions_as(conv_unit):
self.convert_to_units(conv_unit)
return
this_equiv = equivalence_registry[equivalence](in_place=True)
... | Return a copy of the unyt_array in the units specified units, assuming
the given equivalency. The dimensions of the specified units and the
dimensions of the original array need not match so long as there is an
appropriate conversion in the specified equivalency.
Parameters
----... |
374,376 | def build_graph(self, regularizers=()):
key = self._hash(regularizers)
if key not in self._graphs:
util.log()
for loss in self.losses:
loss.log()
for reg in regularizers:
reg.log()
outputs = {}
updates =... | Connect the layers in this network to form a computation graph.
Parameters
----------
regularizers : list of :class:`theanets.regularizers.Regularizer`
A list of the regularizers to apply while building the computation
graph.
Returns
-------
outp... |
374,377 | async def main(loop):
PYVLXLOG.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
PYVLXLOG.addHandler(stream_handler)
pyvlx = PyVLX(, loop=loop)
await pyvlx.load_scenes()
await pyvlx.load_nodes()
await asynci... | Log packets from Bus. |
374,378 | def best_four_point_to_sell(self):
result = []
if self.check_plus_bias_ratio() and \
(self.best_sell_1() or self.best_sell_2() or self.best_sell_3() or \
self.best_sell_4()):
if self.best_sell_1():
result.append(self.best_sell_1.__doc__.strip... | ε€ζ·ζ―ε¦ηΊεε€§θ³£ι»
:rtype: str or False |
374,379 | def _set_scores(self):
anom_scores = {}
self._generate_SAX()
self._construct_all_SAX_chunk_dict()
length = self.time_series_length
lws = self.lag_window_size
fws = self.future_window_size
for i, timestamp in enumerate(self.time_series.timestamps):
... | Compute anomaly scores for the time series by sliding both lagging window and future window. |
374,380 | def _evictStaleDevices(self):
while self.running:
expiredDeviceIds = [key for key, value in self.devices.items() if value.hasExpired()]
for key in expiredDeviceIds:
logger.warning("Device timeout, removing " + key)
del self.devices[key]
... | A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a
while. |
374,381 | def _httplib2_init(username, password):
obj = httplib2.Http()
if username and password:
obj.add_credentials(username, password)
return obj | Used to instantiate a regular HTTP request object |
374,382 | def does_collection_exist(self, collection_name, database_name=None):
if collection_name is None:
raise AirflowBadRequest("Collection name cannot be None.")
existing_container = list(self.get_conn().QueryContainers(
get_database_link(self.__get_database_name(database_na... | Checks if a collection exists in CosmosDB. |
374,383 | def p_edgesigs(self, p):
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | edgesigs : edgesigs SENS_OR edgesig |
374,384 | def cmd_signing_remove(self, args):
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
self.master.mav.setup_signing_send(self.target_system, self.target_component, [0]*32, 0)
self.master.disable_signing()
print("Remove... | remove signing from server |
374,385 | def _pretty_access_flags_gen(self):
if self.is_public():
yield "public"
if self.is_final():
yield "final"
if self.is_abstract():
yield "abstract"
if self.is_interface():
if self.is_annotation():
yield "@interface"
... | generator of the pretty access flags |
374,386 | def describe_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.get_topic_rule(ruleName=ruleName)
if rule and in rule:
rule = rule[]
keys = ... | Given a topic rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_topic_rule myrule |
374,387 | def on_open(self):
filename, filter = QtWidgets.QFileDialog.getOpenFileName(self, )
if filename:
self.open_file(filename)
self.actionRun.setEnabled(True)
self.actionConfigure_run.setEnabled(True) | Shows an open file dialog and open the file if the dialog was
accepted. |
374,388 | def pretty_date(time=False):
from datetime import datetime
from django.utils import timezone
now = timezone.now()
if isinstance(time, int):
diff = now - datetime.fromtimestamp(time)
elif isinstance(time, datetime):
diff = now - time
elif not time:
diff = now - now
... | Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc |
374,389 | def package_username(repo):
fabsetup-theno-termdown
package = repo.replace(, )
username = repo.split()[1]
return package, username | >>> package_user('fabsetup-theno-termdown')
(termdown, theno) |
374,390 | def get_dihedral(self, i: int, j: int, k: int, l: int) -> float:
v1 = self[k].coords - self[l].coords
v2 = self[j].coords - self[k].coords
v3 = self[i].coords - self[j].coords
v23 = np.cross(v2, v3)
v12 = np.cross(v1, v2)
return math.degrees(math.atan2(np.linalg.... | Returns dihedral angle specified by four sites.
Args:
i: Index of first site
j: Index of second site
k: Index of third site
l: Index of fourth site
Returns:
Dihedral angle in degrees. |
374,391 | def _monitor(last_ping, stop_plugin, is_shutting_down, timeout=5):
_timeout_count = 0
_last_check = time.time()
_sleep_interval = 1
if timeout < _sleep_interval:
_sleep_interval = timeout
while True:
time.sleep(_sleep_interval)
if is_shutting_down():
... | Monitors health checks (pings) from the Snap framework.
If the plugin doesn't receive 3 consecutive health checks from Snap the
plugin will shutdown. The default timeout is set to 5 seconds. |
374,392 | def write_ImageMapLine(tlx, tly, brx, bry, w, h, dpi, chr, segment_start, segment_end):
tlx, brx = [canvas2px(x, w, dpi) for x in (tlx, brx)]
tly, bry = [canvas2px(y, h, dpi) for y in (tly, bry)]
chr, bac_list = chr.split()
return + \
",".join(str(x) for x in (tlx, tly, brx, bry)) \
... | Write out an image map area line with the coordinates passed to this
function
<area shape="rect" coords="tlx,tly,brx,bry" href="#chr7" title="chr7:100001..500001"> |
374,393 | def becomeMemberOf(self, groupRole):
self.store.findOrCreate(RoleRelationship,
group=groupRole,
member=self) | Instruct this (user or group) Role to become a member of a group role.
@param groupRole: The role that this group should become a member of. |
374,394 | def RotateServerKey(cn=u"grr", keylength=4096):
ca_certificate = config.CONFIG["CA.certificate"]
ca_private_key = config.CONFIG["PrivateKeys.ca_key"]
if not ca_certificate or not ca_private_key:
raise ValueError("No existing CA certificate found.")
existing_cert = config.CONFIG["Frontend.certificate... | This function creates and installs a new server key.
Note that
- Clients might experience intermittent connection problems after
the server keys rotated.
- It's not possible to go back to an earlier key. Clients that see a
new certificate will remember the cert's serial number and refuse
to accept ... |
374,395 | def dynamics(start, end=None):
def _(sequence):
if start in _dynamic_markers_to_velocity:
start_velocity = _dynamic_markers_to_velocity[start]
start_marker = start
else:
raise ValueError("Unknown start dynamic: %s, must be in %s" % (start, _dynamic_markers_to... | Apply dynamics to a sequence. If end is specified, it will crescendo or diminuendo linearly from start to end dynamics.
You can pass any of these strings as dynamic markers: ['pppppp', 'ppppp', 'pppp', 'ppp', 'pp', 'p', 'mp', 'mf', 'f', 'ff', 'fff', ''ffff]
Args:
start: beginning dynamic marker, if no... |
374,396 | def public_key(self):
if not self._public_key and self.sec_certificate_ref:
sec_public_key_ref_pointer = new(Security, )
res = Security.SecCertificateCopyPublicKey(self.sec_certificate_ref, sec_public_key_ref_pointer)
handle_sec_error(res)
sec_public_key... | :return:
The PublicKey object for the public key this certificate contains |
374,397 | def _get_representative_batch(merged):
out = {}
for mgroup in merged:
mgroup = sorted(list(mgroup))
for x in mgroup:
out[x] = mgroup[0]
return out | Prepare dictionary matching batch items to a representative within a group. |
374,398 | def as_check_request(self, timer=datetime.utcnow):
if not self.service_name:
raise ValueError(u)
if not self.operation_id:
raise ValueError(u)
if not self.operation_name:
raise ValueError(u)
op = super(Info, self).as_operation(timer=timer)
... | Makes a `ServicecontrolServicesCheckRequest` from this instance
Returns:
a ``ServicecontrolServicesCheckRequest``
Raises:
ValueError: if the fields in this instance are insufficient to
to create a valid ``ServicecontrolServicesCheckRequest`` |
374,399 | def try_rgb(s, default=None):
if not s:
return default
try:
r, g, b = (int(x.strip()) for x in s.split())
except ValueError:
raise InvalidRgb(s)
if not all(in_range(x, 0, 255) for x in (r, g, b)):
raise InvalidRgb(s)
return r, g, b | Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.