content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_unicode, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case fi... | 0ce84751d3e81c976da7c0ac76a4f601cf7e5e4b | 54,200 |
def _get_grid_points_by_rotations(bz_gp, bz_grid: BZGrid, rotations):
"""Grid point rotations without surface treatment."""
rot_adrs = np.dot(rotations, bz_grid.addresses[bz_gp])
grgps = get_grid_point_from_address(rot_adrs, bz_grid.D_diag)
return bz_grid.grg2bzg[grgps] | f6815ed9201e6a11444b67601890ca5c5a841094 | 54,201 |
def lstm(xs, ms, s, scope, nh):
"""LSTM layer for policy network, using same weight and bias initialization as LSTM in reward redistribution model
Based on baselines.ppo2.policies.py; These initializations were taken directly from the redistribution model LSTM
and could be optimized;
"""
nbatch... | 336ed0b274364251abe66f6e6870023f5bbab805 | 54,202 |
def move_left(point):
"""Return a copy of `point`, moved left along the X-axis by 1.
This function returns a tuple, not a Vector2D instance, and should only be
used if performance is essential. Otherwise, the recommended alternative is
to write `point + LEFT`.
"""
x, y = point
return x - 1... | 4e06e6f0a7eb0f944c42c3952955441cf9b83728 | 54,203 |
def get_ensembl_gene(ensembl_id, ENSEMBL_REST_SERVER = GRCH37_ENSEMBL_REST_SERVER):
"""
Get gene details from name
* string
Returntype: Gene
"""
key = (ensembl_id, ENSEMBL_REST_SERVER)
if key not in known_genes:
known_genes[key] = fetch_gene_id(ensembl_id, ENSEMBL_REST_SERVER)
return known_genes[key] | d0b83377d71261fa1cfc8840c211af3ec20c5464 | 54,204 |
def list_notes_by_itinerary(itin_id):
"""serialize notes list to jsonify"""
notes_author = db.session.query(User.fname, Note.comment, Note.day).join(User)
itin_notes = notes_author.filter(Note.itinerary_id == itin_id).all()
json_notes = []
for note in itin_notes:
n_dict = {}
n_dic... | 62d3828ab7bb578a3f0a1401d82198472b0c0ff1 | 54,205 |
def set_dist_ang(a, b, dist, ang=0):
"""Returns point distance and angle away from a towards b"""
c = normalize(b - a) * dist
cr2d = rotate2D(*c[:2], ang)
cr = cr2d if len(a) == 2 else a3([*cr2d, c[2]])
return cr + a | 84b7afac6e9d5f0182f99699d240da12c932b300 | 54,206 |
def get_share_in_repo_list(request, start, limit):
"""List share in repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
repo_list = seafile_api.get_org_share_in_repo_list(org_id, username,
... | d27901b75f1bbb273bf7d1267c9f89cd3aded537 | 54,207 |
def load_data(args, device):
"""Loads the data into three different data loaders. (Train, Test, Evaluation)
Split the training dataset into a train / test dataset.
Args:
args: arguments passed to the python script
"""
train_dataset = CSVDataset(args, args.train_files, device)
... | 2644a416086de2de83854f7f76bf3642b3094f32 | 54,208 |
def check_freq(session, freq):
"""
Check the frequency of the radar with the table, hfrSystemTypes. Return the frequency id
:param session: SQLAlchemy database session instance
:param freq: Frequency floating point number
:return: ID of the appropriate system type in hfrSystemTypes table
"""
... | dfb6adbe6488ff111d6abd7ffc6f5ae16fc0d141 | 54,209 |
from typing import Generic
def yesterday_and_today():
"""Prode `date` (d) and `str` (s) versions of yesterday and today."""
d = Generic()
d.today = date.today()
d.yesterday = d.today - timedelta(1)
s = Generic()
s.today = d.today.isoformat()
s.yesterday = d.yesterday.isoformat()
result... | 559dd3d1977e8c54e2b79348d09c2c0526618815 | 54,210 |
def pix_to_sky(idx, nside):
"""Convert the pixels corresponding to the input indexes to sky coordinates (RA, Dec)"""
theta, phi = hp.pix2ang(nside, idx)
ra = np.rad2deg(phi)
dec = np.rad2deg(0.5 * np.pi - theta)
return ra, dec | 65a0e33fc2c7b89f8b686296c2b9aeba0b95e79c | 54,211 |
def stoi(x):
"""Converts strings to integers"""
if type(x) != str:
raise ValueError("Input value not a string")
try:
ans = 0
for d in x:
ans = 10 * ans + dic[d]
return ans
except:
raise ValueError("Input value not a string") | a791e2d030330f1521e4b61ede7f706d0f562786 | 54,212 |
def brightness():
"""Set brightness value for camera."""
# Catch ajax request with form data
brightness_val = 'error'
if request.method == 'POST':
brightness_val = request.form.get('brightness')
if brightness_val is not None:
app.logger.info('Form brightness submitted: %s', b... | 81faca06170c78282e32b37da8eb6d41bab2ecda | 54,213 |
from typing import List
def fraction_low_base_quality(channels: List[np.ndarray],
threshold: int = 127) -> float:
"""Gets fraction of bases that have low base quality scores in a pileup.
Args:
channels: A list of channels of a DeepVariant pileup image. This only uses
c... | bf24d61ef8485f4da8925b9a1aec88f745a76538 | 54,214 |
import os
import hashlib
def convert_deps_from_pip(dep):
""""Converts a pip-formatted dependency to a Pipfile-formatted one."""
dependency = {}
req = get_requirement(dep)
extras = {'extras': req.extras}
# File installs.
if (req.uri or req.path or is_installable_file(req.name)) and not req.vcs:... | 673ab68e80d3066bd35100071a276aae5c26efca | 54,215 |
def draw_corr(img0, pix_pos0, img1, pix_pos1, num=None):
"""
Draw matches, numpy version. Parameters are the same as draw keypoints
"""
if num is None:
inds = np.arange(len(pix_pos0))
num = len(pix_pos0)
else:
inds = np.linspace(0, len(pix_pos0), num, endpoint=False).astype(n... | 1994655337260663af424ba8450d2abdc48db2c1 | 54,216 |
from typing import Tuple
import tqdm
def calc_stft(protocol_df: pd.DataFrame, path: str) -> Tuple[np.ndarray, np.ndarray]:
"""
This function extracts spectrograms from raw audio data by using FFT.
Args:
protocol_df(pd.DataFrame): ASVspoof2019 protocol.
path(str): Path to ASVSpoof2019
Retu... | 341fb31f78974db6407c22e99bdc901e6b508ae5 | 54,217 |
import yaml
def dict_to_yaml(dict_data):
"""Return YAML from dictionary.
:param dict_data: Dictionary data
:type dict_data: dict
:returns: YAML dump
:rtype: string
"""
return yaml.dump(dict_data, default_flow_style=False) | eba7896f63d499ef6c55b057320933dc0ff86333 | 54,218 |
def snake_case_to_capital_case(string):
"""
string::str ex. this_is_an_example
return::str ex. ThisIsAnExample
"""
LOG.debug('Converting string to capital case: %s', string)
split_list = string.split('_')
capital_list = [item.capitalize() for item in split_list]
capital_case = ''.join(ca... | 0350a8a29a7b2e5d5859fb4082090f1e0444605f | 54,219 |
def fixed_variables_only_in_inequalities(block):
"""
Method to return a ComponentSet of all fixed Var components which appear
only within activated inequality Constraints in a model.
Args:
block : model to be studied
Returns:
A ComponentSet including all fixed Var components which ... | d5b5b7c4521ee2e729a18b45322f1a5b32bde27c | 54,220 |
def generate_white_pawn_attack_bb_from_square(from_square: int) -> np.uint64:
"""
Returns the white pawn attack bitboard on an otherwise empty board from the provided square
:param from_square: starting square from which to generate white pawn attacks
:return: np.uint64 bitboard representation of white ... | 1c6083e577d44cde593d91e8ce6a525e0772d839 | 54,221 |
import os
def _read(file_path):
"""
Reads a given .csv file from disk.
:return: loaded data in the form of a pandas Dataframe.
"""
return pd.read_csv(os.path.join(CURRENT_PATH, file_path)) | 4f433a82f1432c0844641db234785185efb06281 | 54,222 |
def is_subscription(service_type):
"""
check service type is subscription or empty
"""
return not service_type or service_type == SUBSCRIPTION_SERVICE_TYPE | cd480020d251ec6a90ec3a5eb9be1871ad42ad4d | 54,223 |
def _args_run_polish(args):
"""Run `pbsvp polish`"""
log.info("Running `{}`".format(POLISH_ENTRY))
log.debug('Locals={}'.format(locals()))
run_polish(genome_fa=args.genome_fa, subreads_xml_fn=args.subreads_bam, aln_fn=args.alignments_bam,
in_bed_fn=args.in_rich_bed, out_dir=args.out_dir,
... | 74e411bb9812ace865751acdfdfa973fd07bcb39 | 54,224 |
def df_to_list(df):
"""Convert a pandas DataFrame values to a list of lists.
Args:
df (pandas.DataFrame): A DataFrame to convert to a dictionary.
Returns:
list: A list of lists
"""
return [df[column_name].values.tolist() for column_name in df.columns] | 6bff41874f195783ee67a859f203f6fb20969269 | 54,225 |
def load_config(config_file_name):
"""Load the JSON configuration file and return its structure."""
try:
with open(config_file_name, 'r') as f:
retval = json.load(f)
return retval
except Exception as e:
print "ERROR reading config file:"
raise e | a0cb80162c8cd45f56e4d348f8aeb0d6b159f50e | 54,226 |
def findNearestDate(date_list, date):
"""
Find closest datapoint of each uppermost sensor in time window.
Adapted from https://stackoverflow.com/a/32237949/3816498 .
Parameters
----------
date_list : array-like
List of dates
date : datetime
The date, to which the nearest da... | 431f93212e6ffeddb994e727d94db8ccfe67315c | 54,227 |
from functools import reduce
def prod(stuff):
""" prod(stuff):
compute the product (i.e. reduce with '*') of the elements of 'stuff'.
'stuff' must be iterable."""
return reduce(lambda x, y: x*y, stuff) | 5ddaaaced8c187018d9a5113ea3a91a21deb6e0b | 54,228 |
def GetIonPositions(names_and_pos, ion_input):
"""
input: names_and_pos dict<string, Vector3>: dictionary that contains the position of each labelled element present.
input: ion_input dict<string, Ionic>: dict of Ionic class wich contains info with no radius value
output: dict<string, Vector3>: refined ... | 51cbcdd34256546bc37414dd5ec5fb06d0af0035 | 54,229 |
import requests
from bs4 import BeautifulSoup
def get_archive_posts():
"""Get post links from codingdose archive."""
base_url = 'https://codingdose.info/archives/'
paging_url = base_url + 'page/'
ordered_list = []
for page in range(1, get_num_pages()):
url = base_url if page < 2 else pagin... | f0735432a466875242d6562f1b7319865ea0c00f | 54,230 |
def normalize(X):
"""Normalize the dataset"""
scaler = MinMaxScaler()
scaler.fit(X)
return scaler.transform(X) | 1be9088497d10d52ff36798d985c402e76d05a1d | 54,231 |
def project_3d_to_2d(points3d, intrinsics):
"""Projects 3d points, (in the Google format) to pixel
location using the intrinsic matrix. The intrinsic matrix
must be scaled if the image is scaled.
Args:
points3d ([list]): List of 3D points in camera frame.
intrinsics ([np.array]): Intrin... | 1d8f449358fc51782332b5945e952c683ece73c5 | 54,232 |
from typing import List
from typing import Dict
def compute_images2labels(images: List[str], labels: List[str]) -> Dict:
"""Maps all image paths to a list of labels.
Args:
images (List[str]): The list of image paths.
labels (List[str]): The list of labels.
Returns:
Dict: The mapp... | 1af99cd93bea7530857502665d4ce388a9d8f9ba | 54,233 |
import difflib
def similarString(inString, inList):
""" check if there is an object that resembles the given string in the list
:param inString: string to check for
:type inString: string
:param inList: list of strings to choose from
:type inList: list
:return: the string that resembles the i... | c61b9a767b0cd1fa063b1c23a45b3e4063a7fa55 | 54,234 |
from typing import Optional
def __validate_enabled_entity(request: Request, db_issue: Optional[Issue], entity, entity_id):
"""
Get entity-id from path and query it in the database. Check if it belongs to the queried issue and if it is disabled.
:param request:
:param db_issue:
:param entity:
... | 780c433d11996795c22eca492edb7675801a6665 | 54,235 |
import sys
def get_custom_report_table(pdb_ids, columns, log=sys.stdout,
prefix="dimStructure", check_for_missing=True):
"""Given a list of PDB IDs and a list of attribute identifiers, returns a
Python list of lists for the IDs and attributes."""
assert (len(columns) > 0)
if (len(pdb_ids) == 0) : return [... | b625d3c2eb1a2dffbf0b1be617ba67356af6f551 | 54,236 |
def _has_constant_term(p, x):
"""
Check if ``p`` has a constant term in ``x``
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import _has_constant_term
>>> R, x = ring('x', QQ)
>>> p = x**2 + x + 1
... | 76bd944244a72d84876441b9c1b4bbd4e2a9f02a | 54,237 |
def values_to_percent_growth(values):
"""
Turn a series of values into a series giving the growth from one period to the next
:param values: a list of floats
:return: another list, of length one less than values
>>> rate = 0.05
>>> n_periods = 5
>>> initial_investment = 100
>>> values =... | 33cf3a10e2c13a0365b31d8a1b77e4a409de6ba8 | 54,238 |
def handle_testing_state(state, session, guest, round_num):
"""TODO: Fix round_num"""
if state not in {State.TESTING, State.WAITING}:
raise ValueError("Unexpected to handle state {}".format(state))
if round_num is None:
round_num = 0
round_num = int(round_num)
if state == State.TES... | 76b4aef0b47cae54adcad6e490970ea93990c83d | 54,239 |
from typing import Dict
def get_listing_by_url(conn: "SQLite connection", url: Dict[str, str]):
"""Collect records by URL
Args:
conn (sqlite connection): connection to zillow db
url (Dict[str,str]): dictionary with key='url' and value=url string
"""
c = conn.cursor()
c.execute(
... | 2fd1c702f694cf1b40ffb4cdb74c8f2329dd3d94 | 54,240 |
import re
def AbsolutePathToModule(file_path: str) -> str:
"""Determine module name from an absolute path."""
match = re.match(r'.+\.runfiles/phd/(.+)', file_path)
if match:
# Strip everything up to the root of the project from the path.
module = match.group(1)
# Strip the .py suffix.
module = m... | 81c51cb3227ce11bda9a1f90759cdfd1770ea715 | 54,241 |
def sum_counts(fname, R1=False):
"""Collect the sum of all reads for all samples from a summary count file (e.g. from collect_counts)"""
count = 0
with open(fname, 'r') as infh:
for line in infh:
l = line.split()
if R1:
if l[2] == "R1":
cou... | 6ce7e156e1100f3106836e0b34caf6750baa18e1 | 54,242 |
import numpy
def vappressure(temp):
"""Approximate vapour pressure over ice.
Approximate the vapour pressure over ice at the given temperature.
:arg float temp: Temperature in K.
:returns: Vapour pressure in Pa.
:Examples:
>>> vappressure(270.)
470.061877574
"""
... | 115e2bbb92d26428122da141cf8444d2c214aebe | 54,243 |
def parse_tags(tag_list):
"""
>>> 'tag2' in parse_tags(['tag1=value1', 'tag2=value2'])
True
"""
tags = {}
for t in tag_list:
k, v = t.split('=')
tags[k] = v
return tags | 962c7ba737c56b46f9783912c528e4da6e4ee145 | 54,244 |
def resnetv1(num_classes=[1000]):
"""Encoder for instance discrimination and MoCo"""
return resnet50(num_classes=num_classes) | 972bc4823271493f76a52aa8db62146b69c6cc39 | 54,245 |
def radial_distrubtion_pair(p1, p2, bins=100, range=None, weighted=False, dim=None):
"""
Compute a pair radial distribution function. Returns (counts, bin_edges)
Arguments:
p1[T,N1,ndim] particle group 1 positions
p1[T,N2,ndim] particle group 2 positions
bins nu... | 100436a6c0caefbb721d8c07e0b8b405d9b0749c | 54,246 |
from typing import Any
from typing import Dict
from typing import Union
from typing import AsyncIterable
from typing import cast
from typing import Awaitable
async def create_source_event_stream(
schema: GraphQLSchema,
document: DocumentNode,
root_value: Any = None,
context_value: Any = None,
vari... | 8c2f36a8fe476e4e7fb77fdbbec7bf2e271fcc2b | 54,247 |
import os.path
def relative(src, dest):
""" Return a relative path from src to dest.
>>> relative("/usr/bin", "/tmp/foo/bar")
../../tmp/foo/bar
>>> relative("/usr/bin", "/usr/lib")
../lib
>>> relative("/tmp", "/tmp/foo/bar")
foo/bar
"""
if hasattr(os.path, "relpath"):
r... | b048175956a90566f7dd324821a71ace5e4ebe0b | 54,248 |
def unread_count_for(user):
"""Returns the number of unread messages for the specified user."""
return InboxMessage.objects.filter(to=user, read=False).count() | 0ea68b9f1baf7bde7c45e91a4a2555c394fcde7f | 54,249 |
def is_available():
# type: () -> bool
"""Returns whether visualization is available or not.
.. note::
:mod:`~optuna.visualization` module depends on plotly version 4.0.0 or higher. If a
supported version of plotly isn't installed in your environment, this function will return
:obj... | 23d44a26e50508b8b12e43fca725d1ee8c88e7fe | 54,250 |
def coerce_bool(value):
"""Coerce a string to a bool, or to None"""
clean_value = str(value).strip().lower()
if clean_value in ["yes", "1", "true", "t"]:
return True
elif clean_value in ["no", "n0", "0", "false", "f"]:
return False
elif clean_value in ["", "na", "n/a", "none"]:
... | dd979b73717b2c86fe28cf7d1bdcc89020eda163 | 54,251 |
import os
import pickle
def setup_oath(token_path, client_path):
"""
Path containing token.pkl and client_secret.json respectively.
"""
# Set up credentials
scopes = ['https://www.googleapis.com/auth/calendar']
# Token generated after first time code is run.
if os.path.exists(token_path):... | 99fbb8058280687f5e86970c48322ade22dd8464 | 54,252 |
def gen_points_GMM(optNK, optCP, optPT, time, numClusters):
"""Generates points from a scikit-learn GMM object for a fit NK, CP and PT"""
GMM = GaussianMixture(n_components=optNK.size, covariance_type="full")
precisions = covFactor_to_precisions(optPT)
means = tl.cp_to_tensor((None, np.asarray(optCP, dt... | ad82e782ea93641872cf029da3ac8d78559d3b31 | 54,253 |
def expand_mask_targets(masks, mask_class_labels, resolution, num_classes):
"""Expand masks from shape (#masks, resolution ** 2)
to (#masks, #classes * resolution ** 2) to encode class
specific mask targets.
"""
assert masks.shape[0] == mask_class_labels.shape[0]
# Target values of -1 are "don't... | e68fa5f5b9c42fcdd6658e27c2d4a63d51760645 | 54,254 |
import torch
def supervised_loss(R_tgt_src_pred, t_tgt_src_pred, batch, config, alpha=10.0):
"""This function computes the L1 loss between the predicted and groundtruth translation in addition to
the rotation loss (R_pred.T * R) - I.
Args:
R_tgt_src_pred (torch.tensor): (b,3,3) predicted rotat... | b98b32c6cc8c0ecb1fde50d531e4d3479716bab1 | 54,255 |
import numpy
def smooth_data(indices_, tag_counts_, sigma=20, width=120, size=None):
"""
#sigma = 20
#width = 120
#epsilon = 0 #some minimum peak height
#size, epsilon = data_size, minimum_peak_size
"""
if size is None:
size = max(indices_)
lo, hi, normal = normal_function... | ba7c8399f7516499cb3987acc82b1c23fa550178 | 54,256 |
def count_consonants(string):
""" Function which returns the count of
all consonants in the string \"string\" """
consonants = "bcdfghjklmnpqrstvwxz"
counter = 0
if string:
for ch in string.lower():
if ch in consonants:
counter += 1
return counter | 4a852b3ec9f8f660d71dde547cbffb0c25b1e209 | 54,257 |
import socket
def in6_isaddrTeredo(x):
"""
Return True if provided address is a Teredo, meaning it is under
the /32 conf.teredoPrefix prefix value (by default, 2001::).
Otherwise, False is returned. Address must be passed in printable
format.
"""
our = inet_pton(socket.AF_INET6, x)[0:4]
... | e7931d4250c119018d69fd4e257f5491fd3a46b8 | 54,258 |
def get_resized_raster_8chan_image(image_id, band_rgb_th, band_mul_th):
"""
RGB + multispectral (total: 8 channels)
"""
im = []
fn = train_image_id_to_path(image_id)
with rasterio.open(fn, 'r') as f:
values = f.read().astype(np.float32)
for chan_i in range(3):
min_va... | 51c259c3628f1c356f9d4f515cb454f5c91a1504 | 54,259 |
def calculateDailyResult_init():
"""主函数,供其他python程序进行模块化程序初始化调用"""
reload(ADRB)
# 创建回测引擎
engine = BacktestingEngine()
# 设置引擎的回测模式为K线
engine.setBacktestingMode(engine.BAR_MODE)
# 设置产品相关参数
engine.setSlippage(0) # 股指1跳
engine.setRate(0) # 万0.3
engine.setSize(... | 392741b76c482bfa6794025dabf1e16e2ae68018 | 54,260 |
import itertools
def bonds_getting_formed_or_broken(rsmi, psmi, n_atoms):
"""
Based on the reaction and product structure, the bonds that are
fomed/broken are singled out for contraintment
the difference in the afjacency matric tells whether bond has been formed
(+1) or bond is broken (-1)
"""... | 9bab5c5a155c0b926b42f840d9834a9c4e63f9f7 | 54,261 |
import tqdm
from io import StringIO
def write_msp(all_preds_in, peprec_in, output_filename='MS2PIP_Predictions',
write_mode='wt+', unlog=True, return_stringbuffer=False):
"""
Write MS2PIP predictions to MSP spectral library file.
"""
def write(msp_output):
if use_tqdm & len(spec_ids) > 100000:
spec_ids... | 14b722413135f07ba1bbbb75d2be09035b1036e4 | 54,262 |
from typing import Optional
from typing import List
from typing import Dict
from typing import Any
async def votes_by_comment(
req: Request,
res: Response,
comment_ID: int,
limit: Optional[int] = 20,
offset: Optional[int] = 0,
sort: Optional[str] = "id:asc",
) -> Optional[List[Dict[str, Any]]]... | db6560d99c1c656552b203f09e34ce8f38677062 | 54,263 |
def retrieve_context_path_routing_constraint_requested_capacity_bandwidth_profile_committed_burst_size_committed_burst_size(uuid): # noqa: E501
"""Retrieve committed-burst-size
Retrieve operation of resource: committed-burst-size # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:rtype: Capac... | 708519c1c6a7ace71c07b7371495aa0d1eca438f | 54,264 |
def _create_file(my_data, sheet_name):
"""Create .xlsx file in memory."""
df = pd.DataFrame(my_data[1:], columns=my_data[0], index=None)
file = BytesIO()
with pd.ExcelWriter(file, date_format='YYYY-MM-DD', mode='w', engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name=sheet_name, na_rep='', index=False)... | 170b14c0fc1a9ea09517c85c1c455477af701873 | 54,265 |
def get_symbol(parent_node):
"""Fetches the node tag value for 'printSymbol'"""
def traverse(node):
while node != Node.TEXT_NODE:
if len(node.childNodes) != 0:
traverse(node.childNodes[0])
else:
return get_name(parent_node)
return node.data... | 2fcce6214be1807117b76ee25410dce84f837b8f | 54,266 |
def compute_point_area(surf, cell_area=None, area_as='one_third'):
"""Compute point area from its adjacent cells.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
cell_area : str, 1D ndarray or None, optional
Array with cell areas. If str, it must be in the cell... | abbac6604754c9828daa89b7231cb88de8c695f7 | 54,267 |
from urllib import quote_plus
def getLogoutlink():
"""Return the HTML required to clear and expire the current OAuth2 token."""
u = ''
host = request.headers['Host']
if session and 'u' in session:
u = session['u']
elif request.args and 'u' in request.args:
u = request.args.get('u')
if u:
u = q... | 8ed62dbd877b021e71a8e2640c1f91f9af853443 | 54,268 |
def run_pyscf(molecule,
run_scf=True,
run_mp2=False,
run_cisd=False,
run_ccsd=False,
run_fci=False,
verbose=False):
"""
This function runs a pyscf calculation.
Args:
molecule: An instance of the MolecularData or Pys... | d45c366d8a5baa1e020dd6c87d54b927369993b9 | 54,269 |
def soft_contingency_table(resp1, resp2):
"""Compute the soft contingency table for two responsibility matrices
Args:
resp1 (numpy array): N x K_1 responsibility matrix - each row is a probability
vector for one of the N items belonging to each of K_1 modes
resp1 (numpy array): ... | 50ee20e05755d320fe9f130a6ca57728d1e1b5ad | 54,270 |
from typing import Optional
def is_opt(typ) -> bool:
"""
Test if the type is `typing.Optional`.
>>> is_opt(Optional[int])
True
>>> is_opt(Optional)
True
>>> is_opt(None.__class__)
False
"""
args = type_args(typ)
if args:
return typing_inspect.is_optional_type(typ) ... | a467d685596fe4ab1a0431b36d5a5e70f3901659 | 54,271 |
from typing import Tuple
from pathlib import Path
import sys
def filter_remove_large_objs(
zarr_grp_name: str,
parsed_raw_data_fpath: str,
processing_parameters: dict,
dark_img: np.ndarray)-> Tuple[Tuple[np.ndarray,np.ndarray],dict]:
"""Function used to mask large objects (ex. lip... | 24d2b28f82196ff727d55acf2e95118f6abae3f5 | 54,272 |
def on_blue(string, *funcs, **additional):
"""Text background color - blue. (see _combine())."""
return bg_blue(string, *funcs, **additional) | 442ee4a9d175815fe09b2a76d8b828cedfa03790 | 54,273 |
def allowed_request_lot_filters(lot_filters):
"""Create a set of (name, value) pairs for all form filters."""
filters = set()
def recursive_search(filters):
more_filters = set()
for f in filters:
more_filters.add((f['name'], f['value']))
children = f.get('children')... | 1b265e0233e08d0cab4248f28424b5b26ad28340 | 54,274 |
def render_error_response(
description: str,
status_code: int = status.HTTP_400_BAD_REQUEST,
content_type: str = "application/json",
) -> Response:
"""
Renders an error response in Django.
Currently supports HTML or JSON responses.
"""
resp_data = {
"data": {"error": description... | a79f8f7b02c677caaf3ed2f55ca6336ef57923e1 | 54,275 |
def decode_token(token):
"""
Decode token but don;t check the signature
:param token:
:return decoded token:
"""
return jwt.decode(token, verify=False, algorithms=[__algorithm__]) | 9a1c4152d47976c26b94ecd859faa5ec2c8be7d0 | 54,276 |
import random
import time
import threading
def test_ps_s3_notification_push_http_on_master():
""" test pushing http s3 notification on master """
if skip_push_tests:
return SkipTest("PubSub push tests don't run in teuthology")
hostname = get_ip()
zones, _ = init_env(require_ps=False)
real... | 87c0862e795ac025075aaa448b75934e8cc1e608 | 54,277 |
def FindPosition(point, points):
"""Determines the position of point in the vector points"""
if point < points[0]:
return -1
for i in range(len(points) - 1):
if point < points[i + 1]:
return i
return len(points) | 11ccabcade65053ccfa6751813d90a0eeaccc339 | 54,278 |
def PARTE_ELSE():
"""
PARTE_ELSE :
else COMANDO
| e
"""
global current_token, tabela, pilha_tipos
if current_token['token'] == 'else':
getSimbol()
if not COMANDO(): return False
else:
return True # vazio
return True | 5e9722241fca29744222ed81b8bc8da1e741262a | 54,279 |
def _check_if_StrNotBlank(string):
"""
check if a sting is blank/empty
Parameters
----------
Returns
-------
: boolean
True if string is not blank/empty
False if string is blank/empty
"""
return bool(string and string.str... | e5de1d902f8e3931d23e04c6ba825b17d90e8d1d | 54,280 |
def createRectangle(image=None,topLeftPoint=None,bottomRightPoint=None,color=(255,255,255),lineThickness=3,fill=False,fillColor=None):
"""
Creates a rectangle on an image
Arguments:
image = 3D Numpy array; image on which the rectangle has to be created
topLeftPoint = (x,y); top left point of... | 632990a633365bb0debe786ae6a1a195ba90154f | 54,281 |
def confirmedPattern(passW,pat):
"""
Checks if the password has the right pattern
"""
if(len(passW)<pat.min_length or len(passW)>pat.max_length):
return False
if(isStatusChecked(pat.numbers,hasNumber(passW))==False):
return False
if(isStatusChecked(pat.capital,hasCapitalLetters(p... | bcd1c6c2cf2f34cbed197dd3c25dfd1d6c4d5db9 | 54,282 |
from math import asin, atan2, sqrt, degrees
def normal2SD(x,y,z):
"""Converts a normal vector to a plane (given as x,y,z)
to a strike and dip of the plane using the Right-Hand-Rule.
Input:
x: The x-component of the normal vector
y: The y-component of the normal vector
z: The z-com... | 6b8bcfb9444352f8722aa1742909544202fa32d9 | 54,283 |
import re
def parse_date_string(s):
"""Attempt to parse the expression as a simple date string."""
# https://en.wikipedia.org/wiki/ISO_8601
y = r'(\d\d\d\d)'
m = r'(\d\d)'
d = m
# wk = r'W' + d
# wd = r'(\d)'
# yd = r'(\d\d\d)'
# def groups(*strings, sep='-'):
# it = (f'({... | 86f37b24f3df21863888924fdc0a6098dbc2f56c | 54,284 |
import logging
import timeit
def run_query(**kwargs):
"""
Takes query name, syntax, and iteration count and calls the
execute_query function for each iteration. Reports total, iteration,
and exec timings, memory usage, and failure status.
Kwargs:
query(dict):::
nam... | 006c57d8776ab7add56e2fb0bcb52cea85bcb754 | 54,285 |
import multiprocessing
def summarize_target_per_regulator(genes, motif_peaks, motif_information, num_workers=None, debug=False,
by_chromosome=True, silent=False):
"""
Process a large dataframe of motif hits into a dataframe with the best hit for each regulator-target pair
... | f19e8e5726564b277a291ae507c47c328528484c | 54,286 |
def append_result(results, result_hash, item):
"""Append to results, creating an index if needed."""
if result_hash not in results:
results[result_hash] = [item]
else:
results[result_hash].append(item)
return results | 1b2af69ad291f885a8f52ce95ba7e0d82792e835 | 54,287 |
def rotateToHome(x, y):
"""Rotate to the home coordinate frame.
Home coordinate frame starts at (0,0) at the start of the runway
and ends at (0, 2982 at the end of the runway). Thus, the x-value
in the home coordinate frame corresponds to crosstrack error and
the y-value corresponds... | 4d4c5cd5a3e5186d81bff60266c99128ad8a9d51 | 54,288 |
def utc_time(ms):
"""return UTC format time"""
return dt.datetime(1970, 1, 1) + dt.timedelta(milliseconds=ms*100) | 5b7089098ec9b50d6c2f6275200af6f959708e30 | 54,289 |
from typing import Sequence
from typing import Union
from typing import Any
from typing import Optional
def cli_args(args: Sequence[str]) -> ToxIniFmtNamespace:
"""Load the tools options.
:param args: CLI arguments
:return: the parsed options
"""
parser = ArgumentParser()
parser.add_argument(... | 3d57de8f318b87593cea36118e78ad07751e335d | 54,290 |
import os
import yaml
def load_requirements():
"""Loads requirements yaml from s3 and updates
requirements in requirements table along with
various other configs"""
s3_response = client_s3.get_object(Bucket=requirements_bucket, Key=os.getenv('REQUIREMENTS_FILE_PATH'))
requirements_file = yaml.safe... | bff8798fdf3bc59c1d7ad36d138b3ad959378a57 | 54,291 |
import ctypes
def FindFirstVolumeMountPoint(volume_name):
"""Find the first volume mount point which the system recognises.
If none is found, raise x_kernel32. Otherwise return the
search handle and the volume mount point name.
"""
volume_mount_point_name = ctypes.create_unicode_buffer(" " * VOLUM... | 0c8ed0f47c9a041ce871dd09980daaf21bcc5318 | 54,292 |
def uniq(seq):
""" the 'set()' way ( use dict when there's no set ) """
return list(set(seq)) | e8136a633fdf08d7c79e8d47b8c90dc2409e9d2f | 54,293 |
def compute_angles(v1: ndarray, v2: ndarray, axis: int = -1) -> ndarray:
"""
Computes angle cosines between sets of vectors.
Parameters
----------
v1
v2
Sets of vectors.
axis
Dimension to sum over.
Returns
-------
A numpy array with angle cosines.
"""
re... | e55928c10c47f098a0883ccf3d2c6577d1f0e3c7 | 54,294 |
def decorator(d):
"""Make function d a decorator: d wraps function fn."""
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d | 4a2ae600ef6952b6829d275b415b3ef98514a37e | 54,295 |
def plot_surface(trimesh):
"""
Plots a surface over a matplotlib Triangulation.
Assumes that the height of the surface has been stored in an attribute 'z'
on the trimesh object.
"""
fig,ax = plt.subplots()
ax = fig.gca(projection='3d')
polycollection = ax.plot_trisurf(trimesh, trimesh.... | 34c5f83674966eb13a94771215d3cb7f78565edf | 54,296 |
import csv
import random
def get_prioritized_county_list():
"""the scraper prioritizes its work such that counties with less recorded
information are addressed before counties with more information. This is
accomplished by dividing the counties into quartiles based on an estimate
of the amount of info... | e9962949026c6b1b2a969dfb27a0fc62c5b66325 | 54,297 |
from typing import Tuple
from typing import Union
from typing import List
from typing import Optional
def gen_rand_ddf(
batch_size: int,
image_size: Tuple[int, ...],
field_strength: Union[Tuple, List, int, float],
low_res_size: Union[Tuple, List],
seed: Optional[int] = None,
) -> tf.Tensor:
""... | 17cc8e7af0777aa1a8ae6b8a6f4cd315e3f1d9f4 | 54,298 |
def sanitize_codes(codes):
"""
Sanitize codes by splitting and removing unnecessarsy characters
Params:
codes (list): target codes
Returns: the sanitized codes
"""
codes = codes.split(';')
codes = [sanitize_code(code) for code in codes]
return codes | 503b41ee015cc9c5c642e9151c1ce60ba84eb914 | 54,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.