content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def all_boolean (phrase):
"""Returns TRUE if all elements of <phrase> are boolean"""
if not isinstance(phrase,list):
return False
for x in phrase:
if not isinstance(x,bool):
return False
return True | eaec8cae03041d5c8b2e7d4af0c2b4e373bfaa4c | 68,900 |
def get_visualized_skeleton(img: np.ndarray, skeleton: SkeletonBase, min_limb_score_to_show: float = 0.4):
"""
Draws the skeletons joints and limbs in the image.
:param img: The original image
:param skeleton: The skeleton to be visualized
:return: A copy of the image with the visualized skeleton
... | 775f3845d47e00491d9f1161ed7cc11b276d69ee | 68,901 |
def get_slips(read, slips, reference):
"""
Return a list of slips from the alignment with the most non-templated SNPs explained by Polymerase slippage events.
:param read:
:param slips:
:param reference:
:return:
"""
results_per_aln = []
for aln in read.alns:
nontemplated_tf ... | f07c5d262365ca3c7ede179d5128b3e121040380 | 68,902 |
def __get_best_matching_chain(node, lineno):
"""
Get the best matching chain.
"""
result = []
while node and __get_line(node) <= lineno:
result.append(node)
node = __get_best_matching_child(node, lineno)
return result | 1946d76f2a61bb406bc055ac7d082e44eeec2c69 | 68,903 |
def frames_to_secons(frames, framerate):
"""
Returning secons.
Args:
frames (int): frame
framerate (flaot): frame rate
Returns:
float: second value
"""
rt = _ot.from_frames(frames, framerate)
return _ot.to_seconds(rt) | e2c01021c909e7dd7260a4f494ba0af50dda0817 | 68,904 |
import re
def reverse_url(url):
"""
>>> reverse_url("http://www.face.bnl.gov/FACEDailyReports/Facts_I/Archive/03132003/ArchivePage.htm")
'gov.bnl.face.www.facedailyreports.facts_i.archive.03132003.archivepage.htm'
"""
components = urlsplit(url)
hostname = components.netloc.partition(':')[0]
... | cfc5e636d6f545d8b57eff8abb0eb01343d3fa36 | 68,905 |
import time
def tprint(string, dt=1, output=False):
""" Print progress of a loop every dt seconds."""
if (time.time() - tprint.time) > dt:
print(string)
tprint.time = time.time()
if output:
return True
else:
return
else:
if output:
... | c6edad145fdab2e5612bdecdd562f44859d9feda | 68,906 |
def in_range(length, start=None, end=None):
"""Return if start and end are between [0, length)"""
if start is None and end is None:
return False
elif start is not None and end is None:
end = start
elif end is not None and start is None:
start = end
if not isinstance(start, i... | 9449abd7bb962890b45ceaccdd6c3109d639174b | 68,907 |
def get_ndmi_task(band_types='BANDS-S2-L1C'):
"""
EOTask that calculates the NDMI values
Expects the EOPatch to have either Sentinel L1C or L2A bands.
Will append the data layer "NDMI" to the EOPatch
Run time parameters:
- band_types(str): the name of the data layer to... | 27f00054de49791b0f2655c880ae3f8ba4b37e5c | 68,908 |
def calculate_halo_correspondence(source_halo_props, target_halo_props, n_threads=-1):
"""Calculating indexing array defined by a statistical correspondence between
source and target halos.
Parameters
----------
source_halo_props : sequence of n_props ndarrays
Each ndarray should have shape... | e32f88188c1b137274292c2c6e2c6b163b861ecf | 68,909 |
def eval_eigs(model, dataloader, fisher=True, train_mode=False, nsteps=10, return_evecs=False, pnames=None):
"""
Get "nsteps" approximate eigenvalues of the Fisher or Hessian marix via Lanczos.
Args:
model: the trained model.
dataloader: dataloader for the dataset, may use a ... | c248031705792da8fd44eea34eac21d69690cec6 | 68,910 |
from typing import Optional
from typing import Union
from typing import List
from typing import Tuple
def mlp_run_real_comparison_montecarlo(dataset: cvnn.dataset.Dataset, open_dataset: Optional[t_path] = None,
iterations: int = 30,
epochs:... | 0db6106204cb2dd5387f8e2a255bee55a7577176 | 68,911 |
import random
def calculate_shapley_value_for_single_node(g, prob_vals, node):
"""
This approach is based on the following paper - https://www.sciencedirect.com/science/article/pii/S0004370208000696?via%3Dihub
:param g: graph
:param prob_vals: node weights
:param node: node under consideration
... | 5144a62c5707032bf6e88dd47c08cea3c2ec682a | 68,912 |
def nerf(key, args):
"""Neural Randiance Field.
Args:
key: jnp.ndarray. Random number generator.
args: FLAGS class. Hyperparameters of nerf.
Returns:
model: nn.Model. Nerf model with parameters.
state: flax.Module.state. Nerf model state for stateful parameters.
"""
deg_point = args.deg_poin... | 7673aad74925ee8ee5fbbfbd43c882462e311c33 | 68,913 |
def psnr_delight(y_true, y_pred):
""""Calculating peak signal-to-noise ratio (PSNR) between two images."""
return tf.image.psnr(y_pred, y_true, max_val=255.0) | 75536092f76f626c5e0874bba46dfa0f610f7a18 | 68,914 |
import os
def check_ansible():
"""
If the playbooks and roles directory exist then ANSIBLE_* settings
variables are likely configured.
"""
exists = os.path.exists(settings.ANSIBLE_PLAYBOOKS_DIR) and\
os.path.exists(settings.ANSIBLE_ROLES_PATH)
if not exists:
logger.warn("Ansibl... | 167a6a0da5cdd1fc6c02e72bc65f764bed4f9a9a | 68,915 |
import warnings
def plot_convergence_results_m(iterations,
distances,
total_energies,
*,
modes,
nodes=None,
saveas1='t_energy_conver... | 40e5c6057bcffdc35decb09904f7be40d0c77889 | 68,916 |
def add(ds_man, ds_id=None, params=None):
"""
:param ds_man: rest.SMapiDatasetManager
:param ds_id: string
:param params: {
doc {
name
input_path
upload_dt
metadata
is_public
(ds_config keys from sm.engine.dataset.FLAT_DS_CO... | f9705e79d6ad27e027c9ae3f6414839dea510b27 | 68,917 |
def _traversable_path(path):
"""
Little helper to remove a leading slash (and trailing slashes as well)
which the .restrictedTraverse method seems to dislike.
>>> _traversable_path('/e-learning/')
'e-learning'
Note: The method will still raise a KeyError if fht object is not yet there!
"""... | e147dc3da014db598ed5f7981e9a5664b33ec907 | 68,918 |
def _neurovault_images(parts, query):
"""Mocks the Neurovault API behind the `/api/images/` path.
parts: parts of the URL path after "images",
ie [] or ["<someimageid>"]
query: the parsed query string, e.g. {"offset": "15", "limit": "5"}
returns a dictionary of API results
See the neurovau... | 930929ac985e06b2f0d8281419b8b23b5bc9fa1b | 68,919 |
import re
def normalize_likes(sql: str) -> str:
"""
Normalize and wrap LIKE statements
:type sql str
:rtype: str
"""
sql = sql.replace("%", "")
# LIKE '%bot'
sql = re.sub(r"LIKE '[^\']+'", "LIKE X", sql)
# or all_groups LIKE X or all_groups LIKE X
matches = re.finditer(r"(or... | 8059eb4bf1ee4a8045702024c81a4f8b35469358 | 68,920 |
def apply_filters(url, redfin_base_url):
"""Apply more filters to make it more fine-grained.
Return a list of urls containing filters, which adds up
to the original url.
Filter priority: price, sqft-size, year-built
"""
if '/filter/' not in url:
price_filters = [(300000, 600000)]
... | df411856ceb55c3f62f5cc463161b8b1cc9bcf45 | 68,921 |
def update_hand(hand, word):
"""
Does NOT assume that hand contains every letter in word at least as
many times as the letter appears in word. Letters in word that don't
appear in hand should be ignored. Letters that appear in word more times
than in hand should never result in a negative count; ins... | 43a976e5abddb66e3e33ff0f4a693278ac490410 | 68,922 |
def get_char_size1(coord1, v):
"""
if not vetical
c1 c2
c4 c3
if vetical
c1 c2
c4 c3
"""
c1, c2, c3, c4 = coord1
if v:
csz = (np.linalg.norm(c1 - c2) + np.linalg.norm(c3 - c4)) / 2
else:
csz = (np.linalg.norm(c1 - c4) + np.linalg.norm(... | 46166d8fd3e8c0384671beebe8bbf00745ccf0ba | 68,923 |
def parse_xml(xml_file):
"""Create the python model for a test_run xml file"""
return AutoCertKitRun(xml_file) | bf696dd2b3c8e00b567e480caa12df810977bca0 | 68,924 |
import logging
def query(query_str):
"""Write rows to bigquery table.
Args:
query_str: str, the query to execute.
Returns: list of google.cloud.bigquery.table.Row objects.
"""
job = gcp.bigquery_client().query(query_str)
if job.error_result:
logging.error('Bigquery: %s', job.... | 5854757273abc3739cba40b1db034a8acac04244 | 68,925 |
import logging
import requests
def removeGitHubTeamMember(teamID, login):
""" Remove a team member from a team """
if str(int(teamID)) != str(teamID):
logging.warning("Bad Team ID passed!!")
return None
if login.lower() == 'humbedooh':
logging.info("Not removing Mr. Humbedooh just ... | c754e619b30720f5198edb1639b15b72eda52548 | 68,926 |
import pickle
def load_omas_pkl(filename, consistency_check=None, imas_version=None):
"""
Load OMAS data set from Python pickle
:param filename: filename to save to
:param consistency_check: verify that data is consistent with IMAS schema (skip if None)
:param imas_version: imas version to use ... | bdfca5f472cfedf86ad80c03e7869dac206f62ea | 68,927 |
import pandas as pd
import os
def kmenta2(path):
"""Simulation Data for model Three-Stage Least Square (threesls) that corresp
onds to method 3SLS of systemfit
Dataframe contains 20 annual observations of a supply/demand model with
5 variables. Columns are q=Food consumption per capita, p=Ratio of food
pri... | 9074405444016e21292f4a9dd7df26f7e65b890b | 68,928 |
from bs4 import BeautifulSoup
def get_job_id_indeed(card: BeautifulSoup) -> str:
"""
Function to retrieve the job ID from an HTML tag in the <div class='jobsearch-SerpJobCard unifiedRow row result'.
The job ID appears to be unique for each job and is used to remove duplicate results and later may be
u... | aeb252cd519f5ef1a1264e8e7d29d9a427d67b95 | 68,929 |
def pivot_df(df, var_name):
"""
Pivot DataFrame converting columns to source and data to var_name
Parameters
----------
df : pandas.DataFrame
Source DataFrame to convert to Seaborn long style
var_name : str
Column name to use for data in final DataFrame
Returns
-------
... | f0e83b92c5ea46ed274173f0dcd5374df85b6a00 | 68,930 |
async def stream_connect(session_name, destination,
sam_address=i2plib.sam.DEFAULT_ADDRESS, loop=None):
"""A coroutine used to connect to a remote I2P destination.
:param session_name: Session nick name
:param destination: I2P destination to connect to
:param sam_address: (opt... | bb46ad3e4dd83d760e605c47ef0e30470fb56cd0 | 68,931 |
def escapes_sub(match):
"""Substitutes escaped characters."""
return match.group(1) | f9d535bfdeea2cf4791301c348d513b606ed258d | 68,932 |
import json
def ref_truncated(ref_scene, matched_footprints, covth=.99):
"""Return True if reference scene will be truncated."""
# geometries are in lat/lon projection
src_srs = osr.SpatialReference()
src_srs.SetWellKnownGeogCS("WGS84")
#src_srs.ImportFromEPSG(4326)
# use projection with uni... | 1d9b32dcfb8bb819f9c51681a44d41b56cb53ee5 | 68,933 |
def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... | 752fa58dbf1cc34e95a1c53f1f38b0746ae25f62 | 68,934 |
def vit_tiny_patch32_224(pretrained=False, **kwargs):
""" ViT-Tiny (Vit-Ti/16)
"""
model_kwargs = dict(patch_size=32, embed_dim=384, depth=12, num_heads=3, **kwargs)
model = _create_vision_transformer('vit_tiny_patch16_224', pretrained=pretrained, **model_kwargs)
return model | 1d8673f713bbe2962b243d9142a1b89cf1b24b77 | 68,935 |
def minimum_time_to_make_a_sale():
"""
Real Name: Minimum Time to Make a Sale
Original Eqn: 1
Units: Months
Limits: (None, None)
Type: constant
Subs: None
What is the absolute minimum calendar time it would take to make a sale to
a person, even if you had all the hours in the da... | ab6acc9421756d944c23119512bb84eb7750c83b | 68,936 |
def read_data_line(line):
"""Process a line from data file.
Assumes the following format:
WORD W ER D
i.e. word tab separated with pronunciation where pronunciation has space
separated phonemes
Args:
line: string representing the one line of the data file
Returns:
chars:... | 66a840e2f2dfbc5e6c9d4a62c938b1bc60454a1f | 68,937 |
from typing import Optional
def infer_compression(input_filename: str) -> Optional[str]:
"""
Infers compression for a file from its suffix. For example, given "/tmp/hello.gz", this will return "gzip"
>>> infer_compression("/tmp/hello.gz")
'gzip'
>>> infer_compression("/tmp/abc.txt") is None
T... | fc4c434586b88113ba5bdff3d1a0b0ce52b60530 | 68,938 |
def _combine_samples(x_pos, x_neg, labels=None):
"""Combines sample data in one large numpy array and labels them according to class."""
y = []
y += [1] * x_pos.shape[0]
y += [-1] * x_neg.shape[0]
x = np.vstack((x_pos, x_neg))
return x, np.array(y) | 596f46237b3dd04c6190c9d1f34f8c5b46ac1e14 | 68,939 |
def get_runner(tasks, args):
"""
:param tasks:
:return: Runner
"""
if is_grid5k():
return Grid5kRunner(tasks, args)
return LocalRunner(tasks, args) | 5c0ab5d131b677a7541dcd7e3b0753e0dd1ee1dd | 68,940 |
def artificial_to_original(params, errors, f, hiatus=0):
"""
Convert artificial beam parameters to original beam parameters.
ISO 11146-1 section 9 equations are used to retrieve the original beam
parameters from parameters measured for an artificial waist
created by focusing the beam with a lens.
... | 0bc94523a3e462221bca63e89a078f160dcb8386 | 68,941 |
def api_get_balance(addr): # noqa: E501
"""get balance from address using woc.
get balance from address using woc. # noqa: E501
:param addr: bitcoin sv address
:type addr: str
:rtype: ResponseGetBalanceModel
"""
return 'do some magic!' | b64771f02553e134f17b8cc5dcfddc3f48465849 | 68,942 |
import logging
import sys
def first_run() -> (list, Connection):
""" This function is launched when the app starts and makes sure that everything is properly setup. If everything
ran correctly, it returns the token. Otherwise it stops the application. """
conn = create_connection()
db_configs = read_... | 69c097f367b9f191bf81ac62e3c67b16f2379bba | 68,943 |
def build_app_generator(request):
"""Build - App Generator page."""
app_generators = [
{
'css_name': 'app-stub',
'title': _('App Stub'),
'download': 'https://github.com/mozilla/mortar-app-stub/archive/v0.1.0.zip',
'preview': 'app-stub-screenshot.png',
... | 609b47b9d5ecc78cd9a936ca889f762c7c6ecaf4 | 68,944 |
import copy
def get_RF_color(rf_vec):
""" Mapping RF space to color in a standard (historical) way.
"""
color = copy.deepcopy(rf_vec)
def renormalize(v):
v -= np.min(v)
return v / np.max(v)
for i in xrange(3):
color[:, i] = renormalize(color[:, i])
return color | 0c10e2622fc9394156b79c6ecae35d4a27c3d4c0 | 68,945 |
import pickle
def get_probabilities(input):
"""
Reads the models from the models directory
Gets the probabilities of the input for all the models
:param input: sparse vector
:return: data frame with the probabilities of the models
"""
with open('models/ada.pkl', 'rb') as file:
ada_... | 22984512263422ad53d3abe90bfd57830514bc7a | 68,946 |
def setup(hass, config):
"""Set up this component."""
# Print startup message
_LOGGER.info(STARTUP)
# Check that all required files are present
file_check = check_files(hass)
if not file_check:
return False
# Create DATA dict
hass.data[DOMAIN_DATA] = {}
hass.data[DOMAIN] =... | 089fe5f0f956841285c8d705431e57f46cbcbbc5 | 68,947 |
import sqlite3
def create_connection(db_file): # Establish SQLITE database connection cursor
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection or None
"""
conn = None
try:
conn = sqlite3.connect(db... | 539474e31326cf95607b375e9469ece964b661a8 | 68,948 |
import click
def eeq(config, inp: str, out: click.File, chrg: int):
"""Electronegativity equilibration atomic partial charges."""
molecule = ksr.constructMolecule(geometry=inp, out=out)
nat = molecule.get_number_of_atoms()
eeq = molecule.get_eeq(chrg)
for i in range(nat):
silentPrinter(co... | c0628d6483a81f2491bf831109dc4c1f422ae436 | 68,949 |
import os
import json
def load_config(config_spec):
"""Loads configuration for a template statement
For each type of bank statement, the exact format will be different.
A config file holds the instructions for how to process the raw pdf.
These config files are stored in a folder structure as follows:... | 4ca53ce22b8b9270a98ee8503794f79c59e8b8c4 | 68,950 |
def get_holdings(xls: pd.ExcelFile) -> np.ndarray:
"""Retireve the holdings data from excel file.
:param xls: The excel file.
:return: The capacities.
"""
df_ward_info = pd.read_excel(xls, WARD_SHEET, index_col=0).astype("str")
holdings = np.array(df_ward_info.loc[WARD_HOLDING_ROW]).astype(
... | 7a400c090a022ac0a6a37f1d5a258dd2cfc82b0a | 68,951 |
import os
import pickle
def authenticate():
"""Authenticates a user and creates an AdMob Service Object.
Returns:
An AdMob Service Object that is authenticated with the user using either
a client_secrets file or previously stored access and refresh tokens.
"""
# The TOKEN_FILE stores the user's acce... | 8ea9a33add369d33a6ff9b7933110fb0f7e271b8 | 68,952 |
def create_comment():
"""
<url>/api/comment/create
View that Creates Comments
"""
token = request.json.get('token')
body = request.json.get('body')
post_id = request.json.get('post_id')
user = User.query.filter_by(token=token).first()
approved = 0
if user.approved == 1:
... | aee942f7a3568fee5fb84998446ef6e2cde6b92d | 68,953 |
def formatted_constituent_array(constituent_array):
"""
Given a constituent array of Species, return the classic CALPHAD-style interaction.
Parameters
----------
constituent_array : list
List of sublattices, which are lists of Species in that sublattice
Returns
-------
str
... | b1e60d21c28b66620eaffed1cda20abcb394a833 | 68,954 |
import os
import io
def _get_cached_run(run_id):
"""Load a run from the cache."""
run_cache_dir = openml.utils._create_cache_directory_for_id(RUNS_CACHE_DIR_NAME, run_id,)
try:
run_file = os.path.join(run_cache_dir, "description.xml")
with io.open(run_file, encoding="utf8") as fh:
... | bb238f555727e262984e31377cdb941941bc5dae | 68,955 |
from rdkit import Chem
def load_molecule(molecule_file,
add_hydrogens=True,
calc_charges=True,
sanitize=True,
is_protein=False):
"""Converts molecule file to (xyz-coords, obmol object)
Given molecule_file, returns a tuple of xyz coords of mo... | 9ea7843eec42cea292ad459d24d63e2122d9d9e8 | 68,956 |
def calc_automated_readability_index(
n_letters: int,
n_words: int,
n_sents: int,
a: float = 6.26,
b: float = 0.2805,
c: float = 31.04,
) -> float:
"""
Вычисление автоматического индекса удобочитаемости
Описание:
Чем выше показатель, тем сложнее текст для чтения
Резу... | d2a49044749dc93bb8684b27a81f47ff1498cc46 | 68,957 |
def FirstFree(seq, base=0):
"""Returns the first non-existing integer from seq.
The seq argument should be a sorted list of positive integers. The
first time the index of an element is smaller than the element
value, the index will be returned.
The base argument is used to start at a different offset,
i.e... | 42323664c7bb2c59506ed3b24115a38bc0fcf63d | 68,958 |
import random
import time
import requests
import json
from datetime import datetime
def getThreadList(forumUrl: str, pageFrom: int = 1, pageTo: int = 1, dynamicPageTo: bool = True) -> list[
dict]:
"""
Get threads in specific page url
Args:
pageFrom:
pageTo:
pageUrl: Url
Re... | afa666894b523a990569f5d75973db59fca0b9d3 | 68,959 |
def overlap_set(str_mention1, set1):
"""
Receives a mention and a set of mentions and returns whether the mention is in the set
:param str_mention1: a mention
:param set1: a set of mentions
:return: whether the mention is in the set
"""
return str_to_set(str_mention1).intersection(set1) | 9b1a276f4d9b426efbb5d1d30b91e5c7a2f872bf | 68,960 |
def get_eval_mask(labels, invalid_voxels):
"""
Ignore labels set to 255 and invalid voxels (the ones never hit by a laser ray, probed using ray tracing)
:param labels: input ground truth voxels
:param invalid_voxels: voxels ignored during evaluation since the lie beyond the scene that was captured by the laser
... | d02ac06abd89b0e0cc9a424a7c4a77ef796afeed | 68,961 |
from typing import Dict
def transform_force(force_in_local,
coord_out: CORDx, coords: Dict[int, CORDx],
nid_cd: int, unused_icd_transform):
"""
Transforms force/moment from global to local and returns all the forces.
Supports cylindrical/spherical coordinate system... | a1ff989990101f8e3c623521c0b3f31678d6813a | 68,962 |
def partition_data(y, nfold=10, fold_method='sublock', nrepeat=None):
"""
partition data for K-Fold Cross-Validation.
Parameters
----------
nobs : int type.
Number of observations.
nfold : int type,
default is 10. number of folds.
method : s... | 04f072c731adc8014d84479e47f6d201867e97e0 | 68,963 |
def dbcursor_query(query,
args=[],
onerow=False, # Require exactly one row returned
tries=2 # Times to try in the face of errors
):
"""
Run a query against a cursor, catching anything that arises from
the rowcount being < 0 ... | e2178d876275debc9fd55074170f84b7b9b6c556 | 68,964 |
def accept_penalty(employee_id: str = None, file: str = None, docname: str = None) -> dict:
""" This is an API to accept penalty. To Accept Penalty, one needs to pass the face recognition test.
Image file in base64 format is passed through face regonition test. And, employee is given 3 tries.
If face recognition i... | 608ff0c2ed3b3b5afd9e7cd371e17afa45bb944c | 68,965 |
def evaluate_mae(dataloader, model):
"""
Calculates MAE using previously trained model
Args:
data_transforms: torchvision transforms to preprocess raw images; same as validation transforms
model: densenet-121 from torchvision previously fine tuned to training data
Returns:
mae: ... | 75fedb1b93d674323232176871924637c7a4a844 | 68,966 |
def user_drafts():
"""Получить список черновиков"""
user = get_user_from_request()
query = Post.get_user_drafts(user)
limit = max(1, min(int(request.args.get("limit") or 20), 100))
paginated_query = PaginatedQuery(query, paginate_by=limit)
posts = [p.to_json() for p in paginated_query.get_obje... | c5f7d114d7e371f0fb6400b2ee982e3a167ec8f4 | 68,967 |
import sys
import traceback
def describe_exc(exc):
"""Create a multi-line description of an exception and its traceback"""
parts = []
parts.append('Exception description:')
ex_type, ex_value, ex_tb = sys.exc_info()
parts.append(' %s:' % str(ex_type).split('\'')[1])
parts.append(indent_message(str(exc), 4... | ae3832f543ad7bdfa3d43cf1cab70a75596722be | 68,968 |
def _guessTrayPosition(screenGeometry, iconGeometry):
"""
Function uses simple heuristic to guess the position of system tray on the screen
@param screenGeometry: screen size where the icon is located
@type screenGeometry: QRect
@param iconGeometry: geometry of the tray icon
@type iconGeometry: ... | a65cb13d705c60691b28de7baa5c36c7cd96e6ee | 68,969 |
def Mprop(d):
"""
M = Mprop(d)
------------
ABCD matrix for free space propagation of distance d.
"""
return np.matrix([[1, d], [0, 1]]) | 4a858b9e953df2b5e5268664797975af1863c158 | 68,970 |
import typing
import collections
def with_argument(
key: str,
/,
converters: _MaybeIterable[ConverterSig[typing.Any]] = (),
*,
default: _UndefinedOr[typing.Any] = UNDEFINED,
greedy: bool = False,
max_value: _UndefinedOr[_CmpProto[typing.Any]] = UNDEFINED,
min_value: _UndefinedOr[_CmpPr... | b698f6601cef00d42a0116383eb202c38c1f84ab | 68,971 |
def possible_values1(grid, r, c):
"""Return the possible values for a cell in the r,c position"""
n = max([max(l) for l in grid])
h = len(grid)
w = len(grid[0])
# ret = []
# count = [0 for i in range(n+1)]
# for dx in [-1, 0, 1]:
# for dy in [-1, 0, 1]:
# if dx == 0 and ... | 3537c90917c7975cffe6bdfd537a406077101a39 | 68,972 |
from typing import Optional
from datetime import datetime
def logins(page: int = 1, login_type: Optional[str] = None):
"""Shows log of login attempts.
Args:
page: Page number for results pagination
login_type: Login type (unique, failed)
"""
if login_type is None:
query = Logi... | 1aec22c635e99194bea69b76ac421d4ae857d5c6 | 68,973 |
def job_header_template(sequence):
"""
Returns a string with the job header template
including SBATCH environment variables for sequencerXX.py script
Parameters
----------
sequence: sequence object
Returns
-------
header: str
String with job header template
"""
pyth... | aed419d5e2ef1dbde6b62b12e74707e50c0b90d5 | 68,974 |
import networkx
def plot_graph(val_matrix,
var_names=None,
fig_ax=None,
figsize=None,
sig_thres=None,
link_matrix=None,
save_name=None,
link_colorbar_label='MCI',
node_colorbar_label='auto-MCI',
... | 3cb5e99a29307bf94d8f067663130a3d0a4f8985 | 68,975 |
def get_details_items(project):
"""Return recent files/links for card on project details page"""
files = File.objects.filter(project=project).order_by('-date_modified')[:5]
links = HyperLink.objects.filter(project=project).order_by(
'-date_modified'
)[:5]
ret = list(files) + list(links)
... | 6d2fd670c1f499690a674af96bf87f6f07668ce5 | 68,976 |
import tensorflow as tf
import logging
from tensorflow.python.client import device_lib
import numpy
import random
import os
def setup_keras(seed=None, profile=None, device=None,
BLAS_thread_count=None, BLAS_MKL_CNR=True,
verbose=True, print_indent=0, **kwargs):
"""Setup tf.keras an... | 1c8da9fcd8bf6bbe36fd9e9075810d7bf33ae504 | 68,977 |
def mu_star_calibration_from_geodetic_mb(gdir,
ref_mb=None,
ref_period='',
step_height_for_corr=25,
max_height_change_for_corr=3000,
... | 6798b95aa562a46a9ffec8f79a69513033ce7c9b | 68,978 |
import requests
def invoke_action(action_name, api_host, api_key, data=None, ignore_certs=True, web=False):
"""
usage:
invoke_action('hello-world',
os.environ['__OW_API_HOST'],
os.environ['__OW_API_KEY'])
"""
if data is None:
data = {}
api_host = api_hos... | 44bc871599e7fc74bbaf8693d9d8b7a313193973 | 68,979 |
from typing import Iterable
def flatten(nested):
"""Flatten a nested sequence where the sub-items can be sequences or
primitives. This differs slightly from itertools chain methods because
those require all sub-items to be sequences. Here, items can be primitives,
sequences, nested sequences, or any c... | 464cd221dfaf6f842bf6da0d96ad8322d1c84e71 | 68,980 |
def prep_irrigation_pws_ratio() -> pd.DataFrame:
"""prepping the ratio of water flows to irrigation vs. water flows to public water supply by county. Used to
determine the split of electricity in interbasin transfers between the two sectors.
:return: DataFrame of percentages by county
"... | 519eb1484c824b0bd6266a586cf17bbf49c34e9b | 68,981 |
def negotiate_rpl_connection(server, is_master=True, strict=True,
options=None):
"""Determine replication connection
This method attempts to determine if it is possible to build a CHANGE
MASTER command based on the server passed. If it is possible, the method
will return a ... | daa64f7c20a80476f99c14ef88b75dd71adc234b | 68,982 |
def __mailing_callback(update: Update, language_code):
"""show mailing menu"""
text, reply_markup = __get_mailing_page(update.effective_user.id, language_code)
cf.edit_message(
update=update,
text=text,
reply_markup=reply_markup,
)
return consts.PARAMETERS_MAIN_STATE | c557bee58d4684b323489a87a296fec7c7514b31 | 68,983 |
def populate_skills(request):
"""
This api populates dummy data in skills table
"""
skills = ['ruby on rails',"kafka","aws","python","django","mysql","mongodb","php","laravel","flask","html","javascript","jquery","css","dotnet","c++","c#"]
for skill in skills:
Skill.objects.create(name=ski... | 91ffa96ecd54061e0c521e5c0ca420f336b9cff7 | 68,984 |
def list_repositories(status):
"""
list repositories
status: ALL, ERROR, FETCHING, HARVESTED, RECORDED
"""
try:
if status == '' or status == 'ALL':
status = None
# TODO: repositories
return iroko_json_response(
IrokoResponseStatus.SUCCESS, 'ok', 'repos... | 13e6ca475433c928488b8e9e150fbdf6eaf4ab69 | 68,985 |
def _literal_params(params):
"""
Converts string parsed-params into a dicitionary
"""
if isinstance(params, dict):
return params
params = literal_eval(params) if params else {}
if not isinstance(params, dict):
abort(400, "Parsed params are not a valid map (dict)")
return par... | 57ca560429c8eae32916a54fd8023befdea13fe7 | 68,986 |
def create_computation_graph(num_lemmas, num_pos, num_dep, num_directions, num_relations, wv=None, num_hidden_layers=0):
"""
Initialize the model
:param num_lemmas Number of distinct lemmas
:param num_pos Number of distinct part of speech tags
:param num_dep Number of distinct depenedency labels
... | 131163c3e3c61a8e9dc10ec6355e340378a6ba4d | 68,987 |
def get_update_from_args(args):
"""Find bot and update instance in the given args.
Args:
args(iterable): arguments to search for the bot and update.
Returns:
telegram.Update. instance of update that found in args.
"""
update = find_instance_in_args(telegram.update.Update, args)
... | ba72c8777909e61277b1439ec21f7f043fe95c7c | 68,988 |
import warnings
import traceback
def render_tasks(write, tasks, field_limit=0, ignored_fields=None,
human_readable=False, colorize=None, write_err=None,
format_node=format_node, format_value=None,
utc_timestamps=True, colorize_tree=False, ascii=False,
... | 870cf69d6f594618be267de7d77544b6219aea11 | 68,989 |
from sys import path
import tempfile
def get_temp_filename(name='srv-temp-file', extension=None):
"""
Returns an absolute path to temp file with the specified name and extension.
Filename format:
- <name>_<rand-int>.<extension>
:param name:
:param extension:
:return:
"""
filenam... | 52f66f9649bcb63bac61866799474252d85a0a67 | 68,990 |
import os
from typing import Dict
from typing import Tuple
from typing import Callable
from typing import Union
import collections
def load_lcmv_vdj(
vdj_fname: str = os.path.join(LOCAL_DATA_DIR, "lcmv_tcr_vdj_unsplit.txt.gz")
) -> Dict[str, Dict[str, Dict[str, Tuple[str, str, str]]]]:
"""
Load the vdj ta... | fdcb744f20513eda00ef8132ea570e4537de0507 | 68,991 |
from scipy.interpolate import splrep, splev
from ..tools.output import Plotter
from scipy.interpolate import interp1d
import sys
def makeTemplate(l,Fl,modLMap,k=1,debug=False):
""" ... | 127dc8974e534b1f8dacb11f5513c97b07d166e9 | 68,992 |
from re import S
def sub_post(e):
""" Replace 1*-1*x with -x.
"""
replacements = []
for node in preorder_traversal(e):
if isinstance(node, Mul) and \
node.args[0] is S.One and node.args[1] is S.NegativeOne:
replacements.append((node, -Mul._from_args(node.args[2:])))
... | c788adf09cedb8bba5a4405b17f54c1fc5932b7f | 68,993 |
import array
def seq2list(seq,result=None):
"""Given an OpenCV sequence object representing contours,
returns a list of 2D point arrays."""
if result is None: result = []
while seq:
l = list(seq)
result.append(array(l,'i'))
# sub = seq2list(seq.v_next(),result)
seq = se... | aa6070b44b6c07fe6de25264ef2977b28d769589 | 68,994 |
def Rpost2M(radius, unit='Earth', grid_size = 1e3, classify = 'No'):
"""
Forecast the mass distribution given the radius distribution.
Parameters
---------------
radius: one dimensional array
The radius distribution.
unit: string (optional)
Unit of the mass. Options are 'Earth' and 'Jupiter'.
grid_size: int... | f5567a03edae59a326fd7c4cad9d6e91c237a5da | 68,995 |
def all_sample_fractions(array, iterations=100, fractions=[0.1,0.15,0.2,0.25],
compression=[50,50], background=np.nan):
"""
Generates a 4D array of several samples; the first axis allows choice of the fraction of each
sampling; the second axis allows for each iteration of this fract... | c265f32eab6570bd23a3705bc42281cae3b9c847 | 68,996 |
def load_hdf5_array(object, node, array_attribute, tag = 'Values'):
"""Loads the property array data as an attribute of object, from the hdf5 referenced in xml node.
:meta private:
"""
assert (rqet.node_type(node) in ['DoubleHdf5Array', 'IntegerHdf5Array', 'Point3dHdf5Array'])
# ignore null value
... | 867a08ea81159e5ac12351ac279aa18cbea6ab35 | 68,997 |
import uuid
import sys
def set_payload(href,session_type,rg_identification, rg_description):
"""Set the headers and Paylod based on the type of session and/or method to be sent to the Resource Groups API."""
rg_uuid = str(uuid.uuid4())
headers = {
'content-type': "application/json",
'accept': "ap... | 07d8f37e43005664a10235e457e0a6f2df9205af | 68,998 |
def test_model_tester(clf,my_dataset,featurs_list):
"""
This function will test our model into the tester file
"""
tester.dump_classifier_and_data(clf, my_dataset, features_list)
return tester.main() | 5ae1fb0d5d47eb0746fa8cc842c37bf7eb5a179f | 68,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.