content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def maxpool_to_same_maxpool(module):
"""Turn All MaxPool2d into SameMaxPool2d to match TF padding"""
module_output = module
if isinstance(module, nn.MaxPool2d):
module_output = MaxPool2dSamePadding(
kernel_size=module.kernel_size,
stride=module.stride,
padding=0, ... | 70217073e0ec8d1bfd74ee5e79775b6b87e8dc62 | 3,626,645 |
def double_wedge_filter(sinogram, center=0, sino_type="180", iteration=5,
mask=None, ratio=1.0, pad=250):
"""
Apply double-wedge filter to a sinogram image (Ref. [1]).
Parameters
----------
sinogram : array_like
2D array. 180-degree sinogram or 360-degree sinogram.
... | 300fdb1cc94e6c95479f02e540a542de7e461bea | 3,626,648 |
def gather_data_to_plot(wells, df):
"""
Given a well ID, plot the associated data, pull out treatments.
Pull in dataframe of all the data.
"""
data_to_plot = []
error_to_plot = []
legend = []
for well in wells:
data_to_plot.append(df.loc[well, '600_averaged'])
error_to_pl... | 1870384b94c2cf3a8a5da84b848586e0a95d1713 | 3,626,649 |
def create_data_frame_sfem(data_sfem, strategy_order):
""" Create the DataFrame that will be used for the
type classification.
Args:
data_sfem (DataFrame): Individual level data that is
already subset to the correct level.
strategy_order (list): Name of all st... | fa8c41ded771e34cba89c99cc4f9bfb80acb7a92 | 3,626,651 |
import re
def is_ignored(filename, ignores):
"""
Checks if the filename matches any of the ignored keywords
:param filename:
The filename to check
:type filename:
`str`
:param ignores:
List of regex paths to ignore. Can be none
:type ignores:
`list` of `str` or... | 3d5016d5ac86efdf9f67a251d5d544b06347a3bf | 3,626,652 |
import requests
def token(username: str, password: str, auth_url: str = 'https://api.sonetel.com/SonetelAuth/beta/oauth/token',
refresh: str = "no", grant_type: str = "password", refresh_token: str = None) -> dict:
"""
Create an API access token from the user's Sonetel email address and password.
... | 3a76a8882a35ba1d4c91132182323f5d4095e73c | 3,626,654 |
async def present(
hub,
ctx,
name,
resource_group,
sku,
kind,
location,
custom_domain=None,
encryption=None,
network_rule_set=None,
access_tier=None,
https_traffic_only=None,
is_hns_enabled=None,
tags=None,
connection_auth=None,
**kwargs,
):
"""
..... | 8d2264e765fd22b6777bbb460174ed42a4c511ca | 3,626,655 |
def check_transaction_threw(client, transaction_hash):
"""Check if the transaction threw/reverted or if it executed properly
Returns None in case of success and the transaction receipt if the
transaction's status indicator is 0x0.
"""
encoded_transaction = data_encoder(transaction_hash.decode(... | ec7d44c8824ea5613642e28a11e0ff635a38d9a2 | 3,626,657 |
def boldReplacements(tex):
"""
SPECIFIC TO shmem_reductions:
Replace the Latex command:
"\\textbf{<NAME>} \\newline <text> <code> \\newline...\\bigskip"
--NAME will the title of a new section header with <text> as the
immediate content.
-- <code> will be replaced as normal (See function ... | 27b7a80c36396d66218857348135d46beb1f760a | 3,626,658 |
def stop_program():
"""Small function to ask for input and stop if needed
"""
ok = input("Press S to Stop, and any other key to continue...\n")
if ok in ["S", "s"]:
return True
return False | c076d4a443331d64ef5855f0d20f7db2adb0cf11 | 3,626,659 |
def rotate(n):
"""
Rotate 180 the binary bit string of n and convert to integer
"""
bits = "{0:b}".format(n)
return int(bits[::-1], 2) | 23fa595ee66c126ad7eae0fa1ca510cf0cebdfbd | 3,626,660 |
def fixture_list_arg():
"""Test for the correct stdout.
Output in the tests should match what this returns
"""
def list_arg(*profiles):
_string = ""
for profile in profiles:
_string += (
f"[{profile}]\n"
f"reponame = {HOST}\n"
... | ee8a3829c95e5a0010a5474fba9b29da0df3b983 | 3,626,661 |
def tkForm(fields):
"""tkForm(fields: dict)->dict
fields: {'label1': 'defVal1', ...}
return: modified fields or {} if Esc
>_> tkForm( {'Imię':'iii', 'Imię 2':'iii 2', 'Nazwisko':'Nnn'} )
{'Imię': 'iii 1', 'Imię 2': 'iii 2', 'Nazwisko': 'nnn 3'}
"""
master = tk.Tk()
entries = {}
for i, (field, defVal) ... | 52d47e83f00dcd77b9a5bc279f5c1fe4aa9d429f | 3,626,662 |
def concentration_at_M(Mass, k, P, n_s, Omega_b, Omega_m, h, T_CMB=2.7255, delta=200, Mass_type="crit"):
"""Concentration of the NFW profile at mass M [Msun/h].
Only implemented relation at the moment is Diemer & Kravtsov (2015).
Note: only single concentrations at a time are allowed at the moment.
Ar... | b5109273c2bc59da0d5723027ab9d3e15595f4d2 | 3,626,663 |
def flip_thetas(thetas, theta_pairs):
"""Flip thetas.
Parameters
----------
thetas : numpy.ndarray
Joints in shape (num_thetas, 3)
theta_pairs : list
List of theta pairs.
Returns
-------
numpy.ndarray
Flipped thetas with shape (num_thetas, 3)
"""
thetas... | e19a274953a94c3fb4768bcd6ede2d7556020ab2 | 3,626,664 |
def Client(token=None, endpoint=None, config_path=None, connect_timeout=None):
"""Return global `RESTClientObject` with optional configuration.
Missing configuration will be read from env or config file.
Parameters
----------
token : str, optional
API token
endpoint : str, optional
... | d6909374b0d94fe86ed20296c3f7b25b7d14650d | 3,626,665 |
def numeral_to_int(numeral: str) -> int:
"""Returns the integer value represented by the given Roman numeral."""
i = 0
numeral_len = len(numeral)
total = 0
while i < numeral_len:
curr_value = numeral_values[numeral[i]]
if i < numeral_len - 1:
next_value = numeral_values[n... | 6d975a57691b392fa5726d97150c87e9f275bbca | 3,626,666 |
def TopOpeBRepTool_TOOL_tryTg2dApp(*args):
"""
:param iv:
:type iv: int
:param E:
:type E: TopoDS_Edge &
:param C2DF:
:type C2DF: TopOpeBRepTool_C2DF &
:param factor:
:type factor: float
:rtype: gp_Vec2d
"""
return _TopOpeBRepTool.TopOpeBRepTool_TOOL_tryTg2dApp(*args) | 6dbd60651c10d3a525ab440a600fd8615712c118 | 3,626,667 |
def disable_slot(slot, con=None):
"""Return True on success, False on failure, if con given does not commit"""
if not slot:
return False
if con is None:
try:
con = open_database()
result = disable_slot(slot, con)
if result:
con.commit()
... | 18b9e07f062e93f76dc7537ace1eac8c4884d327 | 3,626,669 |
def surface_analysis_function_for_tests(surface, a=1, c="bar"):
"""This function can be registered for tests."""
return {'name': 'Test result for test function called for surface {}.'.format(surface),
'xunit': 'm',
'yunit': 'm',
'xlabel': 'x',
'ylabel': 'y',
... | e6e58c172687ce3e0782abb07b9154afae9356cb | 3,626,670 |
def add_or_update(record, key, timetable, name, force_refresh):
"""
Insert a new user record or update exist one
:param name: user name identifier
:param timetable: timetable list
:param force_refresh: if refresh is required
:param key: the key in database
:param record: a User record
:r... | b348fa1718753846fa1edb5864a1094c41935f5b | 3,626,671 |
def from_time (year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None):
"""
Convenience wrapper to take a series of date/time elements and return a WMI time
of the form yyyymmddHHMMSS.mmmmmm+UUU. All elements may be int, string or
omitted altogether. If omitted... | 61d2bf9fb36225990ac0ac9d575c3931ef66e9f6 | 3,626,673 |
def plural(num, one, many):
"""Convenience function for displaying a numeric value, where the attached noun
may be both in singular and in plural form."""
return "%i %s" % (num, one if num == 1 else many) | f29753d25e77bcda2fb62440d8eb19d9bd332d1e | 3,626,674 |
def _handle_login_redirect(request, key):
""" This function is used to redirect login request to Microsoft OneDrive login page.
:param request: Data given to REST endpoint
:param key: Key to search in state file
:return: response authorization_url/admin_consent_url
"""
asset_id = request.GET.g... | 7e18d4a0557bd03e39b7196cbf4d0d9f15dac586 | 3,626,675 |
def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS,
problem_chars=PROBLEMCHARS, default_tag_type='regular'):
"""Clean and shape node or way XML element to Python dict"""
node_attribs = {}
way_attribs = {}
way_nodes = []
tags = [] # Handle secondar... | 0b1cf832731e3c4d8821a9fa5f7c54011d6fe0aa | 3,626,676 |
import inspect
def get_parent_module():
"""Get parent filename."""
frame = inspect.currentframe()
module = inspect.getmodule(frame)
while module.__name__ == __name__:
if frame.f_back is None:
raise ValueError("Fell off the top of the stack.")
frame = frame.f_back
mo... | 36c0a2c42e6eab7c68595c144d2b7c056ffa7918 | 3,626,677 |
from typing import Any
import logging
def log_response(response: str, trim_log_values: bool = False, **kwargs: Any) -> None:
"""Log a response"""
return log_(response, response_logger, logging.INFO, trim=trim_log_values, **kwargs) | 24929c959dac071fc313319cd651b110b6a328d5 | 3,626,678 |
def logged_in(browser: RoboBrowser):
"""
Returns true if we are still on the login page
"""
login_div = browser.find('div', content="Login")
return True if not login_div else False | fb4211b21230df3e055b01fe7a6b70a56a89bb3e | 3,626,679 |
def nan_dot(A, B):
"""
Returns np.dot(left_matrix, right_matrix) with the convention that
nan * 0 = 0 and nan * x = nan if x != 0.
Parameters
----------
A, B : np.ndarrays
"""
# Find out who should be nan due to nan * nonzero
should_be_nan_1 = np.dot(np.isnan(A), (B != 0))
shoul... | 4ac1629cf0517ecba7ebc4f3bd11775535ea955d | 3,626,680 |
def create_sample_lp():
"""
Using gurobi create a sample LP.
"""
# Forest of 100 stands each assumed to be 1 ha in area
stands = create_stands(100)
# Minimum harvest age is 40 years, 10 year planning horizon
schedules = schedule_generator(4, 10)
# Track the age of each stand under eac... | 564e68fdfa326f5e5ddc23bd593d1c1dca1a8bb4 | 3,626,683 |
import warnings
def train_crabnet(model_name, csv_train, csv_val=None, val_frac=0.25):
"""
Function to train crabnet. This function allows a user to easily train
crabnet by only supplying training data a model name. You can update
epoch and batch size if desired.
Parameters
----------
mod... | ae78009c10f4aa3fd441a81f998c94f05e43ef0c | 3,626,684 |
import math
import time
def test_query_retry_maxed_out(
mini_sentry, relay_with_processing, outcomes_consumer, events_consumer
):
"""
Assert that a query is not retried an infinite amount of times.
This is not specific to processing or store, but here we have the outcomes
consumer which we can us... | 9339078c432cd087dcdbf799cad8d881defb41c2 | 3,626,685 |
def get_buckets(rdd, buckets):
"""Extracted from pyspark.rdd.RDD.histogram function
"""
if buckets < 1:
raise ValueError("number of buckets must be >= 1")
# filter out non-comparable elements
def comparable(x):
if x is None:
return False
if type(x) is float and i... | fe143075c8bd37702cbb23e76ea61ca32279ce32 | 3,626,686 |
def dollo_parsimony(phylo_tree, traitLossSpecies):
""" simple dollo parsimony implementation
Given a set of species that don't have a trait (in our hash), we do a bottom up pass through the tree.
If two sister species have lost the trait, then the ancestor of both also lost it. Otherwise, the ancestor has the trait.... | 7929006e1625ba502642fcbd44c0dfff44569777 | 3,626,687 |
from datetime import datetime
def localtime(t=None):
"""
localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead.
Modifi... | 9815211a160824c5e17b836a391a77a51647c648 | 3,626,688 |
def _to_bytes(str_bytes):
"""Takes UTF-8 string or bytes and safely spits out bytes"""
try:
bytes = str_bytes.encode('utf8')
except AttributeError:
return str_bytes
return bytes | fd16c24e80bdde7d575e430f146c628c0000bf9a | 3,626,689 |
import random
def extract_hidden_image(merged_image_path, mesg_image_path, secret_key):
"""
Unmerge an image.
INPUT: The path to the input image.
OUTPUT: The extracted hidden image.
"""
merged_img = Image.open(merged_image_path)
message_image = Image.open(mesg_image_path)
# Create the... | 68c97dc7328abfa7e10f6db5aec1bd5fa8cc258f | 3,626,691 |
from typing import Tuple
import pytz
def get_earliest_tables_last_updated_date(database_name: str, tables: Tuple[Tuple[str, str]]):
"""
Return the earliest of the last updated dates for a list of tables in UTC.
"""
with connections[database_name].cursor() as cursor:
cursor.execute(
... | 626c4407d2abfd4dd55ba3c5171b7390472c8bfe | 3,626,692 |
def check_nested_model(required_attribute_type: str) -> bool:
"""
Takes the properties of a required attribute on a model and searches as to whether or not this attribute
requires a model of its own
Parameters
----------
required_attribute_type : str
The type of the required attribute
... | f356476d6484fc52ade73a8ceda0bdefd39d31c4 | 3,626,693 |
def precision_and_recall(actual, predictions):
"""
Given predictions (an N-length numpy vector) and actual labels (an N-length
numpy vector), compute the precision and recall:
https://en.wikipedia.org/wiki/Precision_and_recall
Hint: implement and use the confusion_matrix function!
Args:
... | 26d656884bbd708156dcd5a8a8658f3b15c3cc1e | 3,626,694 |
import random
from datetime import datetime
def _insert_special_message(body):
"""Troll mode on special day for new pull request."""
tt = datetime.utcnow() # UTC because we're astronomers!
dt = timedelta(hours=12) # This roughly covers both hemispheres
tt_min = tt - dt
tt_max = tt + dt
# Se... | f466f5f6a198c37848ea2737f8d85dc8269eabac | 3,626,695 |
def determine_host(environ):
"""
Extract the current HTTP host from the environment.
Return that plus the server_host from config. This is
used to help calculate what space we are in when HTTP
requests are made.
"""
server_host = environ['tiddlyweb.config']['server_host']
port = int(serv... | 6e91f93d5854600fe4942f093de593e53aaf2aa0 | 3,626,696 |
def gen_rand_sys(size):
"""
generate a grid with input size
"""
# Initialize grid with size
grid = np.zeros(shape=(size, size), dtype=int, order='F')
# Randomize grid
randomize_sys(grid)
# return the generated table
return grid | 694ca5181705b455968cd1e0d0042619738b6e33 | 3,626,697 |
def __get_size__(filename):
"""
Parses the filename to get the size of a file
e.g. 128M+12, 110M-10
"""
match = FILE_REGEX.search(filename)
if match:
size_str = match.group('size')
si_unit = match.group('size_si')
shift = __get_shift__(match)
mul = 1
if si... | 3aa192757ca94ca1e28b4881dd40897ad0aabd23 | 3,626,698 |
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
df = pd.read_csv(filename, parse_dates... | 8be985b6ea729a94db4e90ae6696f00a4a0061c5 | 3,626,700 |
def document_entity_generator(*ehrpreper_files):
"""Generator of DocumentEntity"""
return (
document
for ehrpreper_file in ehrpreper_files
for model in load(ehrpreper_file)
for document in model.documents
) | 823c78590507b05f87e6c0fade73d949e67519e9 | 3,626,701 |
import csv
def readCSV(filepath):
"""
Method that reads a list of values from a CSV file
Parameters:
filepath (str): The path of the CSV file
Returns:
values (list): The list of values
"""
values = []
with open(IP_LIST, "rt", encoding="ascii") as f:
... | 590993fff105b414beedee0aa92279c1bd237f39 | 3,626,702 |
from typing import Tuple
def calc_gamma(data: np.ndarray) -> Tuple[str, int]:
"""Return a tuple consisting of binary form/string and decimal of gamma value."""
n = np.array([len(data)] * len(data[0]), dtype=int)
ones = np.count_nonzero(data, axis=0)
zeros = n - ones
gamma_bin = ''.join(map(str, (o... | 62ece1fdc89eb3da81d94bedfc846638ed2f6161 | 3,626,704 |
def read_messages(message_file):
""" (file open for reading) -> list of str
Read and return the contents of the file as a list of messages, in the
order in which they appear in the file. Strip the newline from each line.
"""
# Store the message_file into the lst as a list of messages... | 0e4b1a6995a6dd25ab3783b53e730d0dd446747c | 3,626,705 |
def result_message(iden, result=None):
"""Return a success result message."""
return {
'id': iden,
'type': TYPE_RESULT,
'success': True,
'result': result,
} | a0d704b39d69f355b2d6e5c772c02be65d13d9db | 3,626,707 |
import scipy
def _smesolve_single_trajectory(data, L, dt, tlist, N_store, N_substeps, rho_t,
A_ops, e_ops, m_ops, rhs, d1, d2, d2_len, dW_factors,
homogeneous, distribution, args,
store_measurement=False,
... | c688520f6b116b6338594687770ecc9b237c47c8 | 3,626,708 |
def reconstruction_error(S1, S2):
"""Do Procrustes alignment and compute reconstruction error."""
S1_hat = compute_similarity_transform_batch(S1, S2)
return S1_hat | ce84df6c1406a9b4e417fa379a49fdffa2ab534b | 3,626,709 |
def encode_bboxes(boxes):
"""[This function processes rectangles from Azure API and converts it to cv2.polylines format]
Args:
boxes ([list]): [list of x, y coordinates of rectangles]
Returns:
[list]: [np.array of formatted for use with cv2.polylines function call]
"""
polygon... | 855cd3bbf206d2adf1f046073a78e45b876b7973 | 3,626,710 |
def createTokenFromCredentials(body):
"""
Given a request body with a username and a password, generates a JWT access token or
returns an error response.
"""
valid = False
try:
user: User = User.objects(username=body["username"]).get()
valid = user.validatePassword(body["password... | c960ae9f3cc4417192ef6b8a80a01cec957c29ad | 3,626,711 |
def upload_forecast_batch(conn, json_io_dict_batch, forecast_filename_batch, project_name,
model_abbr, timezero_date_batch, overwrite=False):
"""
Uploads a batch (list) of JSON dictionaries to the model corresponding
to the args. This only iterates through timezeros, not models or ... | 6ae4c6d108266aa142217298ff530cfd0bbe3817 | 3,626,712 |
def count_team_forecasts_draw(team_id):
"""
count the number of draw forecasts for a team
"""
request = """
SELECT COUNT(*)
FROM season_forecast, season_fixture
WHERE season_forecast.fixture_id = season_fixture.id
AND (
(season_fixture.team_a_id = '%(team_id)s' AND season_forecast.s... | 8c0831fe07a66107178e32ce930e15395e921d5b | 3,626,713 |
def get_args():
"""Add custom knn arguments."""
parser = extraction_argument_parser()
parser.add_argument("-k", "--knearest", type=int, default=5,
help="When using a knn classifier, this is the number "
"of neighbors to check. "
"Defaul... | c8191ea8de39179aa3637041d2059a4bf1222491 | 3,626,714 |
from typing import Union
def start_xql_query_polling_command(client: Client, args: dict) -> Union[CommandResults, list]:
"""Execute an XQL query as a scheduled command.
Args:
client (Client): The XDR Client.
args (dict): The arguments to pass to the API call.
Returns:
CommandResu... | 648d9e5e0433cfc13a4f4d0d80ed5117520e2044 | 3,626,715 |
import logging
def change_main_address_column(df: gpd.geodataframe.GeoDataFrame) -> gpd.geodataframe.GeoDataFrame:
""" Changing the main address column for building gdf
:param df: modified gdf (address column changed)
"""
# Dropping cadaste address from df
df.drop(c.adr_main, inplace=True, axis=1... | a775d569b6c4d8a87a4526a920f82d6c028e44f0 | 3,626,717 |
def hello_world1():
"""
Flask endpoint
:return: TXT
"""
return "Hello World From App 1!" | fed4dcf04234ca8c47885d0702f284c13136f52f | 3,626,719 |
def vpt2(prog, output_str):
""" Reads VPT2 information from the output string.
:param prog: electronic structure program to use as a backend
:type prog: str
:param output_str: string of the program's output file
:type output_str: str
"""
return pm.call_module_function(
... | 0ec6c3a4e31d2188718430b62c4943ecbfdf2920 | 3,626,720 |
def learning_rate_schedule(current_epoch,
base_learning_rate,
lr_boundaries,
lr_multiplier):
"""Handles linear scaling rule, gradual warmup, and LR decay.
The learning rate starts at 0, then it increases linearly per epoch.
After 5 e... | 78a284261a4a6040a620556d1d5177ea73335942 | 3,626,721 |
def cradmin_titletext_for_role(context, role):
"""
Template tag implementation of
:meth:`django_cradmin.crinstance.BaseCrAdminInstance.get_titletext_for_role`.
"""
request = context['request']
cradmin_instance = request.cradmin_instance
return cradmin_instance.get_titletext_for_role(role) | 8e6a29c369c5ae407701c12dc541e82dda31f193 | 3,626,722 |
def to_unicode_for_identify(hash):
"""convert hash to unicode for identify method"""
if isinstance(hash, unicode):
return hash
elif isinstance(hash, bytes):
# try as utf-8, but if it fails, use foolproof latin-1,
# since we don't really care about non-ascii chars
# when runni... | 5071bf71e220389c87913e90a0fef509bded40bf | 3,626,723 |
from pathlib import Path
def url_to_path(url: URL) -> Path:
"""Convert a file:// URL into a UNIX path."""
return Path(url.path) | 42d7bdab2a539c3c2e65f3b36e45e2a32f5fdb39 | 3,626,724 |
def ver_notas(request):
"""Ver notas de investigaciones o documentos"""
form_elegir = BuscadorInvestigacionesForm(request.user)
form_crear = NotaForm()
context = {
'form_elegir':form_elegir,
'form_crear': form_crear,
"title":'Notas de investigaciones',
... | 4693ac1907943c1642c4430c8e5f1d502cacc495 | 3,626,725 |
def training_config(estimator, inputs=None, job_name=None, mini_batch_size=None):
"""Export Airflow training config from an estimator
Args:
estimator (sagemaker.estimator.EstimatorBase):
The estimator to export training config from. Can be a BYO estimator,
Framework estimator or... | cebeb96eb478332ed48d6896ecc989951a13a325 | 3,626,726 |
def stft(sig, fs=16000, win_type="hann", win_len=0.025, win_hop=0.01):
"""
Compute the short time Fourrier transform of an audio signal x.
Args:
x (array) : audio signal in the time domain
win (int) : window to be used for the STFT
hop (int) : hop-size
Returns:
X ... | 925626e7d131edfbd226ac1373ab6d5bdfe7c1ea | 3,626,727 |
from bs4 import BeautifulSoup
import re
def parse_problem_statement(problem_code: str):
"""
This function takes a Leet Code problem code as input and
scrapes the problem statement from the site and returns
the parsed problem statement as a text file.
PARAMETERS:
-----------
problem_co... | cc20a7193f51ae6fb4627d546c0bb9e0d76b5e83 | 3,626,728 |
def get_name():
""" should return the name of the tool as listed on http://qcomp.org/competition/2020/"""
return "PET" | b26b13117711c7943392cde96244afe496cc9cc4 | 3,626,730 |
def gabby_gums_dark_green() -> Colour:
"""A convenience function that returns a :class:`Colour` with a value of 0x508787 (R80, G135, B135)."""
# discord.Color.from_rgb(80, 135, 135))
return Colour(0x508787) | fcf5f7b3669ee2bb92fb433238cbe6257497df23 | 3,626,731 |
def compute_average_oxidation_state(site):
"""
Calculates the average oxidation state of a site
Args:
site:
Site to compute average oxidation state
Returns:
Average oxidation state of site.
"""
try:
avg_oxi = sum([sp.oxi_state * occu
f... | 8ea8611984f171a84a2bac17c0b49b70c85bfba4 | 3,626,732 |
def lookup_zones(output_file=None,opts=None):
"""
This data source provides a list of available zones in the current region.
> This content is derived from https://github.com/terraform-providers/terraform-provider-ucloud/blob/master/website/docs/d/zones.html.markdown.
"""
__args__ = dict()
... | de507b4d8b02281975b7cd8da003a556d41ed62f | 3,626,734 |
from pypy.objspace.std.listobject import W_ListObject
def PyDict_Next(space, w_dict, ppos, pkey, pvalue):
"""Iterate over all key-value pairs in the dictionary p. The
Py_ssize_t referred to by ppos must be initialized to 0
prior to the first call to this function to start the iteration; the
function ... | f3e9591f6c0b21b9e64327d838da7086f08e1a10 | 3,626,735 |
import torch
def load_point_cloud(filename, min_norm_normal=1e-5, dtype=torch.float64):
"""
Load a point cloud with normals, filtering out points whose normal has a magnitude below the given threshold.
:param filename: Path to a PLY file
:param min_norm_normal: The minimum norm of a normal below which... | c3bbd81aec581f6fcd9cd23a62beb4523cb2d783 | 3,626,736 |
import math
def cos(x, offset=0, period=1, minn=0, maxx=1):
"""A cosine curve scaled to fit in a 0-1 range and 0-1 domain by default.
offset: how much to slide the curve across the domain (should be 0-1)
period: the length of one wave
minn, maxx: the output range
"""
value = math.cos((x/peri... | e3119dc71c1b6c6160a29dca37b51b0550479a83 | 3,626,737 |
def get_terms(num_distinct_documents=500,
remove_stopwords=False,
stopwords=[',', '.', '-', '\xa0', '“', '”', '"', '\n', '—', ':', '?', 'I', '(', ')']):
"""
Creates TermGenerator, and parses the documents for a specific set of documents.
:param num_distinct_documents: (int) Passe... | 0e57798596560eb00593e40217af8a43ba409d6e | 3,626,738 |
from typing import List
from typing import Dict
def cli(argv: List[str], renderer: Renderer, commands: Dict[str, Command]):
"""
Command Line Interface
Handles the incoming console input.
:param argv: Raw list of arguments.
:param renderer: The renderer service to print messages.
:param comma... | 474506d5f85ba999e3ce925c42b3960cce74950f | 3,626,741 |
def calc_crossproduct_flow(vU,vV,btU_in,btV_in,elev,bt_depth,mtime):
"""
Calculates the discharge(flow) by finding the cross product of the water
and bottom track velocities. **elev and bt_depth are positive**
Inputs:
vU = U velocity, 2D numpy array, shape [ne,nb] {m/s}
vV = V ve... | e63ec733987d41a4a6c31f7c8d4f72c677d08a93 | 3,626,742 |
def reverse_mutation(perm, *args):
"""
Performs a reverse mutation on a permutation
"""
n = len(perm) - 1
i = np.random.choice(n, 1)[0]
perm[i:i+2] = perm[i:i+2][::-1]
return perm | bdcb517ef247a9c7effd2ae3955a0ff1831bf943 | 3,626,743 |
def MTL_loss(device, batch_size, ndata=0, contrastive_loss=False):
"""Returns the learned uncertainty loss function."""
# task_rot = LearnedLoss('CrossEntropy')
task_contrastive = LearnedLoss('Contrastive', batch_size=batch_size)
task_recons = LearnedLoss('L1')
task_NCE = LearnedLoss('NCE', nda... | af673c91956d36e600482d35d7245cf9cd65a9f3 | 3,626,745 |
def non_commutative_sympify(string: str):
"""Evaluates sympy string in non-commutative fashion.
This function was taken from stack overflow answer by @ely
https://stackoverflow.com/a/32169940
"""
parsed_expr = parse_expr(string, evaluate=False)
new_locals = {
sym.name: Symbol(sym.name,... | c7efba92223543a4e322fc3f9b72d1d2cd6e3f58 | 3,626,746 |
def parse_last_name(name_string):
"""
isolates last name in a name string extracted from a record
args:
name_string: str, entire name
returns:
last_name: str, with removed diactritics and in uppper case;
may include value of subfield $b
"""
try:
last_na... | dfc833329b0c44f8b027a3fdc7d02a56433adf71 | 3,626,747 |
def generate_neighbours(pattern: str, mismatches: int) -> set:
"""
Generate neighbours for the given pattern (genome string)
:param pattern: genome pattern
:param mismatches: number of mismatches to generate neighbours
:return: a set of patterns in the neighbourhood, including the 'pattern' itself
... | f919b8e09463a1096ca1aadaabe4284db674c0d7 | 3,626,748 |
def head_pose_preprocess(imgs):
"""
Preprocesses the image(s) and face detections for the head pose estimator.
Parameters
----------
imgs: NumPy array
The image(s) to format with values in the range [-1, 1].
Returns
-------
input_hp: NumPy array
Formatted image(s).
... | 9f2bac85daefae6dcd4fac53c7a498f8f74360fc | 3,626,749 |
def two_sum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
mid = target - nums[i]
for j in range(i + 1, len(nums)):
if nums[j] == mid:
return [i, j] | 465ddfa8fd02add40426f803276b0c3fdf193599 | 3,626,751 |
import pandas
def filter_useful_paths_into_a_dataframe(path_list):
"""
Classifies the file types of the paths we actually care about then finegles them into a DataFrame.
"""
print("Gathering metadata.")
paths_we_actually_care_about = [path for path in path_list if filetype_of(path) != "unsorted"... | 0834fe3d665610e566ea7c8bc018664b5d167f88 | 3,626,752 |
def pivottab(d, rowkey, columnkey, reducefn, duplicates=False):
""" A simple pivot table generator based on 2 key indexes and a reduce function
Parameters
----------
d: dict like structure
data container (SimpleTable or DictDataFrame)
rowkey : str
Values to group by in the rows
... | ba2b651674e77b2b2bc945bc3910e79e060ca1a2 | 3,626,753 |
def paseto_required():
""" """
def wrapper(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not hasattr(current_app, "paseto_verifier"):
raise ConfigError("paseto_verifier is not set in the current_app.")
if not current_paseto.is_verified:
... | 27cef6babb07b442760e1a977b5ab1661db7f973 | 3,626,754 |
def mean_of_list(list_in):
"""Returns the mean of a list
Parameters
----------
list_in : list
data for analysis
Returns
-------
mean : float
result of calculation
"""
mean = sum(list_in) / len(list_in)
return(mean) | fac8f40b86e7fa37f96a46b56de722c282ffc79c | 3,626,755 |
def delazi(lat1, lon1, lat2, lon2):
"""delazi(double lat1, double lon1, double lat2, double lon2)"""
return _Math.delazi(lat1, lon1, lat2, lon2) | 8c71700387d742147cf7f98a6cd2f5532b88ab6e | 3,626,756 |
def preliminary_register_user():
"""Администратор может добавить предопределенного пользователя (студента или преподавателя)
"""
answer = blank_resp()
try:
if current_user.status != 'admin':
raise Exception('Only admins can do preliminary registration')
form = PreliminaryRe... | d3237ad9040f7c6cc2ddab49687f05278fb2c1b1 | 3,626,758 |
from collections import OrderedDict
def read_markers_gmt(filepath):
"""
Read a marker file from a gmt.
"""
ct_dict = OrderedDict()
with open(filepath) as file_gmt:
for line in file_gmt:
values = line.strip().split('\t')
ct_dict[values[0]] = values[2:]
return ct_... | a45ed9da13c9ba4110bb4e392338036a32a58e60 | 3,626,759 |
def num_decimal_part(value: float) -> float:
"""Return the decimal part of a floating point number.
Parameters
----------
>>> num_decimal_part(-2.1)
-0.1
>>> num_decimal_part(2.1)
0.1
"""
return value - num_truncate(value) | 2054c5818ba488e8987b40f6310c073cff638d7a | 3,626,760 |
def partition_sort(arr):
"""
An idyllic variant of quicksort, powered by numpy.partition.
"""
if arr.shape[0] < 2:
return arr
mid = arr.shape[0] // 2
partitioned = np.partition(arr, mid)
sm = partition_sort(partitioned[:mid])
lg = partition_sort(partitioned[(mid+1):])
... | ca35ebcbafbdf50a5e98172bfcf85e3bfe1c5678 | 3,626,762 |
def _phase_from_label(label):
"""Return the phase from a label"""
# Returns None if label is invalid
label = label.replace("+", "", 1).replace("1", "", 1).replace("j", "i", 1)
phases = {"": 0, "-i": 1, "-": 2, "i": 3}
if label not in phases:
raise QiskitError("Invalid Pauli phase label '{}'"... | 7d23540148b0951123dc0db19daec10108b0b09b | 3,626,763 |
def inverse_metric_tensor(basis):
"""
Compute the inverse metric tensor for a basis.
:param basis: Basis (square matrix with basis vectors as columns).
:return: Inverse metric tensor.
"""
g = metric_tensor(basis)
if not isinstance(g, np.ndarray):
# Assume scalar
return 1 / g... | 461f2a0894611e032b82a3f83f84be4f0e16334e | 3,626,765 |
import logging
def get_all_annots(annotations):
"""
All annotations
"""
all_annots = set()
for genome in annotations.keys():
for annot_name in annotations[genome].keys():
all_annots.add(annot_name)
logging.info(' No. of annotation columns: {}'.format(len(all_annots)))
... | 98270d18fbc8ded648a16178087037b1319263d4 | 3,626,767 |
def get(guild):
"""
Gets a single GuildSettings Object representing the settings of that guild
:param guild:
:return Single GuildSettings Object: :type GuildSettings:
"""
return GuildSettings(guild) | c5d3fa1fae0a6347b498a89ec26eb2bd47baee7b | 3,626,768 |
from pathlib import Path
def process_attachments(path_to_content_file: Path, set_of_links: set[str], note_paths: set[Path],
source_absolute_root):
"""
Generate sets of attachment links from content.
The sets of links based on the status of that links.
all - all links found... | 0ba8f4ba2643cdc9d43998db33d09a36a9375ec3 | 3,626,769 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.