content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_default_session_id() -> int:
"""Returns seesion id for setup and teardown"""
return -1 | 92459ec94e27fd21d88ff21969e4adb2f2b9f422 | 632,649 |
def run(program: list[str]) -> tuple[str, str]:
"""I could not figure this out on my own at all.
At first, I tried implementing the ALU and simply running the program. But of course
that would take way too long to finish. Then I tried converting the input to a set
of equations but that failed, too. So i... | c82d9608dd93a2f4b1c6f52e0a1aa497721eefe6 | 632,650 |
def simple_integrate(f, x):
"""
Numerical integration of a function over an interval x using compositve trapezoid rule
Parameters
----------
f : list
Function that is defined over the interval x, and is valued at the upper and lower bounds of x.
x : list
List that defines the in... | 6b4ef6e6f97829730828b81f973f1c774c5fc3d3 | 632,651 |
def batch_matrix(w, batch_size):
"""
batch a weight matrix
:param w: [M, N]
:param batch_size: B
:return: [B, M, N]
"""
return w.unsqueeze(0).expand(batch_size, -1, -1) | c13e3f83cb72b5c4b24166df5ad58697660fc8e4 | 632,652 |
def diff_dicts(dicts, ignore=None):
""" Given a sequence of dicts, returns
common, [difference1, difference2, ...]
where `commmon` is a dict containing items in all dicts, and `differenceN` is a dict containing keys
unique to the corresponding dict in `dicts`, ignor... | b457894020c0b47e1fdabcd20d9e1af5aec0617d | 632,653 |
import numpy
def adjust_genome_length(genome2families):
"""reduce expected number of gene-families, in case of only 1,2 or 3 ref. genomes in DB"""
num_ref_genomes = len(genome2families.keys())
avg_genome_length = int(numpy.median([len(genome2families[g]) for g in genome2families]))
orig_avg_genome_le... | a4b395de8bb0114733bcab94becae8792cc934e1 | 632,654 |
def formartweek(week_num):
"""
格式化周期数,如1是周日
:param week_num: 数值
:return: 返回中文周
"""
week=['周日','周一','周二','周三','周四','周五','周六']
return week[week_num-1] | 18b4b18c4ab33384dcaf4dde646894836396e528 | 632,655 |
def get_driver_readiness(config: dict) -> str:
"""Get the code_readiness config setting."""
return config.get("code_readiness", "Release") | 43728632dde9e9235019dd06ffbc62ce9cf8679c | 632,656 |
def calc_tf(sentlst, word_tokens: bool = False, calctyp: str = "UNIQ"):
"""
tf = occurrences of word to other words in each tweet.
term frequency can be: word occurrences/unique words, occurrences/total word count,
or word occurrences versus most frequent word
:param sentlst: list of tweet str, dict... | e64903091486575f7fb97234b26d20b1b53581be | 632,657 |
import os
import socket
def host() -> str:
"""
Goal: get the current user logged in and the computer they are logged into
"""
return f"{os.getlogin()}@{socket.gethostname()}" | ed2bbc131ce8c82013033c684e130b7e3df0d81a | 632,659 |
def format_direction(direction):
"""
Examples
--------
>>> format_direction('ra')
'ra'
>>> format_direction('el')
'alat'
>>> format_direction('az')
'alon'
"""
lowerdir = direction.lower()
if lowerdir == 'el':
return 'alat'
elif lowerdir == 'az':
return... | d961ff38fd68b19a8a5975cb2fe1a80af09d8c56 | 632,661 |
def get_soundex(name):
"""Get the soundex code for the string"""
name = name.upper()
soundex = ""
soundex += name[0]
dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."}
for char in name[1:]:
for key in dictionary.keys():
if char in... | 251bef216c0338bd8b060a079799b9b424faa9ef | 632,662 |
def is_subsequence(subtext: str, text: str) -> bool:
"""
>>> is_subsequence('pe', 'apple')
True
>>> is_subsequence('ep', 'apple')
False
"""
if len(subtext) == 0:
return True
i = 0
for symbol in text:
if symbol == subtext[i]:
i += 1
if i == len(... | e0edd404af29cbfb1b6a510dcda3316701b369d9 | 632,667 |
import torch
def sequence_mask(seq):
"""
:param seq: 要生成mask的Tensor shape=(b,l)
:return: 三维 上三角Tensor shape=(b,l,l)
"""
batch_size, seq_len = seq.size()
mask = torch.triu(torch.ones((seq_len, seq_len), dtype=torch.uint8),
diagonal=1)
mask = mask.unsqueeze(0).expand(bat... | 6699b8aefc2e71ad091e5e2b5d2eeded9cb8fb41 | 632,668 |
def compoundPartitioning(agents):
"""Compute and return sections with compound criteria
agents is a dict with keys "d", "id", "od", "s", "is", "os"
with sectorialized_agents__ with each of these criteria
"""
exc_h=set( agents["d"][-1][2]) & \
set(agents["id"][-1][2]) & \
set(age... | 8e12b5451c4ef9d995599b5ea0bad87df2b7bfc5 | 632,669 |
import traceback
import os
import linecache
def structured_traceback(exc: Exception,
call_stack: traceback.StackSummary) -> str:
"""Return a nice text describing the call stack which threw an
exception.
Args:
exc (Exception): Exception raised.
call_stack (tracebac... | ac7a663d2fb6f2e251691ae5771bcb5c207745cf | 632,671 |
def check_popup_blocked(var_name, notification_div_id):
"""
Args:
String: var name is the variable that define the window to check
example: win_var_name = window.open();
"""
ret = '' +\
'if(!'+ var_name +' || '+ var_name +'.closed || typeof '+\
var_name +'.closed==\'undef... | 60e8b567985c0b94077f2d2e23b4a5138ddb28ea | 632,672 |
import posixpath
def posix_relpath(path, root):
"""posix.relpath() that keeps trailing slash."""
out = posixpath.relpath(path, root)
if path.endswith('/'):
out += '/'
return out | 38857168397f3e1fd9d26e106abf1582b9145831 | 632,673 |
import itertools
def combichem(reactant_1_SMILES: list, reactant_2_SMILES: list):
""" "
Gets all possible combinations between two uneven lists of
reactants
Args:
reactant_1_SMILES (list): List of reactant one smiles
reactant_2_SMILES (list): List of reactant two smiles
Returns:
... | bc28038dfb67374fdffaaa4b523b2e444d1eeab9 | 632,674 |
def get_subsecond_component(frac_seconds, frac_seconds_exponent,
subsec_component_exponent, upper_exponent_limit):
"""Return the number of subseconds from frac_seconds *
(10**frac_seconds_exponent) corresponding to subsec_component_exponent that
does not exceed upper_exponent_lim... | 5922cb41a6a9dcf0874ff353f657de062b8763f8 | 632,675 |
def is_fieldstrength_in(coll: list):
"""Check to see if there are any field strengths in `coll`."""
first = lambda f: str(f).split("D")[-1][0] # first non deriv
for f in coll:
if first(f) == "B" or first(f) == "G" or first(f) == "W":
return True
return False | 33bbe8cb55d00edb32eaba81478b79598c565052 | 632,677 |
import requests
def url_to_txt(url):
""" Get data from boxofficemojo.com using requests.
Check for status code 200.
Retrieve data for defined year.
"""
r = requests.get(url)
if r.status_code == 200:
html_text = r.text
return html_text
return None | e52526ca04a15e0ce206d3efa0f3f70cd5fdb19c | 632,678 |
import torch
def normalize_coords(coords, H, W):
""" Normalize coordinates based on feature map shape. coords: [B, 2, N]"""
one = coords.new_tensor(1)
size = torch.stack([one*W, one*H])[None]
center = size / 2
scaling = size.max(1, keepdim=True).values * 0.5
return (coords - center[:, :, None]... | f5d433cf74bdd876ba10953529f4261f8e6bc345 | 632,679 |
def flatten(x):
"""
Collapse image data from (C, H, W) to (C, H * W)
"""
return x.view(x.size(0), -1) | 0f8f47c249e3bdf8707672c66c68fdc07334a3e3 | 632,680 |
def try_split(arr, shift):
"""Try splitting arr into a 2-level trie with chunks of size 2**shift.
Return the two levels of the tree as dicts, as well as shift.
"""
table1, table2 = [], []
size = 2 ** shift
chunks = {}
for i in range(0, len(arr), size):
this_chunk = tuple(arr[i:i+si... | f36a630d45cb772379e3ddc1a8898942c683114d | 632,681 |
def array_to_list(inputarray, length):
"""Converts an "array" to a list.
That is, an array created by `int_list_to_array`,
`double_list_to_array`, etc.
"""
return [inputarray[i] for i in range(length)] | acfdea8aec8a7d65807304e7e06d6d4258937459 | 632,682 |
def posixSpec(paths):
"""Posix nuances for creating the executable script with java command"""
classPath = ["$CLASSPATH"]
classPath.extend(paths)
return ("sclera", "#!/bin/sh", ":".join(classPath), "$@") | 07d708fc83e3bb323be9f871625462b8c9a85f0c | 632,683 |
import os
def get_template(name):
"""Get template text from templates directory by name."""
root_dir = os.path.dirname(__file__)
template_path = os.path.join(root_dir, "formats", "%s.jinja" % name)
with open(template_path, 'r') as handle:
template = handle.read()
return template | 80383e18e3ddc2caf3b9b6ef6589f0d122a0b390 | 632,684 |
import hashlib
def QA_util_file_md5(filename):
"""
explanation:
获取文件的MD5值
params:
* filename ->:
meaning: 文件路径
type: null
optional: [null]
return:
str
demonstrate:
Not described
output:
Not described
"... | bf967cd1c4131058f194228b7d621a2edd2ddbbf | 632,685 |
def get_nested_dict(input_dict, key):
"""
Helper function to interpret a nested dict input.
"""
current = input_dict
toks = key.split("->")
n = len(toks)
for i, tok in enumerate(toks):
if tok not in current and i < n - 1:
current[tok] = {}
elif i == n - 1:
... | 02aba0c4ccd003d27f39e74ec52daadb0e1a59f7 | 632,686 |
import six
def fix_elsevier_xml_whitespace(document):
""" Fix tricky xml tags"""
# space hsp and refs correctly
for el in document.xpath('.//ce:hsp'):
parent = el.getparent()
previous = el.getprevious()
if parent is None:
continue
# Append the text to previous ... | cda53d10068697c3d9e36b86c2368f8471783110 | 632,687 |
def get_device(module):
"""Returns the device of the module's parameters."""
device = None
for param in module.parameters():
if device is None:
device = param.device
continue
if device != param.device:
raise ValueError("Parameters are allocated on differen... | bafe31920af4c4a7b2a853193a3924e78b0321a7 | 632,688 |
def obj_lookup(obj_list, property_dict):
"""
finds subset of obj_list by filtering the list according to provided property_dict
"""
def filer_obj_by_prop(obj, prop_dict):
for prop in prop_dict:
if getattr(obj, prop) != prop_dict[prop]:
return False
return Tr... | ad1a914300a98e9cb185ffd864f1136087f6808a | 632,689 |
def __json_res(success:bool,data:dict={},desc:str="",error_code:int=400, trace:str=""):
"""
创建 api 通用 json 返回值
:param desc: 说明 默认 None
:param data: 返回数据 默认 None
:param success: 成功与否
:param error_code: 错误编码 默认 400
:param trace: 错误信息 默认 None
:return:
"""
int_success = int(success)... | c72a38c72e6cddad44b59d554c6c11e76a9382f8 | 632,690 |
def get_model_constants(model_settings):
"""
Read constants from model settings file
Returns
-------
constants : dict
dictionary of constants to add to locals for use by expressions in model spec
"""
return model_settings.get('CONSTANTS', {}) | 1cc1ab41242a34f06f71bc7ee12404093233228d | 632,691 |
def trim_suffix(s, suffix):
"""Removes a suffix from a string if it exists"""
return s[: -len(suffix)] if s.endswith(suffix) else s | 604e8d1dc8e65e9bf80f46c5e3e05e844ecc12f9 | 632,692 |
def _HexAddressRegexpFor(android_abi):
"""Return a regexp matching hexadecimal addresses for a given Android ABI."""
if android_abi in ['x86_64', 'arm64-v8a', 'mips64']:
width = 16
else:
width = 8
return '[0-9a-f]{%d}' % width | 7bd2dca89dcfe95a44e5a35c947fb158d2e97755 | 632,693 |
def _fbeta_score(beta, p, r):
"""Compute the F-beta score for a given precision and recall."""
return (1 + beta ** 2) * (p * r) / ((beta ** 2 * p) + r + 1e-100) | ab76859c8fd199c0882ff2a0f65428d845d0bcdc | 632,695 |
import subprocess
def _convert_to(audio_format, filename):
""" Converts a wav audio file into a provided audio format
Args:
audio_format (str): format of audio (assuming correct - ogg|mp3)
filename (str): path of the file with its name
(assuming has ext... | 16b5668b2239edc8b58865f0143e8f3561bf76bd | 632,696 |
def clean_adduct(adduct, add_brackets=False):
"""
Harmonizes adducts.
:param adduct:
:param add_brackets: add [M+H]+ brackets that are removed during clean up (True or False)
:return: M-all losses+all additions CHARGE
"""
new_adduct = adduct
new_adduct = new_adduct.replace("[", "")
n... | 128635015e5d7837d25e2fca63a5d5e0e8c82ff4 | 632,697 |
def solution(A, B):
"""
Codility 100%
https://app.codility.com/demo/results/trainingF5HTCA-YFV/
Idea is to use stack concept
For each iteration if current fish is of type 1 add it to stack 1 fish
Create stack 1 fish - it always holds the downstream ie 1 kind of fish
and keep killing th... | b5a0a3514c764681a23a91993f299626413641d6 | 632,698 |
def LineIsComment(line):
"""Whether this entire line is a comment (and whitespace).
Note: This doesn't handle inline comments like:
[ # Blah blah.
But we discourage those in general, so shouldn't be a problem.
"""
return line.lstrip().startswith('#') | 4ff54a136b59541d95d33fd24c4edb703a7c6bcb | 632,699 |
def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
... | ee73851222e0af97654d4db6853226969bd59c01 | 632,700 |
def _getMultiElemText(parentElem, elemName, topKey, bottomKey):
"""
XML parsing helper function to return a 2-level dict of multiple elements
by a specified name, using topKey as the first key, and bottomKey as the second key
"""
elems = parentElem.findall(elemName)
result = {} # 2-level dictionary of items, keye... | 5fe306f935e9174be2653800b3767ae0f998c878 | 632,702 |
import math
def finalInstances (instances, averageUtil):
"""
:type instances: int
:type averageUtil: List[int]
:rtype: int
"""
ptr = 0
while ptr < len(averageUtil):
if 25 <= averageUtil[ptr] <= 60:
ptr += 1
elif averageUtil[ptr] < 25 and instances > 1:
... | 9f0e4434989ddadd84964aa666164e5a76373c4c | 632,703 |
def set_index_as_article_number(df):
"""
:param pd.DataFrame df:
:return: pd.DataFrame
"""
# Makes the index a column in df, which we can use as article_no
df = df.reset_index()
# We want to rename the index column, but since that is difficult (cuz I no want to Google)
# we are copying i... | 8bd39d9b7ca1f76514f1f85dc334d496bfa85ed2 | 632,704 |
def bad_filename_fixture():
"""An example of a bad filename"""
return 'oops.csv' | 82ea52dd328ed2fc0d547bd920bf72ddcb02e31c | 632,705 |
def get_metric_fqdd_tree(metric_fqdd_mapping: dict):
"""get_metric_fqdd_tree Get Metric-FQDD Tree
Get metric-fqdd tree for grafana
Args:
metric_fqdd_mapping (dict): metric-fqdd mapping
"""
partition = 'idrac'
metric_fqdd_tree = {
'name': 'root',
'children': []
}
... | 21127bae9b4a8781e1757a76fc0c5bfe9f52b739 | 632,706 |
import random
def hill_climb(domain, fitness_function, seed=random.randint(10, 100), seed_init=True, init=[], epochs=100):
""" Simple Hill Climbing algorithm implemented
Args:
domain (list): List containing the upper and lower bound.i.e domain of our inputs
fitness_function (function): This p... | 03a12b553b3d9c43ce4d7cab1a3bc4ef0981c8b5 | 632,708 |
def remove_letter(letter, string):
"""Removes all occurrences of a given letter from a string."""
string_without_letter = string.replace(letter, '')
return string_without_letter | 175b29138a534e45e413da58f4b5cca5dbfdf425 | 632,709 |
def dummy_training_data(dummy_dataset):
"""Returns training data from `dummy_dataset`.
"""
training_data = {'x_train': [dummy_dataset.idx_seq['train']['word'],
dummy_dataset.idx_seq['train']['char']],
'x_valid': None,
'x_test': None,... | 88aadbd07b26293f831c8c1fed75d1982305c906 | 632,710 |
def vector_subtract(u, v):
""" return u - v """
return tuple((a - b) for a, b in zip(u, v)); | 8959dec2a601ae9badab68c25a4999e6e5c012d3 | 632,711 |
import re
def seq_validator(sequence):
"""
Checks if the sequence provided is valid fasta sequence. Returns True
if the sequence is valid, otherwise returns False.
sequence: A string for validation
"""
# checks for ascii characters that should not appear in a fasta sequence
seq_val = re.... | b44d01ea38077e456eda7f3f050a3fdf4045fdca | 632,712 |
import torch
def ppo(diff, loss, eps):
""" paper : https://arxiv.org/abs/1707.06347
+ using grads from policy probabilities, clamping them...
- however not efficient to use with replay buffer ( past action obsolete, ratio always clipped )
"""
# print("PPO")
ratio = diff.exp()
su... | 87dc7abc71c14042d95b34a7d3a5b5eaa47d2619 | 632,713 |
def get_role(username, role_db):
"""Take username from user and return its role.
"""
return role_db.query.filter(role_db.username == username).first() | 2a6ab43fad76d8b41b0d20730bf03b2699573709 | 632,714 |
def add_corner_pt_to_dic(pt1, pt2, pt3, pt4, vec_x, vec_y, dic):
"""
Return dictionary of measured values and
also new averaged measured values.
"""
min_x = min(vec_x)
max_x = max(vec_x)
min_y = min(vec_y)
max_y = max(vec_y)
for (i, pt) in enumerate([pt1, pt2, pt3, pt4]):
t... | 73f783a0eb03703d255485e8cd0ecf9688a7f989 | 632,715 |
def remove_empty_parameters(data):
"""Accepts a dictionary and returns a dict with only the key, values where the values are not None."""
return {key: value for key, value in data.items() if value is not None} | 4448556ffd3fe20a651986396c6b724ce6157f4f | 632,716 |
def get_object_value(value) -> str:
"""Get value from object or enum."""
while hasattr(value, "value"):
value = value.value
return value | d8a47381fd7df5595ef3dbe34e24b23624eddb5d | 632,717 |
def get_transport_options_impl(string):
"""
Parse transport options.
:param str optstring: Example input: 'scramblesuit:k=v;scramblesuit:k2=v2;obs3fs:k=v'
:returns: {'obfs3': {'k':'v'}, 'scramblesuit': {'k2' : 'v2', 'k' : 'v'} }
"""
transport_args = {}
params = string.split(';')
for par... | 3b1c2289c8d1b1b1b5c36aab49c663aaa067c37b | 632,718 |
import os
def IsGeeServerInstalled():
"""Check if GEE Server is installed."""
gee_server_start_script = '/etc/init.d/gefusion'
return os.path.exists(gee_server_start_script) | d6e7cdcf82082a8be971494ff802b28009e8e497 | 632,719 |
import os
def multi_cluster_tests_enabled():
"""
Returns true if the COOK_MULTI_CLUSTER environment variable is set,
indicating that multiple cook scheduler instances are running.
"""
return os.getenv('COOK_MULTI_CLUSTER') is not None | 8faae69bf56493b96fa5e6967e9734fec643522e | 632,721 |
def find_sponsor(sponsorid, sponsor_dictionary):
"""
Given a sponsorid, find the org with that sponsor. Return True and URI
if found. Return false and None if not found
"""
try:
uri = sponsor_dictionary[sponsorid]
found = True
except:
uri = None
found = False
... | 390b1473c577f788c15394f0e4ce9d0ab2478c18 | 632,723 |
def evaluate_parameters(rule_parameters):
"""Evaluate the rule parameters dictionary validity. Raise a ValueError for invalid parameters.
Return:
anything suitable for the evaluate_compliance()
Keyword arguments:
rule_parameters -- the Key/Value dictionary of the Config Rules parameters
"""
... | 8bbcb91bd7fa8ba4e39beeac09cc41b1d8bad3ce | 632,725 |
from typing import List
def get_feature_names() -> List[str]:
"""Get feature names
Returns:
feature_names (List[str]): Title of features
"""
time_signal_names = [
"tBodyAccXYZ",
"tGravityAccXYZ",
"tBodyAccJerkXYZ",
"tBodyGyroXYZ",
"tBodyGyroJerkXYZ",
... | dfdfe8b7591ce7e9ef0b9066bbcea026890b2f08 | 632,727 |
import re
def _parse_mcd_channel(attr: dict) -> str:
"""Extract channel and label from MCD channel XML data."""
if attr["ChannelName"] in ("X", "Y", "Z"):
return attr["ChannelName"]
if attr["ChannelLabel"] is None: # Use ChannelName to create label in right format
label, mass = re.findall... | 8a675ce554dc61c02590df909271e8d7186c4cb9 | 632,729 |
def qmf(h):
"""Returns the quadrature mirror filter of a given filter"""
g = h[::-1]
g = g.at[1::2].set(-g[1::2])
return g | 03ccf8078a192ff191cb0228d170426fbe53b7f1 | 632,730 |
import os
def get_root_path(current_script_path):
"""
Return the root path of the project
:param current_script_path:
:return:
"""
parent_path = os.path.normpath(current_script_path + os.sep + os.pardir + os.sep + os.pardir)
return parent_path | c8b5aae4b2d5fefc1fa7e87ce287a7a3f279d562 | 632,731 |
def opacity_button(data_ix, mean_ix):
"""Configures opacity drop down menu.
Args:
data_ix: iterable with data index at 1 and mean index at 0.
mean_ix: iterable with data index at 0 and mean index at 1.
Returns:
opacity_menu: config dict for layout
"""
reset_opac = [1] * le... | 6363d6c445b38acb85f10c73ba260a48156dc401 | 632,732 |
def graph_search_duplicated_value(sequence):
"""
A graph search for the duplicated value.
O(n) - time
O(1) - space
"""
# 1. Get inside the cycle
max_number = len(sequence) - 1
pos_in_cycle = max_number + 1
for _ in range(max_number):
pos_in_cycle = sequence[pos_in_cycle - 1... | 749144c4758b8b1829814e30179df0145c9ab13e | 632,733 |
def _format_block_id(chunk_num):
# type: (int) -> str
"""Create a block id given a block (chunk) number
:param int chunk_num: chunk number
:rtype: str
:return: block id
"""
return '{0:08d}'.format(chunk_num) | 84599f595974c2c8528445cfa89c175a47f19337 | 632,734 |
def get_list_for(db, participant_id):
"""Return a listing of communities.
:database: One SELECT, multiple rows
"""
if participant_id is None:
return db.all("""
SELECT c.*
FROM communities c
ORDER BY nmembers DESC, slug
""")
else:
return d... | 311ea86f5e6e9ff3b3bcd836a38bedbdaeb73555 | 632,736 |
from typing import Counter
def sort_moas(cpds_moa):
"""
Sort MOAs based on the number of compounds that are attributed to them in ASCENDING order.
This is HIGHLY Required before performing the compounds split into train & test.
"""
cpds_moa_split = {cpd:cpds_moa[cpd].split('|') for cpd in cpds_moa... | 3753d6870781e60a5e094db47556b393ee501fc1 | 632,740 |
from typing import Callable
def similarize_distance(distance_measure: Callable) -> Callable:
"""
Takes a distance measure and converts it into a information_density measure.
Args:
distance_measure: The distance measure to be converted into information_density measure.
Returns:
The in... | f35a81e2cbc011f2559e0eb7e25cc45400a11fc0 | 632,741 |
def _gutter(idx, offset, max_val):
"""
When deleting rows and columns are deleted we rely on overwriting.
This may not be the case for a large offset on small set of cells:
range(cells_to_delete) > range(cell_to_be_moved)
"""
gutter = range(max(max_val+1-offset, idx), min(idx+offset, max_val)+1)... | efb2fd9dce4a60303aa9b20d5866482a634c0230 | 632,742 |
def mat_tris(mesh):
"""Returns dict: mat_name -> list_of_triangle_indices"""
m_ps = {}
idx_tri = 0
for p in mesh.polygons:
mat = mesh.materials[p.material_index] if mesh.materials else None
mat_name = mat.name if mat else "__BDX_DEFAULT"
if not mat_name in m_ps:
m_p... | 28bafb86c6127567eed78a08ba69d9fe2cb6d777 | 632,743 |
def diff(runs_1, runs_2, subset=None):
"""
The rows of the two dataframes must have the same setting.
"""
subset = subset or ['ACC', 'AUC', 'TSS', 'HSS', 'BSS']
runs_diff = runs_2.copy()
runs_diff[subset] -= runs_1.loc[:, subset].values
return runs_diff | b1618987ad63c2da84807a2ea1fa175bd95a52de | 632,744 |
def invert(x):
"""
AOD - Delete o operador.
AOR - Troca o operador
"""
return -x | f9f81ad158a9a0f9ed90d15ec6b9df46aeec484f | 632,746 |
def get_confirm_token(response):
"""
The helper function for download_file_from_google_drive()
"""
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None | c027637db484b10621142c8854153f031f00f45e | 632,747 |
import re
def parse_range(range_str):
"""
Generates an object of type range for the specified range.
Parameters
----------
range_str : str
A string indicating a range. Corresponds to either of the
following formats.
* '[0-9]+'
* '[0-9]+-[0-9]+'
Returns
--... | c6cff389a80ff05af5b409194476dadadfe92358 | 632,749 |
def get_policy_descriptions():
"""Gets the descriptions for each policy."""
return {"rov": ("Block route announcements using standard"
" Resource Certification (RPKI) Route Origin"
" Validation (ROV) as defined in RFC 6811"),
"invalid_asn": ("Block route anno... | 9a8c22f1d33add09978f14a4a985abde319adfa7 | 632,750 |
def getsize(data):
""" return smallest possible integer size for the given array """
maxdata = max(data)
assert maxdata < 2**32
if maxdata < 256:
return 1
elif maxdata < 65536:
return 2
else:
return 4 | 530f58a3ab53ad163b9624c5a1a90d7932a7ed9b | 632,751 |
import struct
def ntoh(buf):
"""Convert to network order.
:param buf: Bytes to convert
:type buf: bytearray
:returns: int
"""
if len(buf) == 1:
return buf[0]
elif len(buf) == 2:
return struct.unpack('!H', buf)[0]
elif len(buf) == 4:
return struct.unpack('!I', bu... | 0e2f4c06be01023fca88ba118496a536b1b747b8 | 632,755 |
import torch
def sequence_mask(lengths, max_seq_length=None, dtype=torch.bool):
"""
Returns a mask tensor representing the first N positions of each cell.
lengths: integer tensor, all its values <= maxlen.
max_seq_length: scalar integer tensor, size of last dimension of returned tensor.
Default is the ma... | 2f6261c37c2a3ccc32d615e314e3251333f258c9 | 632,756 |
import os
def create_path(args):
"""
Function that creates a path for the results based on the model arguments.
Inputs:
args - Namespace object from the argument parser
Outputs:
path - Path where to store the results
"""
# create the path
path = os.path.join(
args.... | 784e4f3ab0b8af98b68ca2f623d1de553b9454ff | 632,757 |
def add1(x):
"""
Add 1
>>> add1(2)
3
"""
return x + 1 | a83ee46bfdd42f3fbcc194b7d082b5dd70958144 | 632,758 |
import typing
def canonicalize_headers(
headers: typing.Union[typing.Dict[str, str], typing.List[typing.Tuple[str, str]]]
) -> typing.Dict[str, typing.List[str]]:
"""
HTTP headers are case-insensitive. Join equivalent headers together.
"""
if isinstance(headers, dict):
headers = [
... | 32d6a7218e8f56c97e132f89ed5e2084b1d9fb9f | 632,759 |
def is_label_dataframe(label, df):
"""check column label existance"""
setdiff = set(label) - set(df.columns.tolist())
if len(setdiff) == 0:
return True
else:
return False | 3e8c43016d985cbaa3e47119a084f53170c891b3 | 632,760 |
def enUygunBul(rDegerleri):
"""
Yaklaşılan polinomların r değelerini karşılaştırarak en uygun polinomun derecesini bulur.
:param rDegerleri: Polinomların r değerleri. Liste tipinde olmalı.
"""
r,derece=abs(1-rDegerleri[0]),0
for i in range(1,len(rDegerleri)):
if(abs(1-rDegerleri[i]) < r)... | cd1dffc812deb3bedec646e202c21e6c5ae8a058 | 632,762 |
def weight_path(spec_path, element_path):
"""Determine the weighting number for a matchingRule path spec applied to an actual element path from a
response body.
Both paths are passed in as lists which represent the paths split per split_path()
In spec version 2 paths should always start with ['$', 'bo... | e788062422db9c247c94cac1ca367774c318b227 | 632,763 |
import platform
import struct
def _ioc_encode(direction, number, structure):
"""
ioctl command encoding helper function
Calculates the appropriate spidev ioctl op argument given the direction,
command number, and argument structure in python's struct.pack format.
Returns a tuple of the calculated op and the... | b3f8ac548f767cdb86fbcd0e9819a2d693d24bc9 | 632,764 |
def pluralize(text: str, amount: int) -> str:
"""'Pluralizes' a string if a given amount is plural.
Example:
pluralize('egg', 2) -> 'eggs'
pluralize('python', 1) ->
"""
return text + 's' if amount > 1 else text | 6b2c758e769c97dd8ed5f16fd35ea7bbe93ad0e5 | 632,765 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Age-gender model')
parser.add_argument('--gpu', help='GPU id to use', default=0, type=int)
parser.add_argument('--compute_mode', type=str, choices=['CPU', 'GPU'], def... | 165d7e316115083b01c268047a20067784188bd4 | 632,766 |
def component(
cashflows, from_date, to_date, with_rate
):
"""
Discounts cashflows
:param df: Dataframe
:column cashflow_columns: column(s) should be in the table
:column disc_rate_column: column(s) should be in the table
base to compute
:param cashflow_columns: list
con... | 2e5cb74af7f1e3523e86c84a88ae6ad63f454ee0 | 632,767 |
def usingPerformanceTimers():
"""
usingPerformanceTimers() -> True if on, False if off
Return true if performance timers are in use.
"""
return bool() | e4b01472eb121b8705fabb7bcd20f61860b6423f | 632,768 |
import hashlib
import os
def get_cache_dir(project_dir: str) -> str:
"""Compute cache directory to be used based on project path."""
# 6 chars of entropy should be enough
cache_key = hashlib.sha256(os.path.abspath(project_dir).encode()).hexdigest()[:6]
cache_dir = "%s/ansible-compat/%s" % (
os... | 698fd9759dbcbe946926df933676499a9882285e | 632,769 |
def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param ... | 47bf68cb638329d3632670fbad84d0acd8ce8ef5 | 632,770 |
def word_processor(current):
"""
:param current: lst, store the new order of the characters provide by user
:return string: str, string version of current
"""
string = ''
for i in range(len(current)):
ch = current[i]
string += ch
return string | 9e92980ee6160a5fa956a644afcbd01db48e9add | 632,772 |
def export_network(name: str, batch_size: int, *args, **kwargs) -> str:
""" Exports a network by name and returns the path to the output file.
@param name Network name (options: simple_cnn, deep_mnist, resnet, wide_resnet).
@param batch_size Minibatch size to use
@param args Other arguments... | 5a0fe120f5c0cf0388b1b857d4a0a86156e22586 | 632,773 |
import torch
def heaviside(data):
"""
A `heaviside step function <https://en.wikipedia.org/wiki/Heaviside_step_function>`_
that truncates numbers <= 0 to 0 and everything else to 1.
"""
return torch.where(
data <= torch.zeros_like(data),
torch.zeros_like(data),
torch.ones_l... | ee30354de0ccb40dc9b2b9cf9559328891ab7f4e | 632,775 |
def expand_cli_args(args):
"""
Expand a list of possibly comma separated arguments, removing duplicates.
:param args: The list of arguments to expand.
:return: The set of unique arguments.
"""
items = set()
for arg in args: # "a.jpg,b.png"
for arg_ in [n.strip() for n in arg.split(... | 531e005fffd6bf0d9f7607faac17560c94be656a | 632,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.