content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _select_command_reply(replies: list, command: int, seq: int=None):
"""
Find a valid command reply
returns dict
"""
filtered_replies = list(filter(lambda x: x["cmd"] == command, replies))
if seq is not None:
filtered_replies = list(filter(lambda x: x["seq"] == seq, filtered_replies))... | 4ee65e604918a9c1fe4e639c524f6f4e4371f775 | 3,632,700 |
def remove_st_less_than(dataframe, column='ST', less_than=0.001):
"""
Remove any entry with an ST less than specified
Args:
dataframe (pandas.Dataframe): dataframe containing sensitivity analysis output
column (str): Column name, default is 'ST'
less_than (float): Remove anything le... | 2ba052004c436f8d527ab9b5bc3e76c90aa5dce9 | 3,632,701 |
def count_positives_sum_negatives2(arr):
"""
More space efficient, but not as concise as above
"""
if not arr:
return arr
count = 0
total = 0
for num in arr:
if num > 0:
count += 1
else:
total += num
return [count, total] | f1f8de28dcf6669d49044a43e6a8603f0da01577 | 3,632,702 |
import json
def read_json(url, cached=True):
"""Read JSON content from url."""
content = read(url, cached)
return json.loads(content) if content else None | 9a256e2ec5842c6e77da175cf11e953e2a1c03a0 | 3,632,703 |
def spherical_Lloyd(radius,
num_cells,
dimension=3,
fixed='center',
approximation='monte-carlo',
approx_n=5000,
max_iter=500,
momentum=0.9,
verbose=0):
"""C... | cd3f202945be887a0835ce271bc38c3dc192aa33 | 3,632,704 |
import http
import os
def get_online_version():
"""Download update info and parse it."""
page = http.default_session.get(UPDATE_URL).json()
version = page.get('tag_name', None)
if os.name == 'nt':
try:
url = next((x['browser_download_url'] for x in page['assets'] if
... | 8f32b220de831db1af847285010ec77603ce0911 | 3,632,705 |
import traceback
import sys
def log_errors(func):
"""
Helper to print errors to stderr, since an issue with
Django Debug Toolbar prevents exceptions
from threads from being logged to the console.
"""
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwarg... | 5c943f865abfa8f8183ea8cf295f5953b2ce6548 | 3,632,706 |
def first_primes(n: Integral) -> list:
"""
Generates a list of the first n primes. A cast will be used if the input is not an integer
"""
n = int(n) - 1
bank = []
track = 2
while len(bank) < n + 1:
if all(track % y for y in range(2, min(track, 11))):
bank.append(track)
... | 04927ce0be9f9ed2fc3e65a346599625e9919a95 | 3,632,707 |
def is_ne_atom(phi: Formula):
""" Return whether the given formula is an inequality """
return isinstance(phi, Atom) and phi.predicate.symbol == BuiltinPredicateSymbol.NE | 30cdee64bf622b803efe041bd1feaa7d7a2fb2fe | 3,632,708 |
def fact(n):
"""Return the factorial of the given number."""
r = 1
while n > 0:
r = r * n
n = n - 1
return r | 7bdcdc759b49a9cd72f7bf3f12a18fc03ce50668 | 3,632,709 |
def getCoatThickCorr(f, materials, wavelength, dOpt, dTE, dTR):
"""Finite coating thickness correction
:f: frequency array in Hz
:materials: gwinc optic materials structure
:wavelength: laser wavelength
:wBeam: beam radius (at 1 / e**2 power)
:dOpt: coating layer thickness array (Nlayer x 1)
... | 92734aced5c17e44b97e73f57850409fcddc3102 | 3,632,710 |
from datetime import datetime
import os
from shutil import copyfile
def create_logdir(directory, algorithm, env_name, config_path):
"""
Create a directory inside the specified directory for
logging experiment results and return its path name.
Include the environment name (Sharpe, etc.) in the directo... | 9b1e188e2925dec49dad4c31bba8eec9ab0ddbd0 | 3,632,711 |
import itertools
def create_purchase(row):
"""Creates Purchase object based on BeautifulSoup table row object"""
name = next(itertools.islice(row.stripped_strings, 0, 1))
id = row.a['data-character-id']
price = "".join(next(itertools.islice(row.stripped_strings, 3, 4)).split())
level = len(row.fin... | 3676d8e382bd9cc7441118cdd19a6e12fe955821 | 3,632,712 |
def accuracy(predictions, targets):
"""
Computes the prediction accuracy, i.e. the average of correct predictions
of the network.
Args:
predictions: 2D float array of size [batch_size, n_classes]
labels: 2D int array of size [batch_size, n_classes]
with one-hot encoding. Ground truth la... | 42fa30e7afc1fd6a2272bf4b6f946fed112b7d29 | 3,632,713 |
import logging
import os
def prepare_intercancer_data(jx_dir):
"""
:param jx_dir:
:return:
"""
jx_counts = {}
count_df_dict = {'jx': [], 'top_x': []}
for cancer in _TCGA_ABBR:
logging.info('starting cancer {}'.format(cancer))
jx_file, flag, prev_glob = get_jx_prev_filename... | 6756b50c28f893931601e6d789424ae546ef07a7 | 3,632,714 |
def load_tough_corners(fname):
"""
Load the mesh of the domain; discared by default. Use VTK_output = .TRUE. to obtain from MeshMaker_V2
fname shoud be the CORNERS file
"""
ndim = 3
verts = {}
cells = []
elemnames = []
f = open(fname,"r")
enum = -1
elem = []
for l in f:
... | a7219c39344b79fa33459e64ed7eaffe124b941b | 3,632,715 |
import io
def dumps(obj, bytes=False):
"""WARNING: can mutate obj"""
if bytes:
out = io.BytesIO()
else:
out = io.StringIO()
dump(obj, out)
return out.getvalue() | 063ad30f8bd4b1b5905da5c924e3dcd6a577a244 | 3,632,716 |
def evaluate_results(model, contexts, layer_dimension, all_tasks_test_data, superposition, task_index, first_average, use_MLP, batch_size, use_PSP=False):
"""
Evaluate the results on test data with or without using superposition. Return accuracy, AUROC and AUPRC.
:param model: torch model instance
:par... | 3d8bdaae78d53df9edfd767af85229c73a96b12e | 3,632,717 |
def list_column(column, original_name):
"""Get all non nan values from column."""
if original_name == 'original_formatted':
list_filled = [[x for x in row if str(x) != 'nan'] for row in column]
else:
list_filled = [[_] for _ in column]
return list_filled | ae8b900cdcf3e59ff4ede3b3dc0321d93ea07253 | 3,632,718 |
def query_audioobject(identifier: str = None, title: str = None, contributor: str = None,
creator: str = None, source: str = None, format_: str = None, name: str = None,
date: str = None, encodingformat: str = None,
embedurl: str = None, url: str = None,... | 63ee4c20acef392dad4fa6b4d2039bd6609659f0 | 3,632,719 |
import copy
def test_create_new_grant_alt2(cbcsdk_mock):
"""Test creation of a grant and the profile inside it with more options."""
def respond_to_profile_grant(url, body, **kwargs):
ret = copy.deepcopy(POST_PROFILE_IN_GRANT_RESP_2)
ret['profile_uuid'] = body['profile_uuid']
return re... | 75ddaa6d488409e04b4045aed34813804659c0ee | 3,632,720 |
from models.user import User
def stats() -> str:
""" GET /api/v1/stats
Return:
- the number of each objects
"""
stats = {}
stats['users'] = User.count()
return jsonify(stats) | 18ff101234c1df23460417ecac13663e60e6ae26 | 3,632,721 |
from optparse import OptionParser
def main(args=None):
"""The main function; parses options and plots"""
# ---------- build and read options ----------
optParser = OptionParser()
optParser.add_option("-n", "--net", dest="net", metavar="FILE",
help="Defines the network to read"... | f387756ac777f624f5ccdc2e0b70d72ded646b68 | 3,632,722 |
def create_split(
dataset_builder: tfds.core.DatasetBuilder,
batch_size: int,
train: bool,
dtype: tf.DType = tf.float32,
image_size: int = IMAGE_SIZE,
cache: bool = False,
) -> tf.data.Dataset:
"""Creates a split from the ImageNet dataset using TensorFlow Datasets.
Args:
dataset_builder... | bfb9da0d16f6ef21e0f26a7bcec9b196c1358139 | 3,632,723 |
import random
def randomString(stringLength=16):
"""Generate a random hex-string of fixed length """
# """Generate a random string of fixed length """
# letters = string.ascii_lowercase + string.ascii_uppercase + string.digits
# return ''.join(random.choice(letters) for i in range(stringLength))
r... | d92985a92e9bb24ed4c405c7dc45dce9d12ff135 | 3,632,724 |
def get_uri():
"""
POST body:
{
domain: string representing the domain name
term: string or number referring to be used on composing the URI for the element
}
:return:
{
uri: string with the URI for the resource
}
"""
payload = request.json
uri = DomainUR... | c410eff64e01312a12792c8f9bdd36ef44a1e765 | 3,632,725 |
def split_in_groups(key_func, l, continuous=True, max_group_size=None):
"""
Split the list `l` into groups according to the `key_func`.
Go over the list and group the elements with the same key value together.
If ``continuous==False``, groups all elements with the same key together regardless of wh... | fc5b6d381b3111a00382f16bea15c32b495fbefd | 3,632,726 |
def delete_orderitem(request, id=None):
"""
Deleting orderitems in current order CART
"""
if request.method == "POST":
order_to_delete = OrderItem.objects.get(id=id)
order_to_delete.delete()
return redirect('create-order') | adbc9a12358bab86c44759136865a2f8a2508c26 | 3,632,727 |
import warnings
def moments_dbs(data, xi_n, t_bootstrap=0.5, r_bootstrap=500, eps_stop=1.0,
verbose=False, diagn_plots=False, sort=True):
"""Double-bootstrap procedure for moments estimator.
Parameters
----------
data : (N, ) array_like
_Numpy_ array for which double-bootstrap... | 1d812561daf3ced06d68ef069dd61ace5ce4ca5a | 3,632,728 |
def http_headers(headers=None):
"""Construct common HTTP headers from the jomiel options.
Args:
headers (dict): additional headers to use
Returns:
A headers dictionary ready to be used with `requests`
"""
result = {"user-agent": opts.http_user_agent}
if headers:
result... | 5dc0cf25778c5950d0c70966606385d95f8c3a85 | 3,632,729 |
import requests
from bs4 import BeautifulSoup
def stock_classify_board() -> dict:
"""
http://vip.stock.finance.sina.com.cn/mkt/
:return: 股票分类字典
:rtype: dict
"""
url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodes"
r = requests.get(url)
da... | 258b9315f5d8d854aaf891ff6d35ba55d5a06b31 | 3,632,730 |
def compute_rgroup_dataframe(pdb_df: pd.DataFrame) -> pd.DataFrame:
"""Return the atoms that are in R-groups and not the backbone chain.
:param pdb_df: DataFrame to compute R group dataframe from
:type pdb_df: pd.DataFrame
:returns: Dataframe containing R-groups only (backbone atoms removed)
:rtype... | fe6bef0821e5c3230c961485144ab77c2cede770 | 3,632,731 |
from typing import Dict
def find_requests(spec: Dict) -> Dict:
"""
Returns a Dict like:
{
'pets': {
'create_a_pet': {'method': 'POST', 'url': 'http://petstore.swagger.io/v1/pets'},
'info_for_a_pet': {'method': 'GET', 'url': 'http://petstore.swagger.io/v1/pets/:petId'},
... | 1efd26b8819b90e5371a409c56d11a46ee887e93 | 3,632,732 |
import collections
from typing import OrderedDict
import six
def flatten_ordered(dd, separator='_', prefix='', is_list_fn=lambda x: isinstance(x, list)):
"""Flatten a nested dictionary/list
Args:
separator: how to separate different hirearchical levels
prefix: what to pre-append to the function
... | 4475f613d8b482c31a2fe557355506a5479a9ff3 | 3,632,733 |
def error_internal_server(error):
""" Return default JSON error message for unhandled Internal Server error """
return APIError.default_handler(APIInternalError) | 9e9b543ccbb186121b79c60189deb35e192a7beb | 3,632,734 |
def apply_functions(lst, functions):
"""
:param lst: list of values
:param functions: list of functions to apply to each value.
Each function has 2 inputs: index of value and value
:return: [func(x) for x in lst], i.e apply the respective function to each
of the values
"""
assert len(ls... | 679a2219008e438249e1227d5aab6529019c497c | 3,632,735 |
import torch
def plot_graph(
codepath,
filename="graph",
directory="./",
code2in = [0,1,0,1,2,1,2,3,2,3],
code2out = [0,0,1,1,1,2,2,2,3,3],
):
""" Plot the final searched model
Args:
codepath: path to the saved .pth file, generated from the searching script.
arch_code_a: ar... | 45290fa6254855157b023a172beae242240046ad | 3,632,736 |
def rotate_image(image, rotation):
"""
Rotate the image givent eh cv2 rotation code
"""
return cv2.rotate(image, rotation) | 4d341e5e2efc4d15e9b14bf557928ad4c6bcbb4a | 3,632,737 |
def location_normalize(location):
"""
Normalize location name `location`
"""
#translation_table = dict.fromkeys(map(ord, '!@#$*;'), None)
def _remove_chars(chars, string):
return ''.join(x for x in string if x not in chars)
location = location.lower().replace('_', ' ').replace('+', ' ')... | 4b8aaec23ef9763bc02fd4d3635ba930f8c3dcea | 3,632,738 |
def remove_car(garage_id, car_id): # noqa: E501
"""remove car from garage
# noqa: E501
:param garage_id: id of garage
:type garage_id: int
:param car_id: id of car
:type car_id: int
:rtype: None
"""
with get_db() as con:
cur = con.execute('''
delete from... | ab8a09f9edb027a50cd43b9f380596bc8ff56e89 | 3,632,739 |
import sys
import platform
def check_execute(command, timeout=None,
sandbox_profile=None, max_retries=1,
stdout=sys.stdout, stderr=sys.stderr,
**kwargs):
"""Check execute a given command.
>>> check_execute(['echo', 'Hello, World!'])
0
"""
if t... | d79f9d1766cd8de8a7a14948dd81e9a5ca9f1176 | 3,632,740 |
def review(items, config):
"""Reviews the incoming item and returns a Review for it
:param items: a list of items that must be `Sentence` instances.
:param config: a configuration map
:returns: one or more Review objects for the input items
:rtype: list of dict
"""
# We require a list: much... | c33e363ec66f9afa88f27db255533e22e349b5c0 | 3,632,741 |
def create(words, vector_length, window_size):
"""Create new word2vec model."""
w2vmodel = {}
for col in words.columns:
if col in words:
w2vmodel[col] = gs.models.Word2Vec([list(words[col])], min_count=1, size=vector_length,
window=window_size, seed=... | ba93628ba337cc40caa24bdc0a062c2c61933e14 | 3,632,742 |
import matplotlib as mpl
from distutils.version import LooseVersion
def aga_graph(
adata,
solid_edges='aga_adjacency_tree_confidence',
dashed_edges='aga_adjacency_full_confidence',
layout=None,
root=0,
groups=None,
color=None,
threshold_solid=None,
... | faffd062396cfadf34b7b147681bf9c7591aee31 | 3,632,743 |
def rotate(location, direction=CLOCKWISE):
"""
Find a stronghold 120 degrees clockwise or counter-clockwise from location.
location is an tuple of x and z. direction can either be CLOCKWISE or
COUNTERCLOCKWISE.
"""
location = Point(*location)
x = simplify(cos(direction) * location.x + -sin(d... | 34f98ce6171ea1cb4b488ebcc0e8686973346ae5 | 3,632,744 |
def checkWin():
"""Analyze the scores of the players and check win, return player1 or player2 as a string"""
if player1.score < player2.score:
return "player 2"
else:
return "player 1" | bf6d6ad5aca0713f63658516ce8df422a9bcc0ea | 3,632,745 |
def credits(request):
"""A view that outputs the result of a credit query."""
md = request.matchdict
model = model_from_matchdict(md)
items = items_from_matchdict(md, model)
date = date_from_matchdict(md)
return model.bulk_credits(
items,
*(s for s in md['types'].split('+') if s)... | 34c61e5ef8a29932f296e3678df8ba51b4111fb3 | 3,632,746 |
def dict_is_test(data):
"""helper function to check whether passed argument is a proper :class:`dict` object describing a test.
:param dict data: value to check
:rtype: bool
"""
return (
isinstance(data, dict)
and "type" in data
and data["type"] == "test"
and "id" in... | 320b47f8f41f42f6a6554741c9b2de38b370605a | 3,632,747 |
import string
def _replace_vars(text, param_dict):
"""
Given a block of text, replace any instances of '{key}' with 'value'
if param_dict contains 'key':'value' pair.
This is done safely so that brackets in a file don't cause an error if
they don't contain a variable we want to replace.
See ht... | 4f218a9f9df46c2535c2d3060084430b74d0cd72 | 3,632,748 |
from typing import Union
from pathlib import Path
from typing import Optional
def import_key(filepath: Union[str, PathLike[str], Path], passphrase: Optional[str] = None) -> RsaKey:
"""
Import a secret key from file.
Parameters
----------
filepath : str | os.PathLike[str] | pathlib.Path
Fi... | 40a0b12ea17ec391cb71883aa6aecb9f73fdeb0d | 3,632,749 |
from typing import Set
def GetZonesInRegion(region: str) -> Set[str]:
"""Returns a set of zones in the region."""
# As of 2021 all Azure AZs are numbered 1-3 for eligible regions.
return set([f'{region}-{i}' for i in range(1, 4)]) | e539662604eb5da2583630844dd54d11d266c827 | 3,632,750 |
def compare_3PC_keys(key1, key2) -> int:
"""
Return >0 if key2 is greater than key1, <0 if lesser, 0 otherwise
"""
if key1[0] == key2[0]:
return key2[1] - key1[1]
else:
return key2[0] - key1[0] | d134eaaa4ef8f218164be4e5bc6fced01c3de7eb | 3,632,751 |
import heapq
def merge_two_lists_heap(l1: ListNode, l2: ListNode) -> ListNode:
"""Returns a single sorted, in-place merged linked list of two sorted input linked lists
The linked list is made by splicing together the nodes of l1 and l2
Args:
l1:
l2:
Examples:
>>> l1 = linked... | 19c7507a53d6d365259f2226b008b3ad065e5f21 | 3,632,752 |
import requests
def demo():
""" Step 1 of the authentication workflow, obtain a temporary
resource owner key and use it to redirect the user. The user
will authorize the client (our flask app) to access its resources
and perform actions in its name (aka get feed and post updates)."""
# In this st... | 547114a93f44f152d6e8545c311b07ad86101441 | 3,632,753 |
def get_blast(pdb_id, chain_id='A'):
"""
Return BLAST search results for a given PDB ID
The key of the output dict())that outputs the full search results is
'BlastOutput_iterations'
To get a list of just the results without the metadata of the search use:
hits = full_results['BlastOutput_iterat... | 92a1ed6e53914e5468b491782263082a6c35b4de | 3,632,754 |
from datetime import datetime
import time
def getDayBoundaryTimeStampFromUtcTimeStamp(timeStamp, timeZoneId):
"""
get to the day boundary given a local time in the UTC timeZone.
ts is the local timestamp in the UTC timeZone i.e. what you would
get from time.time() on your computer + the offset betwen ... | e8c24c0a3ec47546cb30eaebe172bdcfd627c7c9 | 3,632,755 |
def generate_cylinder_square_array(size, porosity, segmented=True):
""" Generate a 2D periodic array of circles
:param size: length of one side of the output domain
:type size: int
:param porosity: porosity of the output domain
:type porosity: float
:param segmented: return ... | 0c8c35d6549c6335156bc475eeeef235a442a213 | 3,632,756 |
import csv
def ephemerides(file_path,
P_orb=2.644,
T_e=2455959.0039936211,
e=0.152,
P_rot=None,
phase_start=None,
Rot_phase=False,
print_stat=True,
save_results=False,
save_... | 0651616848c9fa0f20862ab00826751672a86156 | 3,632,757 |
def _GetMSBuildToolSettings(msbuild_settings, tool):
"""Returns an MSBuild tool dictionary. Creates it if needed."""
return msbuild_settings.setdefault(tool.msbuild_name, {}) | 3a2cb3e9c8910a6901be0937be18aac00d532e2b | 3,632,758 |
def _apply_color(color: str, message: str) -> str:
"""Dye message with color, fall back to default if it fails."""
color_code = AvailableColors["DEFAULT"].value
try:
color_code = AvailableColors[color.upper()].value
except KeyError:
pass
return f"\033[1;{color_code}m{message}\033[0m" | 752557dc4416c5d141169f8155f41b6847eef318 | 3,632,759 |
import os
def choice_geometry(elite):
""" Positions shapes for user selection """
geo = []
# Generate shape for selection
for i in range(6):
elite[i].evaluate()
print("Adding geometry: " + str(i))
offset = 100
offset_x = i % 3 * offset
offset_y = i % 2 * offset
... | 6379b37038d69964ae8ffc294bc0e9272b1a1636 | 3,632,760 |
import scipy
def get_mel_spectrogram(audio, pextract=None):
"""Mel-band energies
Parameters
----------
audio : numpy.ndarray
Audio data.
params : dict
Parameters.
Returns
-------
feature_matrix : numpy.ndarray
(log-scaled) mel spectrogram energies per audio ch... | 71e685ee0cf0f1359329aaf15df2a02db0f879b2 | 3,632,761 |
from pathlib import Path
def getName(value):
"""
Finds the name of a :model:`browseNet.path` or :model:`browseNet.Share`.
"""
if isinstance(value,Path):
return value.shortname
elif isinstance(value, Share):
return value.sharename
else:
return "??" | 006114fc40b75d1630ce18f55694e582711c5ee8 | 3,632,762 |
def balanced_outward(source: str, pos: int) -> list:
"""
Returns balanced CSS model: a list of all ranges that could possibly match
given location when moving in outward direction
"""
pool = []
stack = []
result = []
prop = []
prop.append(None) # Get rid of pyLint rant
def scan_... | 1c187c3db71a756ef4e983a850af2a708f021cdf | 3,632,763 |
import struct
def float_2_bytes(f, is_little_endian=False):
"""
:param f:
:param is_little_endian:
:return:
"""
# 小端数据返回
if is_little_endian:
return struct.pack('<f', f)
# 大端数据返回
return struct.pack('>f', f) | cd13cfc7179baf28cda669b2c6fccdce58c63730 | 3,632,764 |
import pathlib
def setup_pluginbase(extra_policies_path=None):
"""Sets up plugin base with default path and provided path
Args:
extra_policies_path (str): Extra path to find plugins in
Returns:
PluginSource: PluginBase PluginSource for finding plugins
"""
here = pathlib.Path(__fi... | e5a7d57a35712f1656e757c5873adc51f670a273 | 3,632,765 |
from typing import Union
from typing import List
from typing import Dict
def compute_balanced_class_weights(train_y: Union[np.array, pd.Series, List[any]]
) -> Dict[int, float]:
"""Computes balanced class weight dictionary from train targets.
The key is a index of sorted ... | f74a56cbc051c9eefbe3149d66969c9697a60977 | 3,632,766 |
import cv2
from numpy import zeros, nan
def get_frames_index_range(filename, start, end):
"""
returns a range of frames as numpy array. The indecies comply with scimage
We can then supplement the above table as follows:
Addendum to dimension names and orders in scikit-image
Image type: 2D color ... | 61e478272bff6c154f47f14744a5ca733ae373b1 | 3,632,767 |
import os
def create_job_env(profiler=False):
"""Create a dictionary that contains the jobs' environment.
The job environment is loaded at execution time and is available in
the process that runs the jobs command. This stores the values from the
current environment (usually the machine from which you... | a0a6faecc2f2ddf5495649f34372a2dab6ee2677 | 3,632,768 |
import requests
def load_SMI_data_from_Helmholtz():
"""
Downloading SMI topsoil data from helmholtz website
"""
url = "https://www.ufz.de/export/data/2/237851_SMI_L02_Oberboden_monatlich_1951_2018_inv.zip" # noqa: E501
response = requests.get(url)
return response | 854f6b2f398764b7afc89cc3b9ca3b95b2d9a345 | 3,632,769 |
import io
import json
from typing import OrderedDict
def get_yaml_test_method(test_file, expected_load_file, expected_dump_file, regen=False):
"""
Build and return a test function closing on tests arguments and the function
name.
"""
def closure_test_function(self):
with io.open(test_file... | 0c58a5a9f62dd9a343ecdfe1bbdd0fbc2d847698 | 3,632,770 |
import glob
import os
import logging
def read_date_dirs(dpath='.',dir_filter='*',
expected_date_format='%Y%m%d',
reader=pd.read_csv,
ext='csv',
verbose=False,
**kwargs):
"""Wrapper around pandas read_csv() or data reade... | 9cb628c54da4eade2d81a018bdd913f41fa7a313 | 3,632,771 |
import os
def find_wfss_config_filename(pathname, instrument, filtername, mode):
"""Construct the name of the WFSS configuration file given instrument parameters
Parameters
----------
pathname : str
Path where the configuration files are located
instrument : str
Instrument name (... | eb0b7cca8e0715d28dc16bd90b90d357ea612cba | 3,632,772 |
def create_mosaic_normal(out_img, maximum):
"""Create grayscale image.
Parameters
----------
out_img: numpy array
maximum: int
Returns
-------
new_img: numpy array
"""
new_img = np.array(
[np.hstack((
np.hstack((
np.flip(out_img[i, :, :], 1).T... | 8a4fa8e64f7c95f0e4c7867626f4c18e23d59250 | 3,632,773 |
def notices_for_cfr_part(title, part):
"""Retrieves all final notices for a title-part pair, orders them, and
returns them as a dict[effective_date_str] -> list(notices)"""
notices = fetch_notices(title, part, only_final=True)
modify_effective_dates(notices)
return group_by_eff_date(notices) | 8454ba063f2f31c57cc91fc5fc5eee771856a54c | 3,632,774 |
import os
def build_markdown_cpp_cell(cell):
"""
Save the C++ source code and try to build it
"""
# Comment out ```'s
txt = cell['source'].replace('```', '// ```')
cpp_file_name = get_filename_in_second_line(txt)
if not cpp_file_name:
# obtain temporary file name
cpp_file... | 6edd4ca0be3555c45eece30a47100ec9b71704c1 | 3,632,775 |
def compute_kdtree_and_dr_tractogram(tractogram, num_prototypes=None):
"""Compute the dissimilarity representation of the target tractogram and
build the kd-tree.
"""
tractogram = np.array(tractogram, dtype=np.object)
print("Computing dissimilarity matrices...")
if num_prototypes is None:
... | ff5ee28c628be38e51ac90e0519e2373b52aa739 | 3,632,776 |
def substitute(dictionary, variables, model_context, validation_result=None):
"""
Substitute fields in the specified dictionary with variable values.
:param dictionary: the dictionary in which to substitute variables
:param variables: a dictionary of variables for substitution
:param model_context: ... | 95cafec2bfb3781272f4569becec60cab835d8ca | 3,632,777 |
import os
def get_status():
"""
Get status of working copy, return tuple of
(changed_paths, new_paths, deleted_paths).
"""
paths = set()
for root, dirs, files in os.walk('.'):
dirs[:] = [d for d in dirs if d != '.git']
for file in files:
path = os.path.join(root, fi... | 1cd531518b2bc129547dc9e445d0aff32d950466 | 3,632,778 |
def batch_query_entrez_from_locus_tag(locus_tag_list):
""" convert a list of locus tags to list of entrez ids
Keyword arguments:
locus_tag_list: a list of locus tags
"""
mapping_dict = {}
id_list = list(set(locus_tag_list))
# initiate the mydisease.info python client
client = get_client(... | 626719688e3164f1b692dc68a3761928f89fcefb | 3,632,779 |
def gather_2d(params, indices):
"""Gathers from `params` with a 2D batched `indices` array.
Args:
params: [D0, D1, D2 ... Dn] Tensor
indices: [D0, D1'] integer Tensor
Returns:
result: [D0, D1', D2 ... Dn] Tensor, where
result[i, j, ...] = params[i, indices[i, j], ...]
Raises:
ValueError... | 81f09fdca8e2330352e839da2f77b7320651bfaa | 3,632,780 |
def updateUserDetails(request, user_id):
"""
Update user details view
depending on is_admin flag, admin profile is either created or deleted.
"""
user = get_object_or_404(User, pk = user_id)
user_serializer = UserSerializer(user, data = request.data)
if user_serializer.is_valid():
... | ade65f5834f0e278221a3b251fdb90567b28d78a | 3,632,781 |
def png_load(pngfile):
"""
Load a PNG file. Returns a numpy matrix with shape (y, x, 3)
png = png_load(pngfile)
pix = png[4, 5]
r, g, b = pix
:param pngfile: the path of the png file
:return: a numpy array of shape (y, x, 3)
"""
#backends = [_pil_load, _pypng_load]
backends = [... | 57670e7cb518b2f4f5c540b9bd9b0f5f227d5d6c | 3,632,782 |
def blackbody_ratio(freq_to, freq_from, temp):
""" Function to calculate the flux ratio between two frequencies for a
blackbody at a given temperature.
Parameters
----------
freq_to: float
Frequency to which to scale assuming black body SED.
freq_from: float
Frequency from which... | 33b34b9906e1ff174df375d49229229acd76a10e | 3,632,783 |
def convert_to_date(col):
"""Convert datetime to date."""
return col.date() | c6ac8febf4751e8f2c2c27fc740de286f2870cbe | 3,632,784 |
import numpy
def orthogonal_projection(all_data, training_data):
"""Projection norm of all_data over space defined by training_data
"""
o, t = subset_PCA(normalize(all_data), normalize(training_data))
norms = numpy.apply_along_axis(numpy.linalg.norm, 1, o)
return norms, o, t | 4102fdd80d61785595fbb5931aaaf5f135d2855b | 3,632,785 |
import json
import traceback
def get_iocs(prefix):
"""
Get the list of available IOCs from DatabaseServer.
Args:
prefix : The PV prefix for this instrument.
Returns:
A list of the names of available IOCs.
"""
#
try:
rawjson = dehex_and_decompress(ChannelAccess.cag... | 475a69dea9acb6f615e652fc14f0535db15ee7a3 | 3,632,786 |
import re
from typing import Counter
def perfect_match(_clipped, _seq, offset = 0, min_nt = 2):
"""
perfect match between clipped reads and breakend sequence
for whole length
min_nt : minimal nt match is better to be larger than 2,
1 nt match is 25% change by random,
2 nt match is 0.0... | 806c0b86d3f97b71c191a2c95fb77ef16bf804e2 | 3,632,787 |
from . import yaml
import gc
import numpy
def newton(
x0,
model_evaluator,
nonlinear_tol=1.0e-10,
newton_maxiter=20,
RecyclingSolver=krypy.recycling.RecyclingMinres,
recycling_solver_kwargs=None,
vector_factory_generator=None,
compute_f_extra_args={},
eta0=1.0e-10,
forcing_term... | e8e413fef00512b97dbe78cb966e0a283b50d85e | 3,632,788 |
import os
def load_images(path_to_directory):
"""Loads all images"""
images = {}
for dirpath, dirnames, filenames in os.walk(path_to_directory):
for name in filenames:
if name.endswith('.png'):
key = name[:-4]
img = pygame.image.load(os.path.join(dirpath... | 5cc71c2aeec51e1600163d34504aabf1f0b0d0ec | 3,632,789 |
def pareto_selection_diversify_ancestry(population):
"""Return a list of selected individuals from the population.
DANIEL: added comparison of lineage for each added individual. Before an inidividual is added, the lineage is
compared to the already added population. If the similarities are higher th... | 3de3c557cfe9e5a354cf92c960545f5e92bfa92a | 3,632,790 |
from typing import Optional
from textwrap import dedent
def remove_continuous_aggregation_query(viewdef: ViewDefinition) -> Optional[str]:
""" Remove a continuous aggregation policy """
if not viewdef.aggregation_policy:
return None
__query = "SELECT remove_continuous_aggregate_policy('{view_nam... | e36fdce76bc5f74992a4e25be6844be66c9b48f1 | 3,632,791 |
def stop_gradient(x):
"""
Disables gradients for the given tensor.
This may switch off the gradients for `x` itself or create a copy of `x` with disabled gradients.
Implementations:
* PyTorch: [`x.detach()`](https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach)
* TensorFlow: [`tf.... | 9103b07c78bd9e4922ab8c29c13efa77c8415095 | 3,632,792 |
def get_boundary_elevations(dataset):
"""
:param dataset: netcdf AEM line dataset
:return:
an array of layer top elevations of the same shape as layer_top_depth
"""
return np.repeat(dataset.variables['elevation'][:][:, np.newaxis],
dataset.variables['layer_top_depth'].shape... | a502a1ee923f7e5eb3f1949feb0ab6f6b8d09884 | 3,632,793 |
import argparse
def get_input_args():
"""
Retrieves and parses the command line arguments provided by the user when
they run the program from a terminal window. If the user fails to provide
some or all of the arguments, then the default values are used for the
missing arguments.
This function ... | 830f31adf1770ebcfaeb6645ce606c758f38bd0f | 3,632,794 |
async def train(
background_tasks: BackgroundTasks,
current_user: User = Depends(auth.get_current_user_and_bot),
):
"""
Trains the chatbot
"""
Utility.train_model(background_tasks, current_user.get_bot(), current_user.get_user(), current_user.email, 'train')
return {"message": "Model... | e222373598c19a83903d701d1c5492c4bc655753 | 3,632,795 |
from datetime import datetime
def get_header():
"""
It returns the Header element of the pmml.
Returns
-------
header :
Returns the header of the pmml.
"""
copyryt = "Copyright (c) 2019 Software AG"
description = "Default Description"
timestamp = pml.Timestamp(datet... | 9051b906d2fc07054f2945be6c2bdaec1e1a0167 | 3,632,796 |
def Identifiers():
"""Returns a "fake" Identifiers field.
Field expects:
"<scheme1>": "<identifier1>",
...
"<schemeN>": "<identifierN>"
"""
return fields.Dict(
# scheme
keys=SanitizedUnicode(
required=True, validate=_not_blank(_('Scheme cannot be bla... | 8357b69bbf706109292db2067fa0b145a9807c81 | 3,632,797 |
import torch
def create_edge_map(x, N=4):
"""
Creates the edge maps for the given image
Args:
x: (ndarray / Tensor, shape (N, *size))
Returns:
x: (same as input) in-place op on input x
"""
# remove the batch dimension
# TODO: could be for every image in ... | 0dfb69e8b0105c911340635142233314688f0036 | 3,632,798 |
def reject_sv(m, s, y):
""" Sample from N(m, s^2) times SV likelihood using rejection.
SV likelihood (in x) corresponds to y ~ N(0, exp(x)).
"""
mp = m + 0.5 * s**2 * (-1. + y**2 * np.exp(-m))
ntries = 0
while True:
ntries += 1
x = stats.norm.rvs(loc=mp, scale=s)
u = sta... | 1516ecc273a7cb1a215604c78a20fbf06e8b704a | 3,632,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.