content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def genBetaModel(matshape, cen, betaparam):
"""
Generate beta model with given parameters
inputs
======
matshape: tuple or list
Shape of the matrix
cen: tuple or list
Location of the center pixel
betaparam: dict
Parameters of the beta function
{ "A": float,
... | 37,100 |
def folders_to_create(search_path, dirs, base_path=""):
"""
Recursively traverse through folder paths looking for the longest existing subpath.
Return the dir info of the longest subpath and the directories that
need to be created.
"""
# Allow user to pass in a string, but use a list in the rec... | 37,101 |
def send_message(token, recipient, text):
"""Send the message text to the recipient using messenger API."""
r = requests.post(
"https://graph.facebook.com/v2.6/me/messages",
params={"access_token": token},
data=json.dumps(
{
"recipient": {"id": recipient},
"message"... | 37,102 |
def profile_line(image, src, dst, linewidth=1,
order=1, mode='constant', cval=0.0):
"""Return the intensity profile of an image measured along a scan line.
Parameters
----------
image : numeric array, shape (M, N[, C])
The image, either grayscale (2D array) or multichannel
... | 37,103 |
def set_out(pin, state):
"""
Set simple digital (high/low) output
:param pin: pun number or logical name
:param state: state: 1/0 = True/False
:return: verdict
"""
__digital_out_init(pin).value(state)
return {'pin': pin, 'state': state} | 37,104 |
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['_run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_p... | 37,105 |
def _assert_identical_data_entity_exists(app_context, test_object):
"""Checks a specific entity exists in a given namespace."""
old_namespace = namespace_manager.get_namespace()
try:
namespace_manager.set_namespace(app_context.get_namespace_name())
entity_class = test_object.__class__
... | 37,106 |
def get_session():
"""Define a re-usable Session object"""
session = requests.Session()
session.auth = auth
session.verify = False
return session | 37,107 |
def main():
"""Main function."""
options = get_options()
LOG.debug("Options are %s", options)
entry_point = get_entrypoint()
plugin = get_plugin(entry_point)
inventory = plugin.get_dynamic_inventory()
if options.list:
dumps(inventory)
elif options.host in inventory["_meta"]["h... | 37,108 |
def create_test_action(context, **kw):
"""Create and return a test action object.
Create a action in the DB and return a Action object with appropriate
attributes.
"""
action = get_test_action(context, **kw)
action.create()
return action | 37,109 |
def parse(header_array, is_paper=False):
""" Decides which version of the headers to use."""
if not is_paper:
version = clean_entry(header_array[2])
if old_eheaders_re.match(version):
headers_list = old_eheaders
elif new_eheaders_re.match(version):
... | 37,110 |
def _GetIssueIDsFromLocalIdsCond(cnxn, cond, project_ids, services):
"""Returns global IDs from the local IDs provided in the cond."""
# Get {project_name: project} for all projects in project_ids.
ids_to_projects = services.project.GetProjects(cnxn, project_ids)
ref_projects = {pb.project_name: pb for pb in id... | 37,111 |
def lookup_plex_media(hass, content_type, content_id):
"""Look up Plex media for other integrations using media_player.play_media service payloads."""
content = json.loads(content_id)
if isinstance(content, int):
content = {"plex_key": content}
content_type = DOMAIN
plex_server_name = ... | 37,112 |
def get_file_paths(directory, file=None):
"""
Collects the file paths from the given directory if the file is not given, otherwise creates a path
joining the given directory and file.
:param directory: The directory where the file(s) can be found
:param file: A file in the directory
:return: The... | 37,113 |
def dsym_test(func):
"""Decorate the item as a dsym test."""
if isinstance(func, type) and issubclass(func, unittest2.TestCase):
raise Exception("@dsym_test can only be used to decorate a test method")
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
if lldb.dont_do_dsym... | 37,114 |
def count_meetings(signups=None, left: datetime=None, right: datetime=None) -> int:
""" Returns the number of meetings the user has been to, between two
date ranges. Left bound is chosen as an arbitrary date guaranteed to
be after any 8th periods from the past year, but before any from the
current year.... | 37,115 |
def fake_surroundings(len_poem, size_surroundings=5):
"""
Retourne une liste d'indices tirée au sort
:param len_poem: nombre de vers dans le poème
:param size_surroundings: distance du vers de référence du vers (default 5)
:return: liste
"""
# bornes inférieures
lower_bounds_w_neg = np.a... | 37,116 |
def interpolate_missing(sparse_list):
"""Use linear interpolation to estimate values for missing samples."""
dense_list = list(sparse_list)
x_vals, y_vals, x_blanks = [], [], []
for x, y in enumerate(sparse_list):
if y is not None:
x_vals.append(x)
y_vals.append(y)
... | 37,117 |
def remove_pipeline(name: str, version: Optional[Union[str, int]] = None, db: Session = DB_SESSION):
"""
Removes a pipeline from the Feature Store
"""
version = parse_version(version)
pipelines = crud.get_pipelines(db, _filter={'name': name, 'pipeline_version': version})
if not pipelines:
... | 37,118 |
def auto_format_rtf(file_path, debug=False):
""" Input complete filepath to .rtf file
replaces all instances of "\\line" to "\\par".
writes new data to new file with "MODFIED" appended.
Prints debug messages to console if debug=True.
"""
# Separates file name and extension for proces... | 37,119 |
def classifier_uncertainty(classifier: BaseEstimator, X: modALinput, **predict_proba_kwargs) -> np.ndarray:
"""
Classification uncertainty of the classifier for the provided samples.
Args:
classifier: The classifier for which the uncertainty is to be measured.
X: The samples for which the u... | 37,120 |
def fetch_nature_scene_similarity(data_home: Optional[os.PathLike] = None, download_if_missing: bool = True,
shuffle: bool = True, random_state: Optional[np.random.RandomState] = None,
return_triplets: bool = False) -> Union[Bunch, np.ndarray]:
"""... | 37,121 |
def state_validation(instance):
"""Perform state validation."""
entity = "State"
check_instance(entity, instance)
check_instance("Country", instance.country)
# Note: underlying implementation may raise KeyError or return None
try:
official = pycountry.subdivisions.get(code=instance.iso_... | 37,122 |
def test_preserve_scalars():
""" test the preserve_scalars decorator """
class Test():
@misc.preserve_scalars
def meth(self, arr):
return arr + 1
t = Test()
assert t.meth(1) == 2
np.testing.assert_equal(t.meth(np.ones(2)), np.full(2, 2)) | 37,123 |
def test_empty_video_id():
"""
Tests that an empty video id does not give a result
"""
result = stream_to_s3("")
assert not result | 37,124 |
def from_string(zma_str, one_indexed=True, angstrom=True, degree=True):
""" read a z-matrix from a string
"""
syms, key_mat, name_mat, val_dct = ar.zmatrix.read(zma_str)
val_mat = tuple(tuple(val_dct[name] if name is not None else None
for name in name_mat_row)
... | 37,125 |
def search(raw_query, query_type='/fast/all'):
"""
Hit the FAST API for names.
"""
out = []
unique_fast_ids = []
query = text.normalize(raw_query, PY3).replace('the university of', 'university of').strip()
query_type_meta = [i for i in refine_to_fast if i['id'] == query_type]
if query_ty... | 37,126 |
def all_data():
"""Return list from fetch data csv"""
import csv
import pygal as pg
main_data = csv.reader(open('airtrafficstats.csv', newline=''))
main_data = [row for row in main_data]
pass_ = []
for i in main_data:
if i[1] == "Passenger":
pass_.append(i)
... | 37,127 |
def get_jmp_addr(bb):
"""
@param bb List of PseudoInstructions of one basic block
@return Address of jump instruction in this basic block
"""
for inst in bb:
if inst.inst_type == 'jmp_T':
return inst.addr
return None | 37,128 |
def mock_publish_from_s3_to_redis_err(
work_dict):
"""mock_publish_from_s3_to_redis_err
:param work_dict: dictionary for driving the task
"""
env_key = 'TEST_S3_CONTENTS'
redis_key = work_dict.get(
'redis_key',
env_key)
str_dict = ae_consts.ev(
env_key,
... | 37,129 |
def open_db_conn(db_file=r'/home/openwpm/Desktop/crawl-data.sqlite'):
""""
open connection to sqlite database
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Exception as e:
print(e)
return None | 37,130 |
def test_default_stock_details_(dummy_request, db_session):
"""test query db with incorrect key"""
from ..views.entry import detail_view
dummy_request.GET = {'sdcs': 'ss'}
response = detail_view(dummy_request)
from pyramid.httpexceptions import HTTPNotFound
assert isinstance(response, HTTPNotFou... | 37,131 |
def update_link(src: Path, dest: Path) -> None:
"""
Create/move a symbolic link at 'dest' to point to 'src'.
If dest is a symbolic link and it points to a different target file, than
src, it changes the link to point to src.
If dest does not exist the link is created.
If dest exists but is not ... | 37,132 |
def totals_per_time_frame(data_points, time_frame):
"""For a set of data points from a single CSV file,
calculate the average percent restransmissions per time frame
Args:
data_points (List[List[int,int,float]]): A list of data points.
Each data... | 37,133 |
def main():
"""Use the GitHub API to print Pull Requests with review requests."""
token = get_token(GITHUB_API_TOKEN, GH_CONFIG_FILE, HUB_CONFIG_FILE)
session = github_session(token)
data = get_review_requests_defaults()
pull_requests = [
{
"url": pull_request["html_url"],
... | 37,134 |
def calc_2phase_vu(datetime_stamps, dsmx, smx, config):
"""."""
logger.info("Computing for 2-phase image-based results")
for view in dsmx:
opath = os.path.join(config.resdir, f'view_{config.name}_{view}')
if os.path.isdir(opath):
shutil.rmtree(opath)
util.sprun(
... | 37,135 |
def extract_lesional_clus(label, input_scan, scan, options):
"""
find cluster components in the prediction
corresponding to the true label cluster
"""
t_bin = options['t_bin']
# t_bin = 0
l_min = options['l_min']
output_scan = np.zeros_like(input_scan)
# threshold input segmentation... | 37,136 |
def glColor3fv(v):
"""
v - seq( GLfloat, 3)
"""
if 3 != len(v):
raise TypeError(len(v), "3-array expected")
_gllib.glColor3fv(v) | 37,137 |
def feed_to_hdf5(feature_vector, subject_num, utterance_train_storage, utterance_test_storage, label_train_storage,
label_test_storage):
"""
:param feature_vector: The feature vector for each sound file of shape: (num_frames,num_features_per_frame,num_channles.)
:param subject_num: The sub... | 37,138 |
def add_port_fwd(
zone, src, dest, proto="tcp", dstaddr="", permanent=True, force_masquerade=False
):
"""
Add port forwarding.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port_fwd public 80 443 tcp
force_masquerade
when a zone is c... | 37,139 |
def reduce_puzzle(values):
"""Reduce a Sudoku puzzle by repeatedly applying all constraint strategies
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary after continued application o... | 37,140 |
async def pin(msg):
""" For .Pin command, pins the replied/tagged message on the top the chat. """
# Admin or creator check
chat = await msg.get_chat()
admin = chat.admin_rights
creator = chat.creator
# If not admin and not creator, return
if not admin and not creator:
await msg.edi... | 37,141 |
def read_int(handle):
"""
Helper function to parse int from file handle
Args:
handle (file): File handle
Returns:
numpy.int32
"""
return struct.unpack("<i", handle.read(4))[0] | 37,142 |
def prem_to_av(t):
"""Premium portion put in account value
The amount of premiums net of loadings, which is put in the accoutn value.
.. seealso::
* :func:`load_prem_rate`
* :func:`premium_pp`
* :func:`pols_if_at`
"""
return prem_to_av_pp(t) * pols_if_at(t, "BEF_DECR") | 37,143 |
def remove_close(points, radius):
"""
Given an nxd set of points where d=2or3 return a list of points where no point is closer than radius
:param points: a nxd list of points
:param radius:
:return:
author: revised by weiwei
date: 20201202
"""
from scipy.spatial import cKDTree
tr... | 37,144 |
def pose_mof2mat_v1(mof, rotation_mode='euler'):
"""
### Out-of-Memory Issue ###
Convert 6DoF parameters to transformation matrix.
Args:
mof: 6DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [B, 6, H, W]
Returns:
A transformation matrix -- [B, 3, 4, H, W]
"""
bs, _, ... | 37,145 |
def kmercountexact(forward_in, reverse_in='NA', returncmd=False, **kwargs):
"""
Wrapper for kmer count exact.
:param forward_in: Forward input reads.
:param reverse_in: Reverse input reads. Found automatically for certain conventions.
:param returncmd: If set to true, function will return the cmd st... | 37,146 |
def update(isamAppliance, local, remote_address, remote_port, remote_facility, check_mode=False, force=False):
"""
Updates logging configuration
"""
json_data = {
"local": local,
"remote_address": remote_address,
"remote_port": remote_port,
"remote_facility": remote_facil... | 37,147 |
def install_requirements():
"""Installs requirements inside vertualenv"""
with source_env():
run('pip install --force-reinstall -Ur requirements.txt') | 37,148 |
def save_vocab(vocab, separate_domains, crop, output_dir, vocab_filename):
"""Save vocabulary to file
Args:
vocab (list of String): the list of vocabularies.
separate_domains (Boolean): indicate the plaintext and cipher are in separate domain.
crop: (Integer): the amount of crop applied.
output_dir ... | 37,149 |
def plot_label_per_class(y_data,LABELS):
"""
MOD:add Labels Dict
"""
classes = sorted(np.unique(y_data))
f, ax = plt.subplots(1,1, figsize=(12, 4))
g = sns.countplot(y_data, order=classes)
g.set_title("Number of labels for each class")
for p, label in zip(g.patches, classes):
... | 37,150 |
def get_model_and_tokenizer(
model_name_or_path: str,
tokenizer_name_or_path: str,
auto_model_type: _BaseAutoModelClass,
max_length: int = constants.DEFAULT_MAX_LENGTH,
auto_model_config: AutoConfig = None,
) -> Tuple[AutoModelForSequenceClassification, AutoTokenizer]:
"""Get transformer model a... | 37,151 |
def get_forecast_by_coordinates(
x: float,
y: float,
language: str = "en"
) -> str:
"""
Get the weather forecast for the site closest to the coordinates (x, y).
Uses the scipy kd-tree nearest-neighbor algorithm to find the closest
site.
Parameters
----------
x : float
L... | 37,152 |
def get_calculated_energies(stem, data=None):
"""Return the energies from the calculation"""
if data is None:
data = {}
stem = stem.find('calculation')
for key, path in VASP_CALCULATED_ENERGIES.items():
text = get_text_from_section(stem, path, key)
data[key] = float(text.split()[... | 37,153 |
def main():
"""Be the top-level entrypoint. Return a shell status code."""
commands = {'hash': peep_hash,
'install': peep_install,
'port': peep_port}
try:
if len(argv) >= 2 and argv[1] in commands:
return commands[argv[1]](argv[2:])
else:
... | 37,154 |
def test_analyze__analyze_storage__7(zodb_storage, zodb_root):
"""It analyzes contents of `BTree`s."""
zodb_root['tree'] = BTrees.OOBTree.OOBTree()
zodb_root['tree']['key'] = b'bïnäry'
zodb_root['tree']['stuff'] = [{'këy': b'binäry'}]
zodb_root['tree']['iter'] = [u'unicode_string']
transaction.c... | 37,155 |
def reshape(spectra):
"""Rearrange a compressed 1d array of spherical harmonics to 2d
Args:
spectra (np.ndarray): 1 dimensional storage of 2d spherical modes
Returns:
np.ndarray:
2-dimensional array of the reshaped input with zonal and meridional
wavenumber coordina... | 37,156 |
def preprocess(save_dir, reactants, products, reaction_types=None):
"""
preprocess reaction data to extract graph adjacency matrix and features
"""
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for index in tqdm(range(len(reactants))):
product = products[index]
reac... | 37,157 |
def dict_factory(cursor, row):
"""
This method is used to convert tuple type to dict after execute SQL queries in python.
:param cursor:
:param row:
:return:
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | 37,158 |
def ping2(report):
"""
Sends 'pong' back
"""
report.author.send_pm("pong2", "Hey %s! Pong!" % report.author.name) | 37,159 |
def predict_batch(model, x_batch, dynamics, fast_init):
"""
Compute the softmax prediction probabilities for a given data batch.
Args:
model: EnergyBasedModel
x_batch: Batch of input tensors
dynamics: Dictionary containing the keyword arguments
for the relaxation dynamic... | 37,160 |
def render_openapi(api, request):
"""Prepare openapi specs."""
# Setup Specs
options = dict(api.openapi_options)
options.setdefault('servers', [{
'url': str(request.url.with_query('').with_path(api.prefix))
}])
spec = APISpec(
options['info'].pop('title', f"{ api.app.cfg.name.ti... | 37,161 |
def apply_transformations(initial_representation: list, events: list) -> float:
"""Apply the transformations in the events list to the initial representation"""
scale = 1
rot_angle = 0
trans_vector = [0, 0]
for item in events:
for event in item["events"]:
if event["type"] == "TR... | 37,162 |
def affine_transform(transform, points):
"""
Transforms a set of N x 2 points using the given Affine object.
"""
reshaped_points = np.vstack([points.T, np.ones((1, points.shape[0]))])
transformed = np.dot(affine_to_matrix(transform), reshaped_points)
return transformed.T[:,:2] | 37,163 |
def disable_passwordless_registration() -> None:
"""Enable open registration configuation"""
yield from tweak_config('USERS_PASSWORDLESS_REGISTRATION', False) | 37,164 |
def get_current_time_in_millisecs():
"""Returns time in milliseconds since the Epoch."""
return get_time_in_millisecs(datetime.datetime.utcnow()) | 37,165 |
def _convert_named_signatures_to_signature_def(signatures):
"""Convert named signatures to object of type SignatureDef.
Args:
signatures: object of type manifest_pb2.Signatures()
Returns:
object of type SignatureDef which contains a converted version of named
signatures from input signatures object
... | 37,166 |
def release(branch=None, fork="sympy"):
"""
Perform all the steps required for the release, except uploading
In particular, it builds all the release files, and puts them in the
release/ directory in the same directory as this one. At the end, it
prints some things that need to be pasted into vari... | 37,167 |
def get_test_paths(paths, snaps):
"""
Return $snaps paths to be tested on GLUE
"""
if snaps == -1:
return paths
interval = len(paths) * 1. / snaps
test_paths = []
for i in range(1, snaps+1):
idx = int(math.ceil(interval * i)) - 1
test_paths.append(paths[idx])
retu... | 37,168 |
def save_games_list(games_list, location):
"""
Save a games list.
games_list/tuple: (game_full_name, game_full_path, game_icon, game_dir, game_state)
location/dir: full path.
"""
pass | 37,169 |
def is_success(code):
"""Return that the client's request was successfully received, understood, and accepted."""
return 200 <= code <= 299 | 37,170 |
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v3('noon')
True
>>> is_palindrome_v3('racecar')
True
>>> is_palindrome_v3('dented')
False
>>> is_palindrome_v3('')
True
>>> is_palindrome_v3(' ')
True
"""
... | 37,171 |
def _create_sample_and_placeholder_dataset(project, row):
"""Create Datasets but don't copy data.
"""
# Parsing and validation.
fastq1_filename = row['Read_1_Filename']
maybe_fastq2_filename = row.get('Read_2_Filename', '')
assert fastq1_filename != maybe_fastq2_filename
# Now create the mo... | 37,172 |
def read(fd: BinaryIO) -> Entity:
"""Read mug scene from `fd` file object.
Args:
fd: File object to read from.
Returns:
Root entity.
"""
if fd.read(4) != b'MUGS':
raise ValueError("not a valid mug file format")
return read_recursive(fd) | 37,173 |
def transform(x,y):
"""
This function takes an input vector of x values and y values, transforms them
to return the y in a linearized format (assuming nlogn function was used
to create y from x)
"""
final = []
for i in range(0, len(y)):
new = y[i]#/x[i]
final.append(2 ** new)... | 37,174 |
def _GRIsAreEnabled():
"""Returns True if GRIs are enabled."""
return (properties.VALUES.core.enable_gri.GetBool() or
properties.VALUES.core.resource_completion_style.Get() == 'gri') | 37,175 |
def record_images(root_folder: Union[str, Path]):
"""Use opencv to record timestamped images from the webcam."""
# Setup paths
if not root_folder:
root_folder = Path.cwd()
root_folder = create_path(root_folder, 'data')
current_subfolder = create_path(root_folder, dt_name(datetime.now()))
... | 37,176 |
def fatorial(n, show=False):
"""
-> Calcula o Fatorial de um número
:param n: O número a ser calculado.
:param show: (opcional) Mostrar ou não a conta.
:return: O valor do Fatorial de um número n.
"""
contador = n
resultado = guardado = 0
print('-' * 35)
while contador >= 0:
... | 37,177 |
def start_job(job, hal_id, refGenome, opts):
"""Set up the structure of the pipeline."""
hal = hal_id
# Newick representation of the HAL species tree.
newick_string = get_hal_tree(hal)
job.fileStore.logToMaster("Newick string: %s" % (newick_string))
tree = newick.loads(newick_string)[0]
rero... | 37,178 |
def user_base(username):
"""Base path of user files"""
return os.path.join(BASE['user'], username) | 37,179 |
def write_html_columns(file):
"""Write HTML columns."""
write_html_column("color1", file, "Backlog", THINGS3.get_someday())
write_html_column("color8", file, "Grooming", THINGS3.get_cleanup())
write_html_column("color5", file, "Upcoming", THINGS3.get_upcoming())
write_html_column("color3", file, "W... | 37,180 |
def main(event, context):
# pylint: enable=unused-argument
"""
Requests the leaderboard for a competition from Kaggle and publishes it into a
Pub/Sub topic.
"""
data = decode(event["data"])
competition = data["competition"]
top = data.get("top")
requested_at = datetime.now().isoform... | 37,181 |
def get_args(arg_input):
"""Takes args input and returns them as a argparse parser
Parameters
-------------
arg_input : list, shape (n_nargs,)
contains list of arguments passed to function
Returns
-------------
args : namespace
contains namespace with keys and values for... | 37,182 |
def cleanup_databases():
"""
Returns:
bool: admin_client fixture should ignore any existing databases at
start of test and clean them up.
"""
return False | 37,183 |
def load_jupyter_server_extension(nb_server_app):
"""
Called when the extension is loaded.
Args:
nb_server_app (NotebookApp): handle to the Notebook webserver instance.
"""
nb_server_app.log.info('serverless module enabled!')
web_app = nb_server_app.web_app
# Prepend the base_url so... | 37,184 |
def _round_down(rough_value, increment, minimum=None, maximum=None):
"""Utility method for rounding a value down to an increment.
Args:
rough_value: A float. The initial value to be rounded.
increment: The increment to round down to.
minimum: Optional minimum value, default is increment.
maximum: O... | 37,185 |
def document_index_list(request, document_id):
"""
Show a list of indexes where the current document can be found
"""
document = get_object_or_404(Document, pk=document_id)
object_list = []
queryset = document.indexinstancenode_set.all()
try:
# TODO: should be AND not OR
Per... | 37,186 |
def spot_centroid(regions):
"""Returns centroids for a list of regionprops.
Args:
regions (regionprops): List of region proposals (skimage.measure).
Returns:
list: Centroids of regionprops.
"""
return [r.centroid for r in regions] | 37,187 |
def FindChromeSrcFromFilename(filename):
"""Searches for the root of the Chromium checkout.
Simply checks parent directories until it finds .gclient and src/.
Args:
filename: (String) Path to source file being edited.
Returns:
(String) Path of 'src/', or None if unable to find.
"""
curdir = os.pa... | 37,188 |
def _merge_uuids(
before: "definitions.Configuration",
after: "definitions.Configuration",
):
"""Add matching UUIDs from before to the after for continuity."""
after.data["_uuid"] = before.uuid
mapping = {name: target for target in before.targets for name in target.names}
for target in after.t... | 37,189 |
def add_parse_cmd(parser):
"""This adds a Zeek script parser CLI interface to the given argparse parser. It
registers the cmd_parse() callback as the parser's run_cmd default."""
parser.set_defaults(run_cmd=cmd_parse)
parser.add_argument(
'--concrete', '-c', action='store_true',
help='re... | 37,190 |
def one_election_set_reg(request, election):
"""
Set whether this is open registration or not
"""
# only allow this for public elections
if not election.private_p:
open_p = bool(int(request.GET['open_p']))
election.openreg = open_p
election.save()
return HttpResponseRedirect(settings.SECURE_U... | 37,191 |
def test_duplicate_subjects():
"""Test that two triplets with the same subject can be retrieved."""
c = chrome_manifest("""
foo bar abc
foo bar def
foo bam test
oof rab cba
""")
assert len(list(c.get_entries('foo'))) == 3
assert len(list(c.get_entries('foo', 'bar'))... | 37,192 |
def overrides(conf, var):
"""This api overrides the dictionary which contains same keys"""
if isinstance(var, list):
for item in var:
if item in conf:
for key, value in conf[item].items():
conf[key] = value
elif var in conf:
for key, value in c... | 37,193 |
def annual_to_daily_rate(rate, trading_days_in_year=TRADING_DAYS_IN_YEAR):
"""
Infer daily rate from annual rate
:param rate: the annual rate of return
:param trading_days_in_year: optional, trading days in year (default = 252)
:return: the daily rate
"""
return subdivide_rate(rate, trading_... | 37,194 |
def make_hashable(data):
"""Make the given object hashable.
It makes it ready to use in a `hash()` call, making sure that
it's always the same for lists and dictionaries if they have the same items.
:param object data: the object to hash
:return: a hashable object
:rtype: object
"""
if... | 37,195 |
def reset_singularity_version_cache() -> None:
"""Reset the cache for testing."""
cwltool.singularity._SINGULARITY_VERSION = None
cwltool.singularity._SINGULARITY_FLAVOR = "" | 37,196 |
def prepare_model_parameters(
parameters: Dict[str, FloatOrDistVar], data: DataFrame,
beta_fun, splines, spline_power
) -> Tuple[Dict[str, FloatLike], Dict[str, NormalDistVar]]:
"""Prepares model input parameters and returns independent and dependent parameters
Also shifts back simulation to start wit... | 37,197 |
def paper_features_to_author_features(
author_paper_index, paper_features):
"""Averages paper features to authors."""
assert paper_features.shape[0] == NUM_PAPERS
assert author_paper_index.shape[0] == NUM_AUTHORS
author_features = np.zeros(
[NUM_AUTHORS, paper_features.shape[1]], dtype=paper_features.... | 37,198 |
def set_chart_time_horizon(request) -> JsonResponse:
"""
Set the x-axis (time horizon) of a chart.
API Call:
/set_chart_time_horizon?
monitor_name=<monitor name>&
value=<time horizon to set>
:param request: HTTP request that expects a 'monitor_name' and 'value' argument. 'value... | 37,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.