Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
349,400 | def send(self, cmd="", timeout=300, wait_for_string=None, password=False):
return self._chain.send(cmd, timeout, wait_for_string, password) | Send the command to the device and return the output.
Args:
cmd (str): Command string for execution. Defaults to empty string.
timeout (int): Timeout in seconds. Defaults to 300 sec (5 min)
wait_for_string (str): This is optional string that driver
waits for afte... |
349,401 | def check_obsolete_version(calculation_mode=):
if os.environ.get() or os.environ.get():
return
headers = {: %
(__version__, calculation_mode, platform.platform(),
config.distribution.oq_distribute)}
try:
req = Request(OQ_API + , headers=headers)... | Check if there is a newer version of the engine.
:param calculation_mode:
- the calculation mode when called from the engine
- an empty string when called from the WebUI
:returns:
- a message if the running version of the engine is obsolete
- the empty string if the engine is ... |
349,402 | def render_export_form(self, request, context, form_url=):
context.update({
: self.has_change_permission(request),
: mark_safe(form_url),
: self.opts,
: True,
: self.save_on_top,
})
return TemplateResponse(request, self.export... | Render the from submission export form. |
349,403 | def status(config=, num_pre=None, num_post=None):
**
try:
pre, post = _get_num_interval(config, num_pre, num_post)
snapper.CreateComparison(config, int(pre), int(post))
files = snapper.GetFiles(config, int(pre), int(post))
status_ret = {}
SUBVOLUME = list_configs()[config... | Returns a comparison between two snapshots
config
Configuration name.
num_pre
first snapshot ID to compare. Default is last snapshot
num_post
last snapshot ID to compare. Default is 0 (current state)
CLI example:
.. code-block:: bash
salt '*' snapper.status
... |
349,404 | def bill(request, abbr, session, bill_id):
fixed_bill_id = fix_bill_id(bill_id)
if fixed_bill_id.replace(, ) != bill_id:
return redirect(, abbr=abbr, session=session, bill_id=fixed_bill_id.replace(, ))
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, : session,
... | Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html |
349,405 | def _runDeferredFunctions(deferredFunctions):
failures = []
for deferredFunction in deferredFunctions:
try:
deferredFunction.invoke()
except:
failures.append(deferredFunction.name)
logger.exception(, deferredFunction)
... | Invoke the specified deferred functions and return a list of names of functions that
raised an exception while being invoked.
:param list[DeferredFunction] deferredFunctions: the DeferredFunctions to run
:rtype: list[str] |
349,406 | def _dicts_to_columns(dicts):
keys = dicts[0].keys()
result = dict((k, []) for k in keys)
for d in dicts:
for k, v in d.items():
result[k] += [v]
return result | Given a List of Dictionaries with uniform keys, returns a single Dictionary
with keys holding a List of values matching the key in the original List.
[{'name': 'Field Museum', 'location': 'Chicago'},
{'name': 'Epcot', 'location': 'Orlando'}]
=>
{'name': ['Field Museum', 'Epcot'],
'location'... |
349,407 | def optimize(self, x0, target):
x = x0
for i in range(self.maxiter):
g = self.g(x, target)
h = self.h(x, target)
if i == 0:
alpha = 0
m = g
else:
alpha = - np.dot(m, np.dot(h, g)) / np.dot(m, np.dot(... | Calculate an optimum argument of an objective function. |
349,408 | def human_time(seconds):
units = [
(, 60 * 60 * 24 * 7 * 52),
(, 60 * 60 * 24 * 7),
(, 60 * 60 * 24),
(, 60 * 60),
(, 60),
(, 1),
]
seconds = int(seconds)
if seconds < 60:
return .format(seconds)
for i in range(len(units) - 1):
u... | Returns a human-friendly time string that is always exactly 6
characters long.
Depending on the number of seconds given, can be one of::
1w 3d
2d 4h
1h 5m
1m 4s
15s
Will be in color if console coloring is turned on.
Parameters
----------
seconds : in... |
349,409 | def info(self):
status, dim_name, dim_size, data_type, n_attrs = \
_C.SDdiminfo(self._id)
_checkErr(, status, )
return dim_name, dim_size, data_type, n_attrs | Return info about the dimension instance.
Args::
no argument
Returns::
4-element tuple holding:
- dimension name; 'fakeDimx' is returned if the dimension
has not been named yet, where 'x' is the dimension
index number
- dimension lengt... |
349,410 | def show(self, dialog):
for dlg in list(self.dialogs.values()):
if to_text_string(dlg.windowTitle()) \
== to_text_string(dialog.windowTitle()):
dlg.show()
dlg.raise_()
break
else:
dialog.show()
... | Generic method to show a non-modal dialog and keep reference
to the Qt C++ object |
349,411 | def MoveFile(source_filename, target_filename):
_AssertIsLocal(source_filename)
_AssertIsLocal(target_filename)
import shutil
shutil.move(source_filename, target_filename) | Moves a file.
:param unicode source_filename:
:param unicode target_filename:
:raises NotImplementedForRemotePathError:
If trying to operate with non-local files. |
349,412 | def cmPrecision(cm, average=True):
cm = cm.type(torch.float64)
precision = cm.diag() / (cm.sum(dim=0) + 1e-15)
if average:
return precision.mean()
return precision | Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda |
349,413 | def toProtocolElement(self):
readGroup = protocol.ReadGroup()
readGroup.id = self.getId()
readGroup.created = self._creationTime
readGroup.updated = self._updateTime
dataset = self.getParentContainer().getParentContainer()
readGroup.dataset_id =... | Returns the GA4GH protocol representation of this ReadGroup. |
349,414 | def integer_binning(data=None, **kwargs) -> StaticBinning:
if "range" in kwargs:
kwargs["range"] = tuple(r - 0.5 for r in kwargs["range"])
return fixed_width_binning(data=data, bin_width=kwargs.pop("bin_width", 1),
align=True, bin_shift=0.5, **kwargs) | Construct fixed-width binning schema with bins centered around integers.
Parameters
----------
range: Optional[Tuple[int]]
min (included) and max integer (excluded) bin
bin_width: Optional[int]
group "bin_width" integers into one bin (not recommended) |
349,415 | def generate(pseudo_ast, language):
pypythonrbrubyjavascriptjscscsharpgocpp
if isinstance(pseudo_ast, dict):
pseudo_ast = pseudo.loader.convert_to_syntax_tree(pseudo_ast)
translated_ast = API_TRANSLATORS[language](pseudo_ast).api_translate()
return GENERATORS[language]().generate(translated_ast... | generate output code in `language`
`pseudo_ast` can be a plain `dict` with ast data or
it can use the internal `pseudo` `Node(type, **fields)` format
if you want to play with it, you can use `generate_main` which
expects just a dict node / a list of dict nodes and a language
`language` can be 'p... |
349,416 | def loadcommon(sources, load_task, asynchronous=True, predicate=None,
task_args=None, task_kwargs=None):
task_args = tuple() if task_args is None else task_args
task_kwargs = dict() if task_kwargs is None else task_kwargs
click.echo()
for idx, source in enumerate(sources, 1):
... | Common helper function for load simple objects.
.. note::
Keyword arguments ``task_args`` and ``task_kwargs`` are passed to the
``load_task`` function as ``*task_args`` and ``**task_kwargs``.
.. note::
The `predicate` argument is used as a predicate function to load only
a *single* i... |
349,417 | def round(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_rint_round,
(BigFloat._implicit_convert(x),),
context,
) | Return the nearest integer to x, rounding halfway cases *away from zero*.
If the result is not exactly representable, it will be rounded according to
the current context.
.. note::
This function corresponds to the MPFR function ``mpfr_rint_round``, not
to ``mpfr_round``. |
349,418 | def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):
if ignore_index is not None:
assert tensor.size() == tensor_other.size()
mask_arr = tensor.ne(ignore_index)
tensor = tensor.masked_select(mask_arr)
tensor_other = tensor_other.masked_select(mask_arr)
re... | Compute ``torch.equal`` with the optional mask parameter.
Args:
ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.
Returns:
(bool) Returns ``True`` if target and prediction are equal. |
349,419 | def fill_subparser(subparser):
url =
filename =
subparser.set_defaults(urls=[url], filenames=[filename])
return default_downloader | Sets up a subparser to download the CIFAR-10 dataset file.
The CIFAR-10 dataset file is downloaded from Alex Krizhevsky's
website [ALEX].
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `cifar10` command. |
349,420 | def plotit(self, x, y, fields, colors=[], title=None):
pylab.ion()
self.fig = pylab.figure(num=1, figsize=(12,6))
self.ax1 = self.fig.gca()
ax2 = None
for i in range(0, len(fields)):
if len(x[i]) == 0: continue
if self.lowest_x is None or x[i][0] ... | plot a set of graphs using date for x axis |
349,421 | def create(self, width=0, max_value=0, path=None, flags=0, seed=0):
return _madoka.Sketch_create(self, width, max_value, path, flags, seed) | Create new sketch
Params:
<int> width
<int> max_value
<str> path
<int> flags
<int> seed |
349,422 | def posts(self, channel, page=None):
entrypoint = self.RCHANNELS + + channel + + self.RPOSTS
params = {
self.PPER_PAGE: self.max_items
}
if page is not None:
params[self.PPAGE] = page
response = self._fetch(entrypoint, params)
retur... | Fetch the history of a channel. |
349,423 | def dict(self):
metadata = {}
properties = {}
for name, prop in list(self.properties.items()):
properties[name] = prop.dict
metadata[] = properties
return metadata | dictionary representation of the metadata.
:return: dictionary representation of the metadata
:rtype: dict |
349,424 | def weighted_variance (x, weights):
n = len (x)
if n < 3:
raise ValueError (
)
wt_mean = np.average (x, weights=weights)
return np.average (np.square (x - wt_mean), weights=weights) * n / (n - 1) | Return the variance of a weighted sample.
The weighted sample mean is calculated and subtracted off, so the returned
variance is upweighted by ``n / (n - 1)``. If the sample mean is known to
be zero, you should just compute ``np.average (x**2, weights=weights)``. |
349,425 | def add_mv_grid_district(self, mv_grid_district):
if mv_grid_district not in self.mv_grid_districts():
self._mv_grid_districts.append(mv_grid_district) | Adds a MV grid_district to _mv_grid_districts if not already existing |
349,426 | def remove(self, idx):
data = {}
for k in self.data:
data[k] = np.delete(self.data[k], idx)
return self._return(data=data) | Return a new DictArray that does not contain the indexed values |
349,427 | def get_kinds(self, kind, R):
stats = self.hazard_stats()
if kind == :
yield from stats
return
elif kind == :
for r in range(R):
yield % r
return
elif kind:
yield kind
return
... | Yield 'rlz-000', 'rlz-001', ...', 'mean', 'quantile-0.1', ... |
349,428 | def _BreakpointEvent(self, event, frame):
error_status = None
if event != native.BREAKPOINT_EVENT_HIT:
error_status = _BREAKPOINT_EVENT_STATUS[event]
elif self.definition.get() == :
error_status = self._collector.Log(frame)
if not error_status:
return
if not self.... | Callback invoked by cdbg_native when breakpoint hits.
Args:
event: breakpoint event (see kIntegerConstants in native_module.cc).
frame: Python stack frame of breakpoint hit or None for other events. |
349,429 | def fetch_last(response: Response) -> typing.Union[str, None]:
recent_paths = environ.configs.fetch(, [])
if len(recent_paths) < 1:
response.fail(
code=,
message=
).console()
return None
return recent_paths[0] | Returns the last opened project path if such a path exists |
349,430 | def new_figure_manager(num, *args, **kwargs):
if __debug__: verbose.report(,
)
FigureClass = kwargs.pop(, Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig) | Create a new figure manager instance |
349,431 | def create(self, name, **kwargs):
new_backend = kwargs.pop("new_backend", False)
resource = _format_old_api_request(content_type="json")
if new_backend:
resource += "?nbe=true"
payload = {"name": name}
if "row_identifier" in kwargs:
payload["met... | Create a dataset, including the field types. Optionally, specify args such as:
description : description of the dataset
columns : list of columns (see docs/tests for list structure)
category : must exist in /admin/metadata
tags : list of tag strings
row_identi... |
349,432 | def fuzzy_date_parser(self, text):
try:
parsed = dateparser.parse(text, dayfirst=True)
return parsed
except (ValueError, TypeError):
locales = parsedatetime._locales[:]
for locale in locales:
const = parse... | Thin wrapper around ``parsedatetime`` and ``dateutil`` modules.
Since there's no upstream suppport for multiple locales, this wrapper
exists.
:param str text: Text to parse.
:returns: A parsed date/time object. Raises exception on failure.
:rtype: datetime |
349,433 | def create_stack(
self,
stack_name,
stack_template_name,
parameters=None,
capabilities=None
):
stack_template_path = pathlib.Path(
self.template_dir).joinpath(stack_template_name)
create_stack(
stack_nam... | Create a stack using Amazon's Cloud formation |
349,434 | def save(self, path):
f = h5py.File(path, )
try:
fm_group = f.create_group()
for field in self.fieldnames():
try:
fm_group.create_dataset(field, data = self.__dict__[field])
except (TypeError,) as e:
... | Saves Datamat to path.
Parameters:
path : string
Absolute path of the file to save to. |
349,435 | def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0):
if isinstance(plain_date, datetime.datetime):
return plain_date
return datetime.datetime(
plain_date.year,
plain_date.month,
plain_date.day,
hours,
minutes,
seconds,
ms,
... | given a datetime.date, gives back a datetime.datetime |
349,436 | def _append_plain_text(self, text, before_prompt=False):
self._append_custom(self._insert_plain_text, text, before_prompt) | Appends plain text, processing ANSI codes if enabled. |
349,437 | def _joint_log_likelihood(self, X):
check_is_fitted(self, "classes_")
X = check_array(X, accept_sparse=)
X_bin = self._transform_data(X)
n_classes, n_features = self.feature_log_prob_.shape
n_samples, n_features_X = X_bin.shape
if n_features_X != n_features:
... | Calculate the posterior log probability of the samples X |
349,438 | def build_tree(self, rebuild=False):
time_qualifier = self.process_hierarchy.bottom_process.time_qualifier
process_name = self.process_hierarchy.bottom_process.process_name
if rebuild or self.build_timeperiod is None:
timeperiod = settings.settings[]
else:
... | method builds tree by iterating from the synergy_start_timeperiod to the current time
and inserting corresponding nodes |
349,439 | def generate(env):
try:
bld = env[][]
except KeyError:
bld = RpmBuilder
env[][] = bld
env.SetDefault(RPM = )
env.SetDefault(RPMFLAGS = SCons.Util.CLVar())
env.SetDefault(RPMCOM = rpmAction)
env.SetDefault(RPMSUFFIX = ) | Add Builders and construction variables for rpm to an Environment. |
349,440 | def format_data(self, value):
s = locale.format_string(, (value,))
return self.fix_minus(s) | Return a formatted string representation of a number. |
349,441 | def d2Sbus_dV2(Ybus, V, lam):
n = len(V)
Ibus = Ybus * V
diaglam = spdiag(lam)
diagV = spdiag(V)
A = spmatrix(mul(lam, V), range(n), range(n))
B = Ybus * diagV
C = A * conj(B)
D = Ybus.H * diagV
E = conj(diagV) * (D * diaglam - spmatrix(D*lam, range(n), range(n)))
F = C - A... | Computes 2nd derivatives of power injection w.r.t. voltage. |
349,442 | def chars(string: any) -> str:
return .join([c if c.isalpha() else for c in str(string)]) | Return all (and only) the chars in the given string. |
349,443 | def update_record(self, dns_type, name, content, **kwargs):
record = self.get_record(dns_type, name)
data = {
: dns_type,
: name,
: content
}
if kwargs.get() and kwargs[] != 1:
data[] = kwargs[]
if kwargs.get() is True:
... | Update dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: |
349,444 | def _load_resources(self):
for resource in self.RESOURCES:
if isinstance(resource, goldman.ModelsResource):
route = % resource.rtype
elif isinstance(resource, goldman.ModelResource):
route = % resource.rtype
elif isinstance(resource... | Load all the native goldman resources.
The route or API endpoint will be automatically determined
based on the resource object instance passed in.
INFO: Only our Model based resources are supported when
auto-generating API endpoints. |
349,445 | def infer(self, inputPattern, computeScores=True, overCategories=True,
partitionId=None):
sparsity = 0.0
if self.minSparsity > 0.0:
sparsity = ( float(len(inputPattern.nonzero()[0])) /
len(inputPattern) )
if len(self._categoryList) == 0 or sparsity < sel... | Finds the category that best matches the input pattern. Returns the
winning category index as well as a distribution over all categories.
:param inputPattern: (list or array) The pattern to be classified. This
must be a dense representation of the array (e.g. [0, 0, 1, 1, 0, 1]).
:param computeSco... |
349,446 | def list2dict(list_of_options):
d = {}
for key, value in list_of_options:
d[key] = value
return d | Transforms a list of 2 element tuples to a dictionary |
349,447 | def update(self, is_reserved=values.unset):
return self._proxy.update(is_reserved=is_reserved, ) | Update the ShortCodeInstance
:param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only
:returns: Updated ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance |
349,448 | def _job_queue_empty(self):
self._iteratively_clean_pending_exits()
while self._pending_jobs:
pending_job = self._get_one_pending_job()
if pending_job is None:
continue
self._insert_job(pending_job)
self._register_a... | A callback method called when the job queue is empty.
:return: None |
349,449 | def get_enclosingmethod(self):
buff = self.get_attribute("EnclosingMethod")
if buff is None:
return None
with unpack(buff) as up:
ci, mi = up.unpack_struct(_HH)
result = None
i... | the class.method or class (if the definition is not from within a
method) that encloses the definition of this class. Returns
None if this was not an inner class.
reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.7 |
349,450 | def list_app_profiles(self):
resp = self._client.instance_admin_client.list_app_profiles(self.name)
return [AppProfile.from_pb(app_profile, self) for app_profile in resp] | Lists information about AppProfiles in an instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_list_app_profiles]
:end-before: [END bigtable_list_app_profiles]
:rtype: :list:[`~google.cloud.bigtable.app_profile.AppProfile`]
:retu... |
349,451 | def project_delete(project_id=None, name=None, profile=None, **connection_args):
***
auth(profile, **connection_args)
if _OS_IDENTITY_API_VERSION > 2:
return tenant_delete(tenant_id=project_id, name=name, profile=None, **connection_args)
else:
return False | Delete a project (keystone project-delete).
Overrides keystone tenant-delete form api V2. For keystone api V3 only.
.. versionadded:: 2016.11.0
project_id
The project id.
name
The project name.
profile
Configuration profile - if configuration for multiple openstack accoun... |
349,452 | def _undo_save(self, datastreams, logMessage=None):
return [ds for ds in datastreams if self.dscache[ds].undo_last_save(logMessage)] | Takes a list of datastreams and a datetime, run undo save on all of them,
and returns a list of the datastreams where the undo succeeded.
:param datastreams: list of datastream ids (should be in self.dscache)
:param logMessage: optional log message |
349,453 | def rc_channels_override_encode(self, target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw):
return MAVLink_rc_channels_override_message(target_system, target_component, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_... | The RAW values of the RC channels sent to the MAV to override info
received from the RC radio. A value of UINT16_MAX
means no change to that channel. A value of 0 means
control of that channel should be released back to the
RC radio. The standard PPM modul... |
349,454 | def replace_parent(self, parent_simples):
assert parent_simples
ancestors = parent_simples[:-1]
parent = parent_simples[-1]
did_replace = False
new_tokens = []
for token in self.tokens:
if not did_replace and token in (, ):
did_repla... | If ``&`` (or the legacy xCSS equivalent ``self``) appears in this
selector, replace it with the given iterable of parent selectors.
Returns a tuple of simple selectors. |
349,455 | def read_namespace_status(self, name, **kwargs):
kwargs[] = True
if kwargs.get():
return self.read_namespace_status_with_http_info(name, **kwargs)
else:
(data) = self.read_namespace_status_with_http_info(name, **kwargs)
return data | read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace_status(name, async_req=True)
>>> res... |
349,456 | def update_certificate_issuer_config(self, certificate_issuer_config_request, **kwargs):
kwargs[] = True
if kwargs.get():
return self.update_certificate_issuer_config_with_http_info(certificate_issuer_config_request, **kwargs)
else:
(data) = self.update_certi... | Update certificate issuer configuration. # noqa: E501
Configure the certificate issuer to be used when creating device certificates for LwM2M communication. <br> **Example usage:** ``` curl -X PUT \\ -H 'authorization: <valid access token>' \\ -H 'content-type: application/json;charset=UTF-8' \\ https://api.... |
349,457 | def symm_group_cubic(mat):
sym_group = np.zeros([24, 3, 3])
sym_group[0, :] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
sym_group[1, :] = [[1, 0, 0], [0, -1, 0], [0, 0, -1]]
sym_group[2, :] = [[-1, 0, 0], [0, 1, 0], [0, 0, -1]]
sym_group[3, :] = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]]
sym_group[4, :] =... | obtain cubic symmetric eqivalents of the list of vectors.
Args:
matrix (lattice matrix, n by 3 array/matrix)
Return:
cubic symmetric eqivalents of the list of vectors. |
349,458 | def concat_chunks(data, ipyclient):
start = time.time()
printstr =
lbview = ipyclient.load_balanced_view()
elapsed = datetime.timedelta(seconds=int(time.time()-start))
progressbar(10, 0, printstr.format(elapsed), spacer=data._spacer)
ftmps = glob.glob(os.path.join(data.dirs.fas... | Concatenate chunks. If multiple chunk files match to the same sample name
but with different barcodes (i.e., they are technical replicates) then this
will assign all the files to the same sample name file. |
349,459 | def get_persistent_boot_device(self):
result = self._get_persistent_boot()
boot_mode = self._check_boot_mode(result)
if boot_mode == :
return result[0][]
value = result[0][]
if in value:
return
elif in value or in value:
... | Get the current persistent boot device set for the host. |
349,460 | def _replaceRenamedPairMembers(kerning, leftRename, rightRename):
renamedKerning = {}
for (left, right), value in kerning.items():
left = leftRename.get(left, left)
right = rightRename.get(right, right)
renamedKerning[left, right] = value
return renamedKerning | Populate the renamed pair members into the kerning. |
349,461 | def stream_download(self, chunk_size=None, callback=None):
chunk_size = chunk_size or CONTENT_CHUNK_SIZE
with contextlib.closing(self.internal_response) as response:
for chunk in response.iter_content(chunk_size):
if not chunk:
... | Generator for streaming request body data.
:param callback: Custom callback for monitoring progress.
:param int chunk_size: |
349,462 | def get_queryset(self):
qs = super(DatatablesView, self).get_queryset()
qs = self.global_search(qs)
qs = self.column_search(qs)
return qs.order_by(*self.get_orders()) | Apply Datatables sort and search criterion to QuerySet |
349,463 | def csv_to_list(csv_file, delimiter=):
with open_csv(csv_file) as csv_con:
if len(delimiter) > 1:
dialect = csv.Sniffer().sniff(csv_con.read(1024),
delimiters=delimiter)
csv_con.seek(0)
reader = csv.reader(csv_con, dialect)
... | Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table. |
349,464 | def ext_pillar(minion_id, pillar, *args, **kwargs):
for i in args:
if not in i:
path =
args[i][] = path
log.warning(, path)
else:
path = i[]
salt_data = {
: __opts__,... | Compile pillar data |
349,465 | def predict(self, X, y=None, output="margin", tree_limit=None):
if tree_limit is None:
tree_limit = -1 if self.tree_limit is None else self.tree_limit
if str(type(X)).endswith("pandas.core.series.Series>"):
X = X.values
flat_output = False
... | A consistent interface to make predictions from this model.
Parameters
----------
tree_limit : None (default) or int
Limit the number of trees used by the model. By default None means no use the limit of the
original model, and -1 means no limit. |
349,466 | def _fail(self, event, message=):
notification = {
: ,
: ,
: message
}
ip = event.sock.getpeername()[0]
self.failing_clients[ip] = event
Timer(3, Event.create(, event.clientuuid, notification, ip)).register(self) | Sends a failure message to the requesting client |
349,467 | def on_cluster(self, up):
similar = self.similarity_view.selected
if up.added:
self._update_cluster_view()
if up.history == :
clusters_0, clusters_1 = up.undo_state[0][]
self.cluster_view.sel... | Update the cluster views after clustering actions. |
349,468 | def create_eager_metrics(metric_names, weights_fn=common_layers.weights_all):
metric_fns = dict(
[(name, METRICS_FNS[name]) for name in metric_names])
return create_eager_metrics_internal(metric_fns, weights_fn) | Create metrics accumulators and averager for Eager mode.
Args:
metric_names: list<str> from Metrics enum
weights_fn: function that takes labels and returns a weights mask. Defaults
to weights of all 1, i.e. common_layers.weights_all. Use
common_layers.weights_nonzero if labels have 0-padding.
... |
349,469 | def remove_unhealthy_peers( self, count, con=None, path=None, peer_table=None, min_request_count=10, min_health=MIN_PEER_HEALTH ):
if path is None:
path = self.atlasdb_path
removed = []
rank_peer_list = atlas_rank_peers_by_health( peer_table=peer_table, with_rank=T... | Remove up to @count unhealthy peers
Return the list of peers we removed |
349,470 | def login_and_store_credentials_in_session(request, *args, **kwargs):
response = authviews.login(request, *args, **kwargs)
if request.method == "POST" and request.user.is_authenticated():
return response | Custom login view. Calls the standard Django authentication,
but on successful login, stores encrypted user credentials in
order to allow accessing the Fedora repository with the
credentials of the currently-logged in user (e.g., when the
application and Fedora share a common authentication system, suc... |
349,471 | def _inject_jump(self, where, dest):
if sys.version_info[0] < 3:
old_check_interval = sys.getcheckinterval()
sys.setcheckinterval(2**20)
else:
old_check_interval = sys.getswitchinterval()
sys.setswitchinterval(1000)
pb = ctypes.pointer(self.ob_sval)
... | Monkeypatch bytecode at ``where`` to force it to jump to ``dest``.
Returns function which puts things back to how they were. |
349,472 | def module_description(module__name__, module__doc__, module__file__):
mod_name = os.path.splitext(os.path.basename(module__file__))[0]
mod_desc = (lambda x: x + + *len(x) + )(+mod_name) if mod_name else
for name, obj in inspect.getmembers(sys.modules[module__name__]):
if inspect.isclass(obj... | Return formatted text that lists the module-level and class-level
embedded documentation. The function should be called exactly
as:
taskforce.utils.module_description(__name__, __doc__, __file__)
The most common use for this function is to produce the help
message for test code in a library m... |
349,473 | def is_file(raise_ex: bool = False, summary: bool = True,
**items: Any) -> ValidationReturn:
return Validator.__test_all(
condition=lambda _, val: Path(val).is_file(),
formatter=lambda name, _: " is not a file".format(varname=name),
validators=[partia... | Tests if the given key-value pairs (items) are physical existent files or links to regular
files.
Per default this function yields whether ``True`` or ``False`` depending on the fact if all
items withstand the validation or not. Per default the validation / evaluation is
short-circuit an... |
349,474 | def _store(self, start, obj, size, overwrite=False):
stored_object = StoredObject(start, obj, size)
self._object_mapping[stored_object.obj_id] = stored_object
self.__store(stored_object, overwrite=overwrite) | Store a variable into the storage.
:param int start: The beginning address of the variable.
:param obj: The object to store.
:param int size: Size of the object to store.
:param bool overwrite: Whether existing objects should be overwritten or not.
:return: None |
349,475 | def locate_range(self, chrom, start=None, stop=None):
slice_chrom = self.locate_key(chrom)
if start is None and stop is None:
return slice_chrom
else:
pos_chrom = SortedIndex(self.pos[slice_chrom])
try:
slice_within_chrom = pos_chr... | Locate slice of index containing all entries within the range
`key`:`start`-`stop` **inclusive**.
Parameters
----------
chrom : object
Chromosome or contig.
start : int, optional
Position start value.
stop : int, optional
Position stop... |
349,476 | def _walk_req_to_install(self, handler):
discovered_reqs = []
reqs = itertools.chain(
list(self.unnamed_requirements), list(self.requirements.values()),
discovered_reqs)
for req_to_install in reqs:
more_reqs = handler(req_to_install)
... | Call handler for all pending reqs.
:param handler: Handle a single requirement. Should take a requirement
to install. Can optionally return an iterable of additional
InstallRequirements to cover. |
349,477 | def key_swap(
d,
cls,
marshal
):
dname = .format("" if marshal else "un")
if hasattr(cls, dname):
key_swap = getattr(cls, dname)
return {
key_swap[k] if k in key_swap else k: v
for k, v in d.items()
}
else:
return d | Swap the keys in a dictionary
Args:
d: dict, The dict to swap keys in
cls: class, If the class has a staticly defined
_marshal_key_swap and/or _unmarshal_key_swap dict,
the keys will be swapped.
Otherwise @d is ret... |
349,478 | def _create_latent_variables(self):
for ar_term in range(self.ar):
self.latent_variables.add_z( + str(ar_term+1) + , fam.Normal(0,0.5,transform=None), fam.Normal(0,3))
for sc_term in range(self.sc):
self.latent_variables.add_z( + str(sc_term+1) + , fam.Normal(0,0.5,tra... | Creates model latent variables
Returns
----------
None (changes model attributes) |
349,479 | def random(self, numnodes = 10, degree_range = (2, 4), length_range = (1, 10),
density = None, edge_format = None, node_format = None,
Euclidean = False, seedInput = 0, add_labels = True,
parallel_allowed = False, node_selection = ,
scale = 10, scale_cost = 5)... | API:
random(self, numnodes = 10, degree_range = None, length_range = None,
density = None, edge_format = None, node_format = None,
Euclidean = False, seedInput = 0)
Description:
Populates graph with random edges and nodes.
Input:
numnodes... |
349,480 | def _make_local_block(x, depth, batch, heads, num_blocks, block_length):
prev_block = tf.slice(x, [0, 0, 0, 0, 0],
[-1, -1, num_blocks - 1, -1, -1])
cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1])
local_block = tf.concat([prev_block, cur_block], 3)
return tf.reshape(loc... | Helper function to create a local version of the keys or values for 1d. |
349,481 | def _get_desktop_size():
if platform.system() == "Linux":
try:
xrandr_query = subprocess.check_output(["xrandr", "--query"])
sizes = re.findall(r"\bconnected primary (\d+)x(\d+)", str(xrandr_query))
if sizes[0]:
return point.Point(int(sizes[0][0]), int(sizes[0][1]))
except:
... | Get the desktop size. |
349,482 | def viewType(self, name):
for view in self._viewTypes:
if view.viewName() == name:
return view
return None | Looks up the view class based on the inputd name.
:param name | <str>
:return <subclass of XView> || None |
349,483 | def _psi(self,m):
return 2.*self.a2*(1./(1.+m/self.a)+numpy.log(m/(m+self.a))) | \psi(m) = -\int_m^\infty d m^2 \rho(m^2) |
349,484 | def get_function(session_factory, name, role, sns_topic, log_groups,
subject="Lambda Error", pattern="Traceback"):
from c7n.mu import (
LambdaFunction, PythonPackageArchive, CloudWatchLogSubscription)
config = dict(
name=name,
handler=,
runtime=,
... | Lambda function provisioning.
Self contained within the component, to allow for easier reuse. |
349,485 | def create_table(clas,pool_or_cursor):
"uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model"
def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else )
fields = .join(map(.join,map(mkfield,clas.FIELDS)))
base = %(clas.TABLE,fields)
if clas.PKEY: bas... | uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model |
349,486 | def _parse_command_response(response):
try:
root = ET.fromstring(response.text)
except ET.ParseError:
raise ResponseParseError(
"Unexpected response format, could not parse XML. Response: {}".format(response.text))
return root | Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The requests response object
:return: An ElementTree... |
349,487 | def query(self, name, node):
qref = qualify(name, node, node.namespace())
query = BlindQuery(qref)
result = query.execute(self.schema)
return (result, []) | blindly query the schema by name |
349,488 | def _debug_log(self, msg):
if not self.debug:
return
sys.stderr.write(.format(msg)) | Debug log messages if debug=True |
349,489 | def full_task(self, token_id, presented_pronunciation, pronunciation, pronunciation_probability,
warn=True, default=True):
if pronunciation_probability is not None and not 0. < pronunciation_probability < 1. and warn:
logging.warning(
... | Provide the prediction of the full task.
This function is used to predict the probability of a given pronunciation being reported for a given token.
:param token_id: The token for which the prediction is provided
:param pronunciation: The pronunciation for which the prediction is being made (a... |
349,490 | def triangle_colors(tile_x, tile_y, tile_size, pix):
quad_size = tile_size / 2
north = []
for y in xrange(tile_y, tile_y + quad_size):
x_off = y - tile_y
for x in xrange(tile_x + x_off, tile_x + tile_size - x_off):
north.append(pix[x, y])
south = []
for y in xrange... | Extracts the average color for each triangle in the given tile. Returns
a 4-tuple of colors for the triangles in this order: North, East, South,
West (clockwise). |
349,491 | def get_url(self, domain_name=DOMAIN_ENGLISH):
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "tag") % {"name": name} | Returns the URL of the tag page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o ... |
349,492 | def _get_music_services_data(cls):
if cls._music_services_data is not None:
return cls._music_services_data
result = {}
root = XML.fromstring(
cls._get_music_services_data_xml().encode()
)
... | Parse raw account data xml into a useful python datastructure.
Returns:
dict: Each key is a service_type, and each value is a
`dict` containing relevant data. |
349,493 | def errors(self,
errors: List[str],
code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST,
key: str = ,
headers: Optional[Dict[str, str]] = None,
):
return jsonify({key: errors}), code, headers or {} | Convenience method to return errors as json.
:param errors: The list of errors.
:param code: The HTTP status code.
:param key: The key to return the errors under.
:param headers: Any optional headers. |
349,494 | def close(self, code=1000, message=):
try:
message = self._encode_bytes(message)
self.send_frame(
struct.pack( % len(message), code, message),
opcode=self.OPCODE_CLOSE)
except WebSocketError:
logger.de... | Close the websocket and connection, sending the specified code and
message. The underlying socket object is _not_ closed, that is the
responsibility of the initiator. |
349,495 | def connection(self, shareable=True):
if shareable and self._maxshared:
self._lock.acquire()
try:
while (not self._shared_cache and self._maxconnections
and self._connections >= self._maxconnections):
self._wait_lock()
... | Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads. |
349,496 | def plot_diodespec(ON_obs,OFF_obs,calflux,calfreq,spec_in,units=,**kwargs):
dspec = diode_spec(ON_obs,OFF_obs,calflux,calfreq,spec_in,**kwargs)
obs = Waterfall(ON_obs,max_load=150)
freqs = obs.populate_freqs()
chan_per_coarse = obs.header[]/obs.calc_n_coarse_chan()
coarse_freqs = convert_to_co... | Plots the full-band Stokes I spectrum of the noise diode (ON-OFF) |
349,497 | def handle(self, *args, **options):
conn = get_boto_ses_connection()
self._print_quota(conn)
self._print_daily_stats(conn) | Renders the output by piecing together a few methods that do the
dirty work. |
349,498 | def _hook_id(self, info):
if isinstance(info, dict) and in info.keys():
self.id = info[] | Extract id from info. Override for custom behaviour. |
349,499 | def imsi(number):
number = to_decimal(number)
groups = (number[:3], number[3:5], number[5:])
return u.join(list(filter(None, groups))) | Printable International Mobile Subscriber Identity (IMSI) numbers. Mind
that there is no validation done on the actual correctness of the MCC/MNC.
If you wish to validate IMSI numbers, take a look at `python-stdnum`_.
:param number: string or int
>>> print(imsi(2042312345))
204-23-12345
.. _p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.