content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_tif(file=None):
"""Read tiff files. Works with 16 bit rgb data"""
if file is not None:
img = tif.imread(file)
return img
else:
print("No file provided") | 4fecf1f9009316157fdbe268d63ea3f9bb0964db | 50,784 |
def verify_predictions(predictions):
"""Ensures that predictions is stored as a numpy array and checks that
all values are either 0 or 1.
"""
# Check that it contains only zeros and ones
predictions = np.array(predictions, copy=False)
if not np.array_equal(predictions, predictions.astype(bool)):... | a139cbd5574c81fbe10556bec50e01e6404de884 | 50,785 |
def merge_bbox(left: Box, right: Box) -> Box:
"""
Merge bounding boxes in format (xmin, xmax, ymin, ymax)
"""
return tuple([
f(l, r) for l, r, f in zip(left, right, [min, max, min, max])
]) | 54918e88be43a6fe4cb5218944185105fd9da68f | 50,786 |
def sumRowDotProdsNEW(origMatrix):
"""
Makes more sense to use on Jacobian than on Hessian.
"""
rowNormalized = normRows(origMatrix)
n = rowNormalized.shape[0]
sumDotProds = sumAllDotProds(rowNormalized[0:n/2]) + sumAllDotProds(rowNormalized[n/2:n])
return sumDotProds | c15346cedffa3486bb3a3513de62bb337553c7dc | 50,787 |
import io
def img_from_fig() -> Image.Image:
"""
Convert a Matplotlib figure to a PIL Image and return it.
The figure is pulled from the current pyplot context, therefore the figure
must be created and then drawn before calling this function.
Returns:
PIL Image array.
"""
buf = i... | df88a688d632a26ed905f272fad30eb6afc2113e | 50,788 |
from django.contrib.auth import get_user_model
def get_subscriber_model():
"""
Users have the option of specifying a custom subscriber model via the
DJSTRIPE_SUBSCRIBER_MODEL setting.
This method attempts to pull that model from settings, and falls back to
AUTH_USER_MODEL if DJSTRIPE_SUBSCRIBER_M... | f2931195f65c68a56f6b3fd826589119baa95702 | 50,789 |
def get_mnist():
""" Returns tuple containing the concatenated train and test_images, train and test_labels, the image size,
and the test length for the MNIST dataset.
"""
#pull data
(train_images, train_labels), (test_images, test_labels) = tf.contrib.keras.datasets.mnist.load_data('datasets')
... | 48c4b8d7eb700309e87bf8a1c680d80759c01636 | 50,790 |
def PreOpL(op, items):
"""
Uses algorithm from SecureSCM WP9 deliverable.
op must be a binary function that outputs a new register
"""
k = len(items)
logk = int(ceil(log(k,2)))
kmax = 2**logk
output = list(items)
for i in range(logk):
for j in range(kmax//(2**(i+1))):
... | b6f9be5612e06c7d3da5988ad89e25d8ee3bdb18 | 50,791 |
def generaGraph (pcapfile, macgraph, ipgraph, pathresults = 'results'):
"""
Genera graphs for connections between IPs and MAC addresses. This function also can be used to read the MACs and
IPs in the .pcap or .pcapng file.
:param pcapfile: path to the .pcap or .pcapng file
:param pathresulst: path t... | 5303fd46b7e07194673f40aa618e99bc9f2f1f8a | 50,792 |
def uploader() -> _Uploader:
"""An _Uploader object with all of its fields filled in."""
return _UploaderFactory() | ba8669f43d07a5f43792a30b0a692325b7d4f10b | 50,793 |
def existingusercheck(userdata):
"""Checks if the input username is already in the userdata file, and if user entry is in valid format.
If valid, returns username, password, and user permissions."""
for line in userdata:
if (len(line) > 1 and line.split()[0] == username):
if (len(line.split()) == 3):
re... | 101a01078926c6c4733e7420b37463cc9912193f | 50,794 |
def calc_linear_crossing(m, left_v, right_v):
"""
Computes the intersection between two line segments, defined by two common
x points, and the values of both segments at both x points
Parameters
----------
m : list or np.array, length 2
The two common x coordinates. m[0] < m[1] is assum... | 3f5eeab9fa906b6858e249f97c7e175e427cb2d7 | 50,795 |
from typing import get_args
def run_fresh_full_train_DARTS(epochs,output_path_fulltrain, cell_list = None, sep_conv_list = None):
"""
Perform model evaluation for DARTS/DARTS+
"""
GLOBALS.FIRST_INIT = False
#optimizer,scheduler=network_initialize(new_network,train_loader)
parser = ArgumentPa... | 32e49e8eb868ef42a007565a675fe433515fadbd | 50,796 |
def get_program_no_movement(blending):
"""Test program with two joint steps no movement in between"""
j1 = [58, -70, 107, 64, -60, 43]
steps = [
# Step: name, move_type, tcp, pose, blending, speed, accel):
Step("1", MoveType.Joint, 0, j1, blending, 0, 0),
Step("2", MoveType.Joint, 0,... | 1ae24d1683cc737a1bd2791cc51202d3a63a848f | 50,797 |
def validate_input(input_string):
"""
:param str input_string: A string input to the program for validation
that it will work wiht the diamond_challenge program.
:return: *True* if the string can be used to create a diamond.
*False* if cannot be used.
"""
if not isinstance(input_string, st... | cf18344ddd336d878837bc5654a3ea3b98eec729 | 50,798 |
def get_public_roles():
"""Roles which make a collection to be considered public."""
return [
Role.load_id(Role.SYSTEM_GUEST),
Role.load_id(Role.SYSTEM_USER),
] | 5bf1a761c68bf7c6ab904241da854882b3940d5f | 50,800 |
def data_missing():
"""Length-2 array with [NA, Valid]"""
variant = Variant(
chromosome="chr1", position=123456, id="rs12345", ref="A", alt=["T", "G"]
)
genotypes = [variant.make_genotype(), variant.make_genotype("T", "T")]
return GenotypeArray(values=genotypes) | 8123ecda0b73066125b2d716d38fa45dadb68355 | 50,802 |
from pyspark.sql import functions as F
from pyspark.sql import DataFrame
from functools import reduce
def append(dfs, like="columns"):
"""
Concat multiple dataFrames columns or rows wise
:param dfs: List of DataFrames
:param like: concat as columns or rows
:return:
"""
# FIX: Because mono... | 75a28b7ba94838f1f2c8e8bd41f387a5905c8e71 | 50,803 |
from typing import Optional
def event_to_show(
event: Event,
session: Depends(get_db),
user: Optional[User] = None,
) -> Optional[Event]:
"""Check the given event's privacy and return
event/fixed private event/ nothing (hidden) accordingly"""
is_owner = check_event_owner(event, session, user)
... | c502760e1ff1fdc786c30feedb0a6ba99f2b421e | 50,804 |
def reduce_group_ndims(operation, tensor, group_ndims, name=None):
"""
Reduce the last `group_ndims` dimensions in `tensor`, using `operation`.
In :class:`~tfsnippet.distributions.Distribution`, when computing the
(log-)densities of certain `tensor`, the last few dimensions
may represent a group of... | d94c5aec353bfde8cc4df56c67eca3be6d7efc41 | 50,807 |
def items_id(collection_id, item_id, roles=None):
"""Retrieve a given feature from a given feature collection.
:param collection_id: identifier (name) of a specific collection
:param item_id: identifier (name) of a specific item
"""
item = get_collection_items(collection_id=collection_id, roles=rol... | d5c0d80bced6941c983631d98a49530612f9618c | 50,808 |
def Bi_RNN(vocab_size, embedding_matrix,ckpt_path,max_len,embedding_size):
"""
bi-RNN + GRU
:param vocab_size:
:param embedding_matrix:
:param ckpt_path:
:param max_len:
:param embedding_size:
:return:
"""
model = Sequential()
model.add(Embedding(len(vocab_size),embedding_size,input_length=max_len))
model.a... | 7343db59b3b1accaddbcd718f6880725c4ce7dc4 | 50,809 |
import torch
def sample_patch_multiscale(im, pos, scales, image_sz, mode: str='replicate', max_scale_change=None):
"""Extract image patches at multiple scales.
args:
im: Image.
pos: Center position for extraction.
scales: Image scales to extract image patches from.
image_sz: Si... | 1094ca452b78dbcd77bf481a4055a751481c303c | 50,810 |
def make_accumulate_client_votes_fn(round_num, discovered_prefixes_table,
possible_prefix_extensions_table):
"""Returns a reduce function that is used to accumulate client votes.
This function creates an accumulate_client_votes reduce function that can be
consumed by a tf.data... | b64d53eba57d134d78d9ad5d357b3ce5639e76df | 50,811 |
def octave_to_frequency(octave: float) -> float:
"""Converts an octave to its corresponding frequency value (in Hz).
By convention, the 0th octave is 125Hz.
Parameters
----------
octave : float
The octave to put on a frequency scale.
Returns
-------
float
The frequency value c... | d50fe69e0dd267b5418834ca2999867213b5f306 | 50,812 |
import array
def clause_tensor(l, q=2, g=oror, m=0, dtype=int):
""" Return tensorization of the truth table of gate g.
Generally, g is a l-ary relation in the constraint
language of a (weighted) CSP and this function
returns a tensor representation of the relation g. """
d = [q] * l
... | ce6804b478bc0a380a957f2a26c912edfb56e65d | 50,813 |
def predictions_wavfile(data, model_type):
"""
Takes the embeddings of wav file and runs the predictions on it
"""
# call the model and load the weights
model = create_keras_model()
if model_type == "Motor":
model.load_weights("../predictions/binary_relevance_model/Binary_Relevance_Mode... | 0f714454def30ed2883b1da184148391a1c52f83 | 50,814 |
import re
def _trim_endpoint_api_version(url):
"""Trim API version and trailing slash from endpoint."""
return re.sub(_API_VERSION_RE, '', url) | 207fb5f46c52d92a1cf40c969ad80f2c9891349c | 50,815 |
def get_mmp(option, maps=None, out_put=None, target_id=None, extra=None):
"""Function to find the MMP comparison
Takes a pk of the MMP comparison
Returns the SD block of that data"""
mmp = MMPComparison.objects.get(pk=option)
return mmp.sdf_info | 7c0bcb9c2d6b63e508ba411333fb8e7dfb75218e | 50,816 |
def insertion(word1, word2):
"""
Args:
word1: String, a double occurrence word.
word2: String, a double occurrence word.
Returns:
A boolean indicating whether word2 can be constructed by
inserting a repeat word or return word into word1. If it can,
then the two indi... | 3290e722eb55e4a274237fa5dca71ae4767fd003 | 50,817 |
import copy
def consolidate_trcks(x, include_end=False):
"""
Consolidates all midi.events in a midi.Pattern into a single track
"""
if isinstance(x, midi.Pattern):
old_ptrn = x
else:
old_ptrn = midi.Pattern(format=1, resolution=480, tick_relative=True,)
for trck in x:
... | ab782d691fe557ca17c1eb70520d7334102f6844 | 50,818 |
def calculate_curtailment_time_series(scenario):
"""Calculate hourly curtailment for each renewable generator.
:param powersimdata.scenario.scenario.Scenario scenario: scenario instance.
:return: (*pandas.DataFrame*) -- time series of curtailment.
"""
_check_scenario_is_in_analyze_state(scenario)
... | a8bbaca06e01f67ce4fba717cb8a5556a766aa6b | 50,819 |
def index():
"""List archived parties."""
parties = party_service.get_archived_parties_for_brand(g.brand_id)
parties = [p for p in parties if not p.canceled]
return {
'parties': parties,
} | 1231f9c7690a7570002f0a2ff27e084ac1f35111 | 50,820 |
def getMessageLength(imageArray):
"""gets the message length out of the first 8 pixels"""
length = ""
for i in range(8):
for j in range(3):
length += str(imageArray[i][j] % 2)
if doLogOutput:
print(f"Binary length: {str(length)}")
print(f"Decimal length: {str(int(len... | 97553fb1bbcbda0bcdbc4392da4b2f03594e3a74 | 50,822 |
import re
def find_orbitals_from_statelines(out_info_dict):
"""
This function reads in all the state_lines, that is, the lines describing
which atomic states, taken from the pseudopotential, are used for the
projection. Then it converts these state_lines into a set of orbitals.
:param out_info_di... | 8d3487013b33f0e9eed14b93d8958ad7e270d9d9 | 50,823 |
def EI(model, _, X, xi=0.0):
"""
Expected improvement policy with an exploration parameter of `xi`.
"""
model = model.copy()
target = model.predict(X)[0].max() + xi
def index(X, grad=False):
"""EI policy instance."""
return model.get_improvement(target, X, grad)
return inde... | 89e67b14abf6d0c2b76dc45da37281c9c7a01cf9 | 50,824 |
def scoring(es_doc):
"""Return the final scored instance as an elasticsearch-format document."""
doc = {"_source": es_doc[1],
"_id": es_doc[0],
"_index": get_index_name(),
"_type": get_type_name()
}
result = score_instance(doc)
return (es_doc[0], result["... | 9e6fb573965d6a7366b2886fc46f8281b8b0737a | 50,825 |
def TFlt_GetMegaStr(*args):
"""
TFlt_GetMegaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetMegaStr(*args) | a441ad0288fe891846028c4556d2704039296e36 | 50,826 |
def format_metrics_map(metrics_map):
"""Properly format iterable `metrics_map` to contain instances of :class:`Metric`
Parameters
----------
metrics_map: Dict, List
Iterable describing the metrics to be recorded, along with a means to compute the value of
each metric. Should be of one o... | f366411164879d692d1d1885881c3b5e1b2fe1c2 | 50,827 |
import re
def add_categories(user_id):
"""This route handles posting categories"""
if request.method == "POST":
name = str(request.data.get('name')).strip()
name = re.sub(' +',' ', name)
resultn = valid_category(name)
if resultn:
return jsonify(resultn), 400
... | 8df979871c3239b59e3e6c4972f74b15e8bdd8d7 | 50,828 |
def WV_WI(bands: dict) -> xr.DataArray:
"""
WorldView-Water (WV-WI)
Useful for detecting standing, flowing water, or shadow in VNIR imagery
WV_WI = ((B8-B1)/(B8+B1))
https://resources.maxar.com/optical-imagery/multispectral-reference-guide
Args:
bands (dict): Bands as {band_name: xr.Da... | 5db242ca23ac405d03aa5edc536dae7e6e60db3b | 50,829 |
def api_settings_gui(request):
"""Test utility."""
auth = get_auth(request)
obj = SettingsGui(auth=auth)
check_apiobj(authobj=auth, apiobj=obj)
return obj | b1f923b60f3eeb5a0a77809c9dc7cd4d41298439 | 50,830 |
import numpy
def _geometric_mean(array):
"""Calculate a geometric mean of numpy array of floats.
Returns:
float, unless array contains a ``nan``, then returns ``nan``.
"""
return numpy.prod(array)**(1./len(array)) | 46ca9ec3be68ed3a2687579b2369f082dc030429 | 50,831 |
def helicsCreateCore(type: str, name: str, init_string: str) -> HelicsCore:
"""
Create a `helics.HelicsCore`.
**Parameters**
- **`type`** - The type of the core to create.
- **`name`** - The name of the core. It can be a nullptr or empty string to have a name automatically assigned.
- **`init_... | f58cc855650752088b388309d4a3ad6794118a42 | 50,832 |
def _complete_choices(msg, choice_range, prompt, all=False, back=True):
"""Return the complete message and choice list."""
choice_list = [str(i) for i in choice_range]
if all:
choice_list += ['a']
msg += '\n- a - All of the above.'
if back:
choice_list += ['b']
msg... | 0e5052643cd027d760b08b22bc5f14608845fcb2 | 50,833 |
def is_snippet(abbr, doc_type = 'html'):
"""
Check is passed abbreviation is a snippet
@return bool
"""
return get_snippet(doc_type, abbr) and True or False | 8b04700dc7bf7bc5583a6e5971467023afc399c6 | 50,834 |
def compute_entropy(x, k=1, norm='max', min_dist=0.):
"""
Estimates the entropy H of a random variable x (in nats) based on
the kth-nearest neighbour distances between point samples.
Implementation credits: Paul Brodersen
@reference:
Kozachenko, L., & Leonenko, N. (1987). Sample estimate of the ... | f9cdbac4fb2cbbcb50d32544f7288202c4d4f372 | 50,835 |
import random
def building_data_one_per_par(collection,minlen=10,regression=False,time=False,subdir=None,save=False):
"""Builds the training and out-of-sample sets.
Parameters
----------
collection : data in class format
Returns
-------
list
x: list of Numpy data set, ... | 10b1554f3597bda86f4abace27f4f5594518d19d | 50,836 |
def create_item(item_create: ItemCreate = Body(...,
example=ItemFactory.mock_item)):
"""
create an item
"""
return item_service.create_item(item_create) | 820e7dc538d5fdbd5812bbbc8b9a85d98759966c | 50,837 |
def satellite_ref(sat):
"""
To load the band_names for referencing either LANDSAT8 or LANDSAT7 bands
"""
if sat == 'LANDSAT_8':
sat_img = bands_ls8
elif sat == 'LANDSAT_7' or sat == 'LANDSAT_5':
sat_img = bands_ls7
else:
raise ValueError('Satellite data Not Supported')
... | a4003120c24291e5ea75a5b35e98b911a3f37586 | 50,838 |
def is_bitcode_file(path):
"""
Returns True if path contains a LLVM bitcode file, False if not.
"""
with open(path, 'rb') as f:
return f.read(4) == b'BC\xc0\xde' | acfd17eee949f42994b2bc76499ee58c710eb388 | 50,839 |
def licensed(name):
"""Ensure that Crowdstrike is licensed.
.. note::
This state will ONLY license crowdstrike if it isn't licensed. This
state should NOT be used to change the license.
name:
the customer id to license the machine with.
"""
ret = {'name': name, 'result': Tr... | 0021f2d1ac13334db52e5aa16150d0c32f2e19ce | 50,840 |
def PEI_threshold(gp, u, idxU, boundsK):
"""find the minimum of the prediction for u fixed
and compares it with the current evaluated minimum.
It serves as the threshold for the PEI criterion
:param gp: GaussianProcessRegressor
:param u: value that is fixed
:param idxU: index of u
:param bo... | 076563030d29d16af6d6f3a7021141d2f6d71eae | 50,841 |
def gaussian_blur(x: np.ndarray, sigma: float, multichannel: bool = True, xrange: tuple = None) -> np.ndarray:
"""
Apply Gaussian blur.
Parameters
----------
x
Instance to be perturbed.
sigma
Standard deviation determining the strength of the blur.
multichannel
Wheth... | 8a6f3430d7068ca56cb771d673be2b9c322573cd | 50,842 |
def is_vocalized(word):
"""Checks if the arabic word is vocalized.
the word musn't have any spaces and pounctuations.
@param word: arabic unicode char
@type word: unicode
@return: if the word is vocalized
@rtype:Boolean
"""
if word.isalpha():
return False
for char in word:
... | afb57cba18ec6c1d3de23d62834439f78c311d46 | 50,843 |
from typing import Callable
def _get_and_deflate(
function: Callable,
base_year: int,
target_currency: str = None,
col: str = "value",
) -> pd.DataFrame:
"""Get data using a specific function and apply an exchange rate
and deflators if provided"""
if target_currency is None:
df = ... | e3cab928c824fa9db26958da778a5d30c4a75920 | 50,846 |
def main(args=None):
"""Console script for sentry_onboarding."""
app.run()
return 0 | cef848459f9f38d5aec1e1fd3c433e511888f446 | 50,847 |
import json
def responder():
"""
Listen to webhooks.
Returns
-------
response : flask.Response object
Response object that is used by default in Flask.
"""
response = Response(status=200)
try:
loan_data = request.get_json(force=True, silent=True)
trading.b... | 59fc385c0207541d02a4e5fb667384bd591a7a80 | 50,848 |
def equalization_line(data, key, equilibrium_point):
"""
Создание линии эквализации.
Уравнение прямой с плавающей температурой является прямой с углом наклона,
большим, чем 0 градусов. Таким образом, она выражается следующим равенством:
y_float = kx = [y(f) - y(0)] / N * x, где а - время в конце, N ... | d3834a738c790b0f0d064f52710db0f93ba3813f | 50,849 |
import torch
def pairwise_landmark_ranking_loss_step(model, data, search_space, criterion, args,
change_model_spec_fn, module_forward_fn,
rank_obj=None, pair_indicies=None):
"""
Compute the ranking loss:
for landmark model... | 28b6967a4958304795e5d199cee8ea56a90af968 | 50,850 |
def get_org_repo_owner(repo_id):
"""
Get owner of org repo.
"""
try:
owner = seafserv_threaded_rpc.get_org_repo_owner(repo_id)
except SearpcError:
owner = None
return owner | ddb5699f27a2d326d49dcfb3a24a654db1e71edf | 50,851 |
def remove_from_user_path(path: str):
"""
Remove **one** path from PATH of current user
"""
assert ';' not in path
old_paths = get_user_path()
new_paths = [i for i in old_paths if not is_same_file(i, path)]
if new_paths != old_paths:
return set_user_path(new_paths) | 192f65236bb0b205e9673b2a6970d05074115dd8 | 50,852 |
def read_one(activatorId):
"""
Responds to a request for /api/application_meta/{activatorId}
:param application: activatorId
:return: count of applications that match the acivatorId
"""
acount = Application.query.filter(Application.activatorId == activatorId).count()
data = ... | a7e47987f0e50ac33fabf17627617e9bc342213f | 50,853 |
def server_role_def(role):
"""Defines various role objects"""
server_roles = {'simple' : {'groups' : ['default', 'web'],
'ami' : 'precise64',
'role' : SimpleRole}
}
return server_roles[role] | fa5f21c90db929e2e64d5fc5e580fec494c09698 | 50,855 |
import platform
def get_session(module):
"""Return System Object or Fail"""
user_agent = '%(base)s %(class)s/%(version)s (%(platform)s)' % {
'base': USER_AGENT_BASE,
'class': __name__,
'version': VERSION,
'platform': platform.platform()
}
array_name = module.params['fa... | 3cd2233286f928c964f94aeac6025fc12504345b | 50,856 |
def read_line_values_as_array(file_path, dtype, line_no):
"""
Reads in chemical potential multipliers
"""
success = True
error = ""
values = None
if not check_file:
success = False
error = "File: %s cannot be found." % (file_path)
else:
try:
f = open(file_path)
... | d40719344212c4077d05232dc97d47640a2a764b | 50,857 |
def comment_delete_answer(request, comment_id):
"""
HelloWorld 답글댓글삭제
"""
comment = get_object_or_404(Comment, pk=comment_id)
if request.user != comment.author:
messages.error(request, '댓글삭제권한이 없습니다')
return redirect('HelloWorld:detail', question_id=comment.answer.question.id)
el... | 8d6ae80677f43e826db934ecbce3b16e3713f5cd | 50,858 |
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1), block_id=1):
"""Adds an initial convolution layer (with batch normalization and relu6).
# Arguments
inputs: Input tensor of shape `(rows, cols, 3)`
(with `channels_last` data format) or
(3, rows, cols) (with ... | b7ff0047313e66e443173c886f0ac1bd079ed143 | 50,859 |
from typing import List
def get_file_pattern() -> List[str]:
"""
Returns a list with all possible file patterns
"""
return ["*.pb", "*.data", "*.index"] | 8c4f471dea29dfe5c79cf3ea353cb1a335a5cf45 | 50,860 |
from typing import OrderedDict
async def async_setup(hass: HomeAssistantType, config: OrderedDict) -> bool:
"""Set up songpal environment."""
conf = config.get(DOMAIN)
if conf is None:
return True
for config_entry in conf:
hass.async_create_task(
hass.config_entries.flow.as... | eec8d48b721ff034b1d8cba9719979448065bfd2 | 50,861 |
def features_to_nonpadding(features, inputs_or_targets = 'inputs'):
"""See transformer.features_to_nonpadding."""
key = inputs_or_targets + '_segmentation'
if features and key in features:
return tf.minimum(tf.to_float(features[key]), 1.0)
return None | fcbcac44ef28e0b68188f9295df0c244e90677d9 | 50,862 |
import copy
import itertools
def _make_inner_dense(sparse_nested_table, outer_inner_cards, default_value):
"""
Convert n sparse nested table dictionary's implicit default values in the innetables to real entries so that
all possible assignments are present in the inner sub tables.
:param sparse_neste... | 372861e9a38016e0426ff29b62eb47fd82ff9631 | 50,863 |
def xcafdoc_DatumRefGUID(*args):
"""
* Return GUIDs for TreeNode representing specified types of datum
:rtype: Standard_GUID
"""
return _XCAFDoc.xcafdoc_DatumRefGUID(*args) | 7a84fd9ba0f46266bcb8c7a2e2a205a358ae46ab | 50,864 |
import select
import json
def get_cohort_dictionary(conn, table_name, year):
"""Get cohort dictionary."""
s = select([column("cohort_id"), column("features"), column("size")])\
.select_from(table("cohort"))\
.where(column("table") == table_name)
if year is not None:
s = s.where(col... | 1af83b0d877474a163c60e5b9c8accb60e5ee7c0 | 50,865 |
def SceneItemListsAddItemLists(builder, itemLists):
"""This method is deprecated. Please switch to AddItemLists."""
return AddItemLists(builder, itemLists) | 8eb80bc94dbac413873963f2b4f0df9b56b0e243 | 50,866 |
from typing import Union
def native_median(data: Union[list, np.ndarray, pd.Series]) -> float:
"""
Calculate Median of a list.
:param data: Input data.
:type data: list, np.ndarray, or pd.Series
:return: Returns the Median.
:rtype: float
:example: *None*
:note: If multiple values hav... | fbecfcefb29bd6cf7595936537a6b49a726050d0 | 50,867 |
import torch
def extract_tensor_batch(t, batch_size):
""" batch extraction from tensor """
# extracs batch from first dimension (only works for 2D tensors)
idx = torch.randperm(t.nelement())
return t.view(-1)[idx][:batch_size].view(batch_size,1) | 291ee82385dad8ad6a60ced0759900a8fb71e0c5 | 50,868 |
import pandas
def main():
"""Main function."""
# Print program info
print('AlfheimDataset features program.')
# Specify the list of files to read
files = ['2013-11-03_tromso_stromsgodset_first_ONLY_ONE_MINUTE.csv']#'2013-11-03_tromso_stromsgodset_first.csv']#, '2013-11-03_tromso_stromsgodset_sec... | d80884b3665f82497fe5025d47ddbc48a5f79e4d | 50,869 |
def handle_optional_login(func):
"""
Doesn't show error if no user logged in
"""
def handle(*args):
user_g = users.get_current_user()
if user_g:
curr_user = user(email=user_g.email())
else:
curr_user = None
return func(*args, curr_user=curr_user)
return handle | 21f8dcfe70dbc577a432f0e36bb2f6627677afce | 50,871 |
def charPresent(s, chars):
"""charpresent(s, chars) - returns 1 if ANY of the characters present in the string
chars is found in the string s. If none are found, 0 is returned."""
for c in chars:
if str.find(s, c) != -1:
return True
return False | cac51d18788ae4556609f5f289eb8dbb0741fc79 | 50,872 |
def get_dimensions(model_dict):
"""Extract the dimensions of the model.
Args:
model_dict (dict): The model specification. See: :ref:`model_specs`
Returns:
dict: Dimensional information like n_states, n_periods, n_controls,
n_mixtures. See :ref:`dimensions`.
"""
all_n_p... | 05898dc93cde86f30b56d09b602a1ba3c8a0a824 | 50,873 |
def assign_rank(subs, rank, tree, rankdic, root=None, above=False, major=None,
ambig=False):
"""Assign query to a fixed rank in a classification system.
Parameters
----------
subs : set of str
Subjects.
rank : str
Target rank.
tree : dict
Hierarchical cla... | f65e33d8d8cbc0bd73982b8dd22572e0b12efce3 | 50,874 |
def parse_rating(line):
"""
Parses a recommendation. Format: userId\tgender\tage\toccupation\tavg_rating\trmse\tlabels
Parameters
----------
line : str
The line that contains user information
Returns
-------
list : list
A list containing gender, age, labels
"""
... | 9860d05e7a53f9a1710433f9f9f9154e4a4e4435 | 50,875 |
import random
def enterfn(fname, call=None):
"""
Start a new call of the given function type
:param fname: Function name. All instances of the same function should execute the exact same sequence of instructions
:param call: Call name. Should be globally unique (autogenerated if not given)
:return... | 4ab15ecd2762817ee6b34aa9885c4ed3602d90da | 50,876 |
import urllib
def delete_plugin(name):
"""
Delete all the versions of a plugin by name.
Returns:
None
Raises:
404 - NotFoundError
500 - ChaliceViewError
"""
try:
name = urllib.parse.unquote(name)
print(f"Deleting plugin '{name}' and all its versions"... | 8ca08d98d6ced2157ed1fe4b08e6e1b464803cef | 50,877 |
def err_ratio(cases):
"""calculate error ratio
Args:
cases: ([case,]) all cases in all parts
Return:
float
"""
return 1 - len(list(filter(lambda x: x['valid'], cases))) / len(cases) | 421905b46c594d99b091e4d6ad094092c4483faa | 50,878 |
def _ProcessPhaseCond(cond, alias, phase_alias, _snapshot_mode):
"""Convert gate:<phase_name> to SQL."""
op = cond.op
if cond.op == ast_pb2.QueryOp.NE:
op = ast_pb2.QueryOp.EQ
elif cond.op == ast_pb2.QueryOp.NOT_TEXT_HAS:
op = ast_pb2.QueryOp.TEXT_HAS
cond_str, cond_args = _Compare(
phase_alia... | 1395e084071fcf0621e92d5c2829fe2bab3188b1 | 50,879 |
def create_keymaps(raw_keymaps):
"""Create `Keymap` object from `raw_keymaps`."""
keymap_objs = []
for raw_keymap in raw_keymaps:
try:
keymap_obj = KeymapCreater.create(raw_keymap)
keymap_objs.append(keymap_obj)
except exception.InvalidKeymapException as e:
... | 5d26613f39b423fc0db2607b03e7d6fa69718da9 | 50,882 |
def get_param_cols(columns):
""" Get the columns that were provided in the file and return that list so we don't try to query non-existent cols
Args:
columns: The columns in the header of the provided file
Returns:
A dict containing all the FPDS query columns that the provi... | 8a0030c745d2de5bd2baf93af79efce4dcb4c696 | 50,883 |
import re
def depluralize(word):
"""Return the depluralized version of the word, along with a status flag.
Parameters
----------
word : str
The word which is to be depluralized.
Returns
-------
str
The original word, if it is detected to be non-plural, or the
dep... | 9d879a320da566bceb6e5db6cbfe2e7f23f9bb73 | 50,884 |
from typing import List
def generate_text(n: int, **kwargs) -> List[str]:
"""
:param n: number of words
:return:
"""
words = [generate_word(**kwargs) for _ in range(n)]
return words | fdf08af9ea537255c38d5004e814e3d137448b67 | 50,885 |
def TInt_GetInRng(*args):
"""
TInt_GetInRng(int const & Val, int const & Mn, int const & Mx) -> int
Parameters:
Val: int const &
Mn: int const &
Mx: int const &
"""
return _snap.TInt_GetInRng(*args) | 30be5d5f6dbad6b119192f71c039e88c3af69b05 | 50,887 |
async def room_data(room_id: int, redis: Redis = Depends(get_redis)):
"""Get the current state of the room.
The clients maintain their own state, which _should_ each
be accurate, but as not all clients may join before
one of the clients start making changes to the room's state.
"""
return get_r... | e5d7200eab587e38f85d7941c294a7e74bf7b6fb | 50,888 |
def get_reference_model(model, endog, exog):
"""
Build an `UnobservedComponents` model using as reference the input `model`. We need
an exactly similar object as `model` but instantiated with different `endog` and
`exog`.
Args
----
model: `UnobservedComponents`.
Template model t... | 2139ca7fe371ef9547d38fa4ca604600fb38735b | 50,889 |
def remove_suffix_ness(word):
"""
:param word: str of word to remove suffix from.
:return: str of word with suffix removed & spelling adjusted.
This function takes in a word and returns the base word with `ness` removed.
"""
# print(word[:-4])
word = word[:-4]
if word[-1] == "i":
... | c8fa4e55a8eaa1259e66a90adc60329d3a9bc3c9 | 50,890 |
import ipaddress
def _get_network_address(ip, mask=24):
"""
Return address of the IPv4 network for single IPv4 address with given mask.
"""
ip = ipaddress.ip_address(ip)
return ipaddress.ip_network(
'{}/{}'.format(
ipaddress.ip_address(int(ip) & (2**32 - 1) << (32 - mask)),
... | bb706209cc7295ab1d0b4bf88e11d3efba10d526 | 50,891 |
def happy_birthday(name, age:hug.types.number):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals()) | 2483f1f1e47720e93772a4fddf3486c3cb39e2be | 50,892 |
def get_admin_ids(bot, chat_id):
"""
Returns a list of admin IDs for a given chat. Results are cached for 1 hour.
Private chats and groups with all_members_are_administrator flag are handled as empty admin list
"""
chat = bot.getChat(chat_id)
if chat.type == "private" or chat.all_members_are_adm... | 6bd89e1d6b7333d97cbc60fd2617a86d1b69fb2f | 50,893 |
import torch
def multiply_conj(x, y):
"""Return x * conj(y) in complex form."""
x_real, x_imag = unpack(x)
y_real, y_imag = unpack(y)
yconj_real = y_real
yconj_imag = -y_imag
return torch.stack(
[
x_real * yconj_real - x_imag * yconj_imag,
x_imag * yconj_real + ... | 89bbd49d5052aa4f3c6ef611c461b4fb44c82070 | 50,894 |
def read_results_file(filename):
"""
For n=3 with automatic interval selection, reads in the results file to get C
Args:
filename: location of results file
Returns:
C: list form of the second column of the result copy number profile
"""
with open(filename) as f:
lines = ... | 0c9854476ed28142930b21bf55df54c63a598fd5 | 50,895 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.