Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
16,000 | def _OpenCollectionPath(coll_path):
hunt_collection = results.HuntResultCollection(coll_path)
if hunt_collection and hunt_collection[0].payload:
return hunt_collection
indexed_collection = sequential_collection.GeneralIndexedCollection(coll_path)
if indexed_collection:
return indexed_collection | Tries to open various types of collections at the given path. |
16,001 | def unpack_rsp(cls, rsp_pb):
ret_type = rsp_pb.retType
ret_msg = rsp_pb.retMsg
if ret_type != RET_OK:
return RET_ERROR, ret_msg, None
res = {}
if rsp_pb.HasField():
res[] = rsp_pb.s2c.serverVer
res[] = rsp_pb.s2c.loginUserID
... | Unpack the init connect response |
16,002 | def setup(applicationName,
applicationType=None,
style=,
splash=,
splashType=None,
splashTextColor=,
splashTextAlign=None,
theme=):
import_qt(globals())
output = {}
if not QtGui.QApplication.instance():
... | Wrapper system for the QApplication creation process to handle all proper
pre-application setup. This method will verify that there is no application
running, creating one if necessary. If no application is created, a None
value is returned - signaling that there is already an app running. If you
... |
16,003 | def _call(self, method, params):
url = self.base_url % {: self.bot_token, : method}
logger.debug("Telegram bot calls method: %s params: %s",
method, str(params))
r = self.fetch(url, payload=params)
return r.text | Retrive the given resource.
:param resource: resource to retrieve
:param params: dict with the HTTP parameters needed to retrieve
the given resource |
16,004 | def _export_to2marc(self, key, value):
def _is_for_cds(value):
return in value
def _is_for_hal(value):
return in value and value[]
def _is_not_for_hal(value):
return in value and not value[]
result = []
if _is_for_cds(value):
result.append({: })
if _i... | Populate the ``595`` MARC field. |
16,005 | def pubkey(self, identity, ecdh=False):
curve_name = identity.get_curve_name(ecdh=ecdh)
log.debug(,
identity.to_string(), curve_name, self)
addr = identity.get_bip32_address(ecdh=ecdh)
result = self._defs.get_public_node(
self.conn,
n=ad... | Return public key. |
16,006 | def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | Set random seed for python, numpy and pytorch RNGs |
16,007 | def loadFromCheckpoint(savedModelDir, newSerialization=False):
if newSerialization:
return HTMPredictionModel.readFromCheckpoint(savedModelDir)
else:
return Model.load(savedModelDir) | Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance. |
16,008 | def baseline(y_true, y_score=None):
if len(y_true) > 0:
return np.nansum(y_true)/count(y_true, countna=False)
else:
return 0.0 | Number of positive labels divided by number of labels,
or zero if there are no labels |
16,009 | def create_entity(self):
self._highest_id_seen += 1
entity = Entity(self._highest_id_seen, self)
self._entities.append(entity)
return entity | Create a new entity.
The entity will have a higher UID than any previously associated
with this world.
:return: the new entity
:rtype: :class:`essence.Entity` |
16,010 | async def _connect_and_read(self):
while not self._stopped:
try:
self._connection_attempts += 1
async with aiohttp.ClientSession(
loop=self._event_loop,
timeout=aiohttp.ClientTimeout(total=self.timeout),
... | Retreives and connects to Slack's RTM API.
Makes an authenticated call to Slack's RTM API to retrieve
a websocket URL. Then connects to the message server and
reads event messages as they come in.
If 'auto_reconnect' is specified we
retrieve a new url and reconnect any time the... |
16,011 | def compile_compiler_bridge(self, context):
bridge_jar_name =
bridge_jar = os.path.join(self._compiler_bridge_cache_dir, bridge_jar_name)
global_bridge_cache_dir = os.path.join(self._zinc_factory.get_options().pants_bootstrapdir, fast_relpath(self._compiler_bridge_cache_dir, self._workdir()))
glo... | Compile the compiler bridge to be used by zinc, using our scala bootstrapper.
It will compile and cache the jar, and materialize it if not already there.
:param context: The context of the task trying to compile the bridge.
This is mostly needed to use its scheduler to create digests of the... |
16,012 | def from_int(cls, integer):
bin_string = bin(integer)
return cls(
text=len(bin_string) >= 1 and bin_string[-1] == "1",
comment=len(bin_string) >= 2 and bin_string[-2] == "1",
user=len(bin_string) >= 3 and bin_string[-3] == "1",
restricted=len(bin... | Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`
column of the `revision` MariaDB table.
* DELETED_TEXT = 1
* DELETED_COMMENT = 2
* DELETED_USER = 4
* DELETED_RESTRICTED = 8 |
16,013 | def normalize(pw):
pw_lower = pw.lower()
return .join(helper.L33T.get(c, c) for c in pw_lower) | Lower case, and change the symbols to closest characters |
16,014 | def _MergeTaskStorage(self, storage_writer):
if self._processing_profiler:
self._processing_profiler.StartTiming()
for task_identifier in storage_writer.GetProcessedTaskIdentifiers():
try:
task = self._task_manager.GetProcessedTaskByIdentifier(task_identifier)
self._task_manag... | Merges a task storage with the session storage.
This function checks all task stores that are ready to merge and updates
the scheduled tasks. Note that to prevent this function holding up
the task scheduling loop only the first available task storage is merged.
Args:
storage_writer (StorageWrite... |
16,015 | def run_task_class(self, class_path, **options):
logger.console("\n")
task_class, task_config = self._init_task(class_path, options, TaskConfig())
return self._run_task(task_class, task_config) | Runs a CumulusCI task class with task options via kwargs.
Use this keyword to run logic from CumulusCI tasks which have not
been configured in the project's cumulusci.yml file. This is
most useful in cases where a test needs to use task logic for
logic unique to the tes... |
16,016 | def pyquil_to_tk(prog: Program) -> Circuit:
reg_name = None
qubits = prog.get_qubits()
n_qubits = max(qubits) + 1
tkc = Circuit(n_qubits)
for i in prog.instructions:
if isinstance(i, Gate):
name = i.name
try:
optype = _known_quil_gate[name]
... | Convert a :py:class:`pyquil.Program` to a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` .
Note that not all pyQuil operations are currently supported by pytket.
:param prog: A circuit to be converted
:return: The converted circuit |
16,017 | def disconnect_node(node, target_obj_result, graph, debug):
branch_kind = graph.adj[node][target_obj_result][].kind
branch_type = graph.adj[node][target_obj_result][].type
branch_ring = graph.adj[node][target_obj_result][].ring
graph.remove_edge(node, target_obj_result)
if isinstance(ta... | Disconnects `node` from `target_obj`
Args
----
node: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
target_obj_result: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
graph: :networkx:`NetworkX Grap... |
16,018 | def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
self.response.card.type =
self.response.card.title = title
self.response.card.text = text
if smallImageUrl:
self.response.card.image.smallImageUrl = smallImag... | Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. Content of Standard type card.
smallImageUrl: str. URL of small image. Cannot exceed 2,000
... |
16,019 | def posthoc_mackwolfe(a, val_col, group_col, p=None, n_perm=100, sort=False, p_adjust=None):
aabb
x = __convert_to_df(a, val_col, group_col)
if not sort:
x[group_col] = Categorical(x[group_col], categories=x[group_col].unique(), ordered=True)
x.sort_values(by=[group_col], ascending=True, inpl... | Mack-Wolfe Test for Umbrella Alternatives.
In dose-finding studies one may assume an increasing treatment effect with
increasing dose level. However, the test subject may actually succumb to
toxic effects at high doses, which leads to decresing treatment
effects [1]_, [2]_.
The scope of the Mack-W... |
16,020 | def _read_dataset_metadata(self):
blob = self.storage_client.get_blob(
+ self.dataset_name + )
buf = BytesIO()
blob.download_to_file(buf)
buf.seek(0)
return eval_lib.DatasetMetadata(buf) | Reads dataset metadata.
Returns:
instance of DatasetMetadata |
16,021 | def _create_key_manager(self, get_match_fuzzy, set_match_fuzzy,
get_enable_vi_bindings, set_enable_vi_bindings,
get_show_completion_columns,
set_show_completion_columns,
get_show_help, set_show_help,
... | Create and initialize the keybinding manager.
:type get_fuzzy_match: callable
:param get_fuzzy_match: Gets the fuzzy matching config.
:type set_fuzzy_match: callable
:param set_fuzzy_match: Sets the fuzzy matching config.
:type get_enable_vi_bindings: callable
:param g... |
16,022 | def install_config_kibana(self):
if self.prompt_check("Download and install kibana"):
self.kibana_install()
if self.prompt_check("Configure and autostart kibana"):
self.kibana_config() | install and config kibana
:return: |
16,023 | def sudoku(G):
global N, N2, N4
if len(G) == 16:
N, N2, N4 = 4, 16, 256
e = 4 * N4
universe = e + 1
S = [[rc(a), rv(a), cv(a), bv(a)] for a in range(N4 * N2)]
A = [e]
for r in range(N2):
for c in range(N2):
if G[r][c] != 0:
a = a... | Solving Sudoku
:param G: integer matrix with 0 at empty cells
:returns bool: True if grid could be solved
:modifies: G will contain the solution
:complexity: huge, but linear for usual published 9x9 grids |
16,024 | def result(self):
if not self.is_done():
raise ValueError("Cannot get a result for a program that isnstatusCANCELLEDresultstatusERRORQVMresultQPUresultQUILCresultresultprogramtypewavefunctionresultprogramaddressesprogramtypemultishotmultishot-measureexpectationresultresult'] | The result of the job if available
throws ValueError is result is not available yet
throws ApiError if server returned an error indicating program execution was not successful
or if the job was cancelled |
16,025 | def skip(self, regex):
return self.scan_full(regex, return_string=False, advance_pointer=True) | Like :meth:`scan`, but return the number of characters matched.
>>> s = Scanner("test string")
>>> s.skip('test ')
5 |
16,026 | def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ):
from .readwrite.write import write_csvs
write_csvs(dirname, self, skip_data=skip_data, sep=sep) | Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
----------
dirname
Name of directory to which to export.
skip_data
... |
16,027 | def detx(self, det_id, t0set=None, calibration=None):
url = .format(det_id)
detx = self._get_content(url)
return detx | Retrieve the detector file for given detector id
If t0set is given, append the calibration data. |
16,028 | def flag(self, key, env=None):
env = env or self.ENVVAR_PREFIX_FOR_DYNACONF or "DYNACONF"
with self.using_env(env):
value = self.get_fresh(key)
return value is True or value in true_values | Feature flagging system
write flags to redis
$ dynaconf write redis -s DASHBOARD=1 -e premiumuser
meaning: Any premium user has DASHBOARD feature enabled
In your program do::
# premium user has access to dashboard?
>>> if settings.flag('dashboard', 'premiumuser'... |
16,029 | def __create_dir_property(self, dir_name, docstring):
property_name = "{}_dir".format(dir_name)
private_name = "_" + property_name
setattr(self, private_name, None)
def fget(self):
return getattr(self, private_name)
def fset(self, path):
verify_... | Generate getter and setter for a directory property. |
16,030 | def get_resource_search_session_for_bin(self, bin_id):
if not self.supports_resource_search():
raise errors.Unimplemented()
return sessions.ResourceSearchSession(bin_id, runtime=self._runtime) | Gets a resource search session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
return: (osid.resource.ResourceSearchSession) - ``a
ResourceSearchSession``
raise: NotFound - ``bin_id`` not found
raise: NullArgument - ``bin_id`` is ``null``
... |
16,031 | def select_inputs(self, address: str, amount: int) -> dict:
s to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO
utxos = []
utxo_sum = Decimal(0)
for tx in sorted(self.list... | finds apropriate utxo's to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO's |
16,032 | def lookup_users(self, user_ids=None, screen_names=None, include_entities=None, tweet_mode=None):
post_data = {}
if include_entities is not None:
include_entities = if include_entities else
post_data[] = include_entities
if user_ids:
post_data[] = l... | Perform bulk look up of users from user ID or screen_name |
16,033 | def register(self, name, obj):
if name in self.all:
log.debug(, name, obj.name)
raise DuplicateDefinitionException(
% (name, obj.name))
log.debug(, name)
self.all[name] = obj
return obj | Registers an unique type description |
16,034 | def replace_cluster_role(self, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.replace_cluster_role_with_http_info(name, body, **kwargs)
else:
(data) = self.replace_cluster_role_with_http_info(name, body, **kwargs)
return data | replace the specified ClusterRole
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_cluster_role(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:... |
16,035 | def create(
name,
attributes=None,
region=None,
key=None,
keyid=None,
profile=None,
):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if attributes is None:
attributes = {}
attributes = _preprocess_attributes(attributes)
try:
conn.cr... | Create an SQS queue.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.create myqueue region=us-east-1 |
16,036 | def run(self, *, delay=None):
self.broker.enqueue(self.messages[0], delay=delay)
return self | Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself. |
16,037 | def find_max_label_length(labels):
length = 0
for i in range(len(labels)):
if len(labels[i]) > length:
length = len(labels[i])
return length | Return the maximum length for the labels. |
16,038 | def index_of_reports(self, report, account_id):
path = {}
data = {}
params = {}
path["account_id"] = account_id
path["report"] = report
self.logger.debug("GET /api/v1/accounts/{account_id}/reports/{report} with q... | Index of Reports.
Shows all reports that have been run for the account of a specific type. |
16,039 | def __get_translation(self, surah, ayah, lang):
url = .format(
base=self.BASE_API, lang=lang, surah=int(surah)
)
try:
response = urlopen(url)
data = json.loads(response.read().decode())
translation =... | Perform http request to get translation from given surah, ayah and
language.
Parameter:
:surah -- Surah index from API pages.
:ayat -- Ayat key.
:lang -- Language code.
Return:
:string -- Translation from given surah and ... |
16,040 | def convertPixelXYToLngLat(self, pixelX, pixelY, level):
mapSize = self.getMapDimensionsByZoomLevel(level)
x = (self.clipValue(pixelX, 0, mapSize - 1) / mapSize) - 0.5
y = 0.5 - (self.clipValue(pixelY, 0, mapSize - 1) / mapSize)
lat = 90 - 360 * math.atan(math.exp(-y * 2 * math... | converts a pixel x, y to a latitude and longitude. |
16,041 | def onRefreshPluginData(self, plugin_name, data):
logger.info(u"onRefreshPluginData: {}".format(plugin_name))
if not plugin_name:
logger.error("Missing plugin name")
return
reactor.callFromThread(self._sendJSON, {
: "plugin_data_get",
: pl... | Frontend requests a data refresh
:param plugin_name: Name of plugin that changed
:type plugin_name: str
:param data: Additional data
:type data: None
:rtype: None |
16,042 | def roundness(im):
perimeter = im.shape[0]*2 +im.shape[1]*2 -4
area = im.size
return 4*np.pi*area/perimeter**2 | from astropy.io import fits as pyfits
data=pyfits.getdata('j94f05bgq_flt.fits',ext=1)
star0=data[403:412,423:432]
star=data[396:432,3522:3558]
In [53]: findobj.roundness(star0)
Out[53]: 0.99401955054989544
In [54]: findobj.roundness(star)
Out[54]: 0.83091919980660645 |
16,043 | def _namify_arguments(mapping):
result = []
for name, parameter in mapping.iteritems():
parameter.name = name
result.append(parameter)
return result | Ensure that a mapping of names to parameters has the parameters set to the
correct name. |
16,044 | def copy_path_to_clipboard(i):
import os
p=os.getcwd()
if i.get(,)==:
p=+p+
rx=copy_to_clipboard({:p})
return {:0} | Input: {
(add_quotes) - if 'yes', add quotes
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
} |
16,045 | def has_delete_permission(self, request, obj=None):
if settings.TREE_EDITOR_OBJECT_PERMISSIONS:
opts = self.opts
r = request.user.has_perm(opts.app_label + + opts.get_delete_permission(), obj)
else:
r = True
return r and super(TreeEditor, self).has_... | Implement a lookup for object level permissions. Basically the same as
ModelAdmin.has_delete_permission, but also passes the obj parameter in. |
16,046 | def get_graphviz_dirtree(self, engine="automatic", **kwargs):
if engine == "automatic":
engine = "fdp"
return Dirviz(self.workdir).get_cluster_graph(engine=engine, **kwargs) | Generate directory graph in the DOT language. The graph show the files and directories
in the node workdir.
Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph> |
16,047 | def list_vm_images_sub(access_token, subscription_id):
endpoint = .join([get_rm_endpoint(),
, subscription_id,
,
, COMP_API])
return do_get_next(endpoint, access_token) | List VM images in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM images. |
16,048 | def build_and_start(query, directory):
Async(target=grep, args=[query, directory]).start() | This function will create and then start a new Async task with the
default callbacks argument defined in the decorator. |
16,049 | def _get_pos(self):
if self._canvas.height >= self._max_height:
return 0
else:
return self._canvas.start_line / (self._max_height - self._canvas.height + 1) | Get current position for scroll bar. |
16,050 | def proto_01_13_steps025dual(abf=exampleABF):
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in [,]:
swhlab.ap.plot_values(abf,feature,continuous=False)
swhlab.plot.save(abf,tag=+feature)
f1=swhlab.ap.getAvgBySweep(abf,,None,1)
f2=swhlab.ap.getAvgBySweep(a... | IC steps. See how hyperpol. step affects things. |
16,051 | def discard_between(
self,
min_rank=None,
max_rank=None,
min_score=None,
max_score=None,
):
no_ranks = (min_rank is None) and (max_rank is None)
no_scores = (min_score is None) and (max_score is None)
if no_ranks and no_scores:
... | Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If no bounds are specified, no members will be removed. |
16,052 | def handle_register_or_upload(post_data, files, user, repository):
name = post_data.get()
version = post_data.get()
if settings.LOCALSHOP_VERSIONING_TYPE:
scheme = get_versio_versioning_scheme(settings.LOCALSHOP_VERSIONING_TYPE)
try:
Version(version, scheme=scheme)
... | Process a `register` or `upload` comment issued via distutils.
This method is called with the authenticated user. |
16,053 | def _hexify(data, chunksize=None):
if chunksize is None:
chunksize = _hex_chunksize
hex = data.encode()
l = len(hex)
if l > chunksize:
chunks = []
i = 0
while i < l:
chunks.append(hex[i : i + chunksize])
i += chunksize
hex = .join(chu... | Convert a binary string into its hex encoding, broken up into chunks
of I{chunksize} characters separated by a space.
@param data: the binary string
@type data: string
@param chunksize: the chunk size. Default is L{dns.rdata._hex_chunksize}
@rtype: string |
16,054 | def _update_scsi_devices(scsis_old_new, current_disks):
device_config_specs = []
if scsis_old_new:
devs = [scsi[][] for scsi in scsis_old_new]
log.trace(, devs)
for item in scsis_old_new:
next_scsi = item[]
current_scsi = item[]
difference = recur... | Returns a list of vim.vm.device.VirtualDeviceSpec specifying the scsi
properties as input the old and new configs are defined in a dictionary.
scsi_diffs
List of old and new scsi properties |
16,055 | def _get_subcats(self, recurse=False):
if recurse:
return sorted([Category(e) for e in self._subcats_recursive],
key=lambda c: c.sort_breadcrumb)
parts = len(self.path.split()) + 1 if self.path else 1
... | Get the subcategories of this category
recurse -- whether to include their subcategories as well |
16,056 | def reindex_model_on_save(sender, document, **kwargs):
if current_app.config.get():
reindex.delay(document) | (Re/Un)Index Mongo document on post_save |
16,057 | def dataframe_to_smp(dataframe,smp_filename,name_col="name",
datetime_col="datetime",value_col="value",
datetime_format="dd/mm/yyyy",
value_format="{0:15.6E}",
max_name_len=12):
formatters = {"name":lambda x:"{0:<20s}".format(s... | write a dataframe as an smp file
Parameters
----------
dataframe : pandas.DataFrame
smp_filename : str
smp file to write
name_col: str
the column in the dataframe the marks the site namne
datetime_col: str
the column in the dataframe that is a datetime instance
value... |
16,058 | def copyKeyMultipart(srcBucketName, srcKeyName, srcKeyVersion, dstBucketName, dstKeyName, sseAlgorithm=None, sseKey=None,
copySourceSseAlgorithm=None, copySourceSseKey=None):
s3 = boto3.resource()
dstBucket = s3.Bucket(oldstr(dstBucketName))
dstObject = dstBucket.Object(oldstr(dstK... | Copies a key from a source key to a destination key in multiple parts. Note that if the
destination key exists it will be overwritten implicitly, and if it does not exist a new
key will be created. If the destination bucket does not exist an error will be raised.
:param str srcBucketName: The name of the b... |
16,059 | def _set_tieBreaking(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: {: 2}, u: {: 0}, u: {:... | Setter method for tieBreaking, mapped from YANG variable /brocade_mpls_rpc/show_mpls_te_path/input/tieBreaking (tie-breaking)
If this variable is read-only (config: false) in the
source YANG file, then _set_tieBreaking is considered as a private
method. Backends looking to populate this variable should
... |
16,060 | def fit(self, Xs=None, ys=None, Xt=None, yt=None):
if check_params(Xs=Xs, Xt=Xt):
self.cost_ = dist(Xs, Xt, metric=self.metric)
self.cost_ = cost_normalization(self.cost_, self.norm)
if (ys is not None) and (yt is not None):
... | Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The class labels
... |
16,061 | def process_json(filename):
logger.debug(, filename)
doecode_json = json.load(open(filename))
for record in doecode_json[]:
yield record | Converts a DOE CODE .json file into DOE CODE projects
Yields DOE CODE records from a DOE CODE .json file |
16,062 | def verify(password_hash, password):
ensure(len(password_hash) == PWHASH_SIZE,
"The password hash must be exactly %s bytes long" %
nacl.bindings.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
raising=exc.ValueError)
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_st... | Takes the output of scryptsalsa208sha256 and compares it against
a user provided password to see if they are the same
:param password_hash: bytes
:param password: bytes
:rtype: boolean
.. versionadded:: 1.2 |
16,063 | def ogr2ogr(src, dst, options):
out = gdal.VectorTranslate(dst, src, options=gdal.VectorTranslateOptions(**options))
out = None | a simple wrapper for gdal.VectorTranslate aka `ogr2ogr <https://www.gdal.org/ogr2ogr.html>`_
Parameters
----------
src: str or :osgeo:class:`ogr.DataSource`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.VectorTranslate;
... |
16,064 | def create_waveform_generator(variable_params, data,
recalibration=None, gates=None,
**static_params):
try:
approximant = static_params[]
except KeyError:
raise ValueError("no approximant provided in the static args")
gene... | Creates a waveform generator for use with a model.
Parameters
----------
variable_params : list of str
The names of the parameters varied.
data : dict
Dictionary mapping detector names to either a
:py:class:`<pycbc.types.TimeSeries TimeSeries>` or
:py:class:`<pycbc.types... |
16,065 | def network_profile_name_list(self, obj):
profile_list = pointer(WLAN_PROFILE_INFO_LIST())
self._wlan_get_profile_list(self._handle,
byref(obj[]),
byref(profile_list))
profiles = cast(profile_list.contents.ProfileI... | Get AP profile names. |
16,066 | def _all_recall_native_type(self, data, ptitem, prefix):
typestr = self._all_get_from_attrs(ptitem, prefix + HDF5StorageService.SCALAR_TYPE)
colltype = self._all_get_from_attrs(ptitem, prefix + HDF5StorageService.COLL_TYPE)
type_changed = False
if colltype == HDF5Stora... | Checks if loaded data has the type it was stored in. If not converts it.
:param data: Data item to be checked and converted
:param ptitem: HDf5 Node or Leaf from where data was loaded
:param prefix: Prefix for recalling the data type from the hdf5 node attributes
:return:
... |
16,067 | def DictReader(ltsvfile, labels=None, dict_type=dict):
for rec in reader(ltsvfile, labels):
yield dict_type(rec) | Make LTSV Reader for reading selected labels.
:param ltsvfile: iterable of lines.
:param labels: sequence of labels.
:return: generator of record in {label: value, ...} form. |
16,068 | def get_feature_variable_boolean(self, feature_key, variable_key, user_id, attributes=None):
variable_type = entities.Variable.Type.BOOLEAN
return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes) | Returns value for a certain boolean variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
... |
16,069 | def __try_parse_number(self, string):
try:
return int(string)
except ValueError:
try:
return float(string)
except ValueError:
return False | Try to parse a string to a number, else return False. |
16,070 | def block_compute(x_start, x_stop,
y_start, y_stop,
z_start, z_stop,
origin=(0, 0, 0),
block_size=(512, 512, 16)):
x_bounds = range(origin[0], x_stop + block_size[0], block_size[0])
x_bounds = [x for x in x_bounds if (x > x_start ... | Get bounding box coordinates (in 3D) of small cutouts to request in
order to reconstitute a larger cutout.
Arguments:
x_start (int): The lower bound of dimension x
x_stop (int): The upper bound of dimension x
y_start (int): The lower bound of dimension y
y_stop (int): The upper ... |
16,071 | def d3logpdf_dlink3(self, link_f, y, Y_metadata=None):
N = y.shape[0]
D = link_f.shape[1]
d3logpdf_dlink3 = np.zeros((N,D))
return d3logpdf_dlink3 | Third order derivative log-likelihood function at y given link(f) w.r.t link(f)
.. math::
\\frac{d^{3} \\ln p(y_{i}|\\lambda(f_{i}))}{d^{3}\\lambda(f)} = 0
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:par... |
16,072 | def loc(lexer: Lexer, start_token: Token) -> Optional[Location]:
if not lexer.no_location:
end_token = lexer.last_token
source = lexer.source
return Location(
start_token.start, end_token.end, start_token, end_token, source
)
return None | Return a location object.
Used to identify the place in the source that created a given parsed object. |
16,073 | def union(self, sig: Scope) -> Scope:
new = Scope(sig=self._hsig.values(), state=self.state)
new |= sig
return new | Create a new Set produce by the union of 2 Set |
16,074 | def filer(filelist):
filedict = dict()
for seqfile in filelist:
strainname = os.path.splitext(os.path.basename(seqfile))[0]
filedict[strainname] = seqfile
return filedict | Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension |
16,075 | def initialize_tracer(self, io_loop=None):
with Config._initialized_lock:
if Config._initialized:
logger.warn()
return
Config._initialized = True
tracer = self.new_tracer(io_loop)
self._initialize_global_tracer(tracer=tracer)
... | Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect. |
16,076 | def runDia(diagram):
ifname = .format(diagram)
ofname = .format(diagram)
cmd = .format(ofname, ifname)
print(.format(cmd))
subprocess.call(cmd, shell=True)
return True | Generate the diagrams using Dia. |
16,077 | def edit(self, obj_id, parameters, create_if_not_exists=False):
if create_if_not_exists:
response = self._client.session.put(
.format(
url=self.endpoint_url, id=obj_id
),
data=parameters
)
else:
... | Edit an item with option to create if it doesn't exist
:param obj_id: int
:param create_if_not_exists: bool
:param parameters: dict
:return: dict|str |
16,078 | def ns(self):
ret = libxml2mod.xmlNodeGetNs(self._o)
if ret is None:return None
__tmp = xmlNs(_obj=ret)
return __tmp | Get the namespace of a node |
16,079 | def minOpar(self,dangle,tdisrupt=None,_return_raw=False):
if tdisrupt is None: tdisrupt= self._tdisrupt
Oparb= (dangle-self._kick_interpdOpar_poly.x[:-1])/self._timpact
lowx= ((Oparb-self._kick_interpdOpar_poly.c[-1])\
*(tdisrupt-self._timpact)+Oparb... | NAME:
minOpar
PURPOSE:
return the approximate minimum parallel frequency at a given angle
INPUT:
dangle - parallel angle
OUTPUT:
minimum frequency that gets to this parallel angle
HISTORY:
2015-12-28 - Written - Bovy (UofT) |
16,080 | def request(self, method, url, erc, **kwargs):
abs_url = self.abs_url(url)
kwargs.setdefault(, self.single_request_timeout)
while True:
response = self._req_session.request(method, abs_url, **kwargs)
try:
... | Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Teams rate-limiting
* Inspects response codes an... |
16,081 | def compose(*funcs):
if len(funcs) == 2: f0,f1=funcs; return lambda *a,**kw: f0(f1(*a,**kw))
elif len(funcs) == 3: f0,f1,f2=funcs; return lambda *a,**kw: f0(f1(f2(*a,**kw)))
elif len(funcs) == 0: return lambda x:x
elif len(funcs) == 1: return funcs[0]
else:
def composed(*args,... | Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2] |
16,082 | def _finalize(self):
container = {}
try:
for name in self._traces:
container[name] = self._traces[name]._trace
container[] = self._state_
file = open(self.filename, )
std_pickle.dump(container, file)
file.close()
... | Dump traces using cPickle. |
16,083 | def generate(ast_tree: ast.Tree, model_name: str):
component_ref = ast.ComponentRef.from_string(model_name)
ast_tree_new = copy.deepcopy(ast_tree)
ast_walker = TreeWalker()
flat_tree = flatten(ast_tree_new, component_ref)
sympy_gen = SympyGenerator()
ast_walker.walk(sympy_gen, flat_tree)
... | :param ast_tree: AST to generate from
:param model_name: class to generate
:return: sympy source code for model |
16,084 | def pop_object(self, element):
redacted_text = "Redacted. Object contained TLP value higher than allowed."
element[] =
element[] =
element[] =
element[] = []
element[] = None
element[] = redacted_text
element[] = element[]
element[] =... | Pop the object element if the object contains an higher TLP then allowed. |
16,085 | async def find_deleted(self, seq_set: SequenceSet,
selected: SelectedMailbox) -> Sequence[int]:
session_flags = selected.session_flags
return [msg.uid async for _, msg in self.find(seq_set, selected)
if Deleted in msg.get_flags(session_flags)] | Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mailbox session. |
16,086 | def summary(self):
if self.hasSummary:
return GeneralizedLinearRegressionTrainingSummary(
super(GeneralizedLinearRegressionModel, self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__c... | Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`. |
16,087 | def load_commodities(self):
if isinstance(self.fee, Amount):
self.fee = Amount("{0:.8f} {1}".format(self.fee.to_double(), self.currency))
else:
self.fee = Amount("{0:.8f} {1}".format(self.fee, self.currency))
if isinstance(self.amount, Amount):
self.a... | Load the commodities for Amounts in this object. |
16,088 | def messageRemote(self, cmdObj, consequence=None, **args):
messageBox = cmdObj.makeArguments(args, self)
messageBox[COMMAND] = cmdObj.commandName
messageData = messageBox.serialize()
self.queue.queueMessage(self.sender, self.target,
Value(AMP_MESS... | Send a message to the peer identified by the target, via the
given L{Command} object and arguments.
@param cmdObj: a L{twisted.protocols.amp.Command}, whose serialized
form will be the message.
@param consequence: an L{IDeliveryConsequence} provider which will
handle the result... |
16,089 | def get_compression_filter(byte_counts):
assert isinstance(byte_counts, numbers.Integral) and byte_counts > 0
if 2 * byte_counts > 1000 * memory()[]:
try:
FILTERS = tables.filters(complevel = 5, complib = ,
shuffle = True, least_significant_di... | Determine whether or not to use a compression on the array stored in
a hierarchical data format, and which compression library to use to that purpose.
Compression reduces the HDF5 file size and also helps improving I/O efficiency
for large datasets.
Parameters
----------
byte_co... |
16,090 | def to_filespec(cls, args, root=, exclude=None):
result = {: [os.path.join(root, arg) for arg in args]}
if exclude:
result[] = []
for exclude in exclude:
if hasattr(exclude, ):
result[].append(exclude.filespec)
else:
result[].append({: [os.path.join(root, x) ... | Return a dict representation of this glob list, relative to the buildroot.
The format of the dict is {'globs': [ 'list', 'of' , 'strings' ]
(optional) 'exclude' : [{'globs' : ... }, ...] }
The globs are in zglobs format. |
16,091 | def split_iter(src, sep=None, maxsplit=None):
if not is_iterable(src):
raise TypeError()
if maxsplit is not None:
maxsplit = int(maxsplit)
if maxsplit == 0:
yield [src]
return
if callable(sep):
sep_func = sep
elif not is_scalar(sep):
... | Splits an iterable based on a separator, *sep*, a max of
*maxsplit* times (no max by default). *sep* can be:
* a single value
* an iterable of separators
* a single-argument callable that returns True when a separator is
encountered
``split_iter()`` yields lists of non-separator valu... |
16,092 | def _try_redeem_disposable_app(file, client):
redeemedClient = client.redeem_onetime_code(None)
if redeemedClient is None:
return None
else:
return _BlotreDisposableApp(file,
redeemedClient.client,
creds = redeemedClient.creds,
config = redeemedClient... | Attempt to redeem a one time code registred on the client. |
16,093 | def daily_pr_intensity(pr, thresh=, freq=):
r
t = utils.convert_units_to(thresh, pr, )
pr_wd = xr.where(pr >= t, pr, 0)
pr_wd.attrs[] = pr.units
s = pr_wd.resample(time=freq).sum(dim=, keep_attrs=True)
sd = utils.pint_multiply(s, 1 * units.day, )
wd = wetdays(pr, thresh=thr... | r"""Average daily precipitation intensity
Return the average precipitation over wet days.
Parameters
----------
pr : xarray.DataArray
Daily precipitation [mm/d or kg/m²/s]
thresh : str
precipitation value over which a day is considered wet. Default : '1 mm/day'
freq : str, optional... |
16,094 | def path_exists(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError( % value)
elif not value:
return None
value = path(value, force_run = True)
if not os.path.e... | Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyVal... |
16,095 | async def _init_writer(self):
async with self._initialization_lock:
if not self.initialized:
self.stream = await aiofiles.open(
file=self.absolute_file_path,
mode=self.mode,
encoding=self.encoding,
... | Open the current base file with the (original) mode and encoding.
Return the resulting stream. |
16,096 | def aligned_covariance(fit, type=):
cov = fit._covariance_matrix(type)
cov /= N.linalg.norm(cov)
return dot(fit.axes,cov) | Covariance rescaled so that eigenvectors sum to 1
and rotated into data coordinates from PCA space |
16,097 | def getRemoteObject(self, busName, objectPath, interfaces=None,
replaceKnownInterfaces=False):
weak_id = (busName, objectPath, interfaces)
need_introspection = False
required_interfaces = set()
if interfaces is not None:
ifl = []
... | Creates a L{RemoteDBusObject} instance to represent the
specified DBus object. If explicit interfaces are not
supplied, DBus object introspection will be used to obtain
them automatically.
@type busName: C{string}
@param busName: Name of the bus exporting the desired object
... |
16,098 | def generate_readme(catalog, export_path=None):
if isinstance(catalog, string_types):
catalog_path_or_url = catalog
else:
catalog_path_or_url = None
catalog = read_catalog(catalog)
validation = validate_catalog(catalog)
indicators = generate_catalogs_indicators(
... | Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
- cantidad de datasets federados y no federados,
... |
16,099 | def identity_factor(self):
return DiscreteFactor(self.variables, self.cardinality, np.ones(self.values.size)) | Returns the identity factor.
Def: The identity factor of a factor has the same scope and cardinality as the original factor,
but the values for all the assignments is 1. When the identity factor is multiplied with
the factor it returns the factor itself.
Returns
-----... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.