content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sumTransactions(account):
"""
Takes in account object and returns the total native currency spent on that wallet.
This includes the total amount of native currency spent minus the amount received if any was sold.
"""
transactions = account.get_transactions()
transactionTotal = 0
for tran... | 60ee106ba2a34122a47ba47a8fad16d44cc273ae | 659,611 |
import sys
def args_to_dict(func, args):
"""
Returns argument names as values as key-value pairs.
@input `func` that is a function object
@input `args` argument list that the functions is called with
"""
if sys.version_info >= (3, 0):
arg_count = func.__code__.co_argcount
... | 768ef2ee611f25af0dc594fc20be35c6b96ea3d6 | 659,612 |
from datetime import datetime
def current_datetime():
"""Returns string of current date and time."""
return datetime.today().strftime("%Y%m%d%H%M") | f2947624528c9d81ca000cbb1d6864691e4a6db6 | 659,613 |
import os
def sample_names(files, extension, pair_identifier=None):
""" Return the basenames of the files, without any extensions, as the sample names
Args:
files (list): A list of files (with or without the full paths)
extension (string): The extension for all files.
pair_identifier (string): The string in ... | ff15caf3df856cb5c385cf77bf60309eb93d2635 | 659,614 |
import glob
import re
def find_vasp_calculations():
"""
Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories.
"""
dir_list = [ './' + re.sub... | d86742df1d5dd2c994c2bcc8f7e5955279ec5a71 | 659,615 |
def correct_world_coords(coords, path):
"""Two activties for subject S9 have erroneous coords, they are horizontally shifted.
This corrects them. Use --dataset=h36m-incorrect-S9 to use the erroneous annotation."""
if 'S9' in path and ('SittingDown 1' in path or 'Waiting 1' in path or 'Greeting.' in path):
... | d33f26db2d1f83b5d87d0e119532734ed31bdb58 | 659,616 |
def AnvilSimulator(target, sacrifice, newName=''):
#https://minecraft.gamepedia.com/Anvil/Mechanics#Combining_items
"""Simulates anvil mechanics"""
"""sacrifice can be NULL if setting the target name"""
#Repairing is not yet supported
xpCost = None
if(sacrifice == None and newName):
i... | 2127874f99c0d17f2d4631731501570c79807229 | 659,617 |
import os
def get_mime_type(file):
"""Get the MIME-type of the specified file. It uses the file's extension.
Currently supported: xlsx, pdf, csv.
"""
ext = os.path.splitext(file)[1].lower()
return {
".xlsx" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".p... | 7cdf404ae5b35f9aef1de94019ab1a357bb456ad | 659,618 |
from pathlib import Path
def make_file(dir: Path, f: Path):
"""outputs a file in a dir using the current file features"""
output = dir / (f"{f.stem}_cookies{f.suffix}")
if not output.exists():
output.touch()
return output | 39ede7a7622451709a8b7bb53e7b18e10e227306 | 659,619 |
def get_value(vector):
"""Convert a byte-vector string into an integer"""
if len(vector) == 0:
return 0
vector = [ord(c) for c in vector]
sign = 1
if vector[0] & 0x80:
vector[0] = (vector[0] & 0x7f)
sign = -1
value = 0
for c in vector:
value *= 256
... | 8080ab0e30e555326edfd8fadf0e5fb6d83b6ee5 | 659,621 |
def eia_mecs_URL_helper(build_url, config, args):
"""This helper function uses the "build_url" input from flowbyactivity.py, which is a base url for coa cropland data
that requires parts of the url text string to be replaced with info specific to the usda nass quickstats API.
This function does not parse th... | 1508f27bfff285f0e86a03f43c58959454e8a91f | 659,622 |
import linecache
def checkline(filename, lineno, ui):
"""Return line number of first line at or after input
argument such that if the input points to a 'def', the
returned line number is the first
non-blank/non-comment line to follow. If the input
points to a blank or comment line, return 0. At ... | acdcc76a91e7882a0a836e2783847e23deb1f84b | 659,623 |
def _is_none(arg):
"""Check if argument is None."""
return arg is None | bc8a02871d2d52db1f031d4ea354edfd1728c5b7 | 659,625 |
def find_lcm(NumpyArray):
"""Retorna o Minimo Multiplo Comum de um Numpy Array"""
def gcd(x, y):
while y > 0:
x, y = y, x % y
return x
def lcm(x, y):
return x * y / gcd(x, y)
Nlcm = NumpyArray[0]
for i in range(1, len(NumpyArray)):
Nlcm = lcm(Nlcm, Nu... | 7c7aacf7dfcd54868a1dd1f3c0ed8e9f059df690 | 659,626 |
import re
def _match_trainid(value):
"""Return the trainID in value, None if no trainID."""
mat = re.search(r"TR(\d{4})", value)
if mat is not None and len(mat.groups()) > 0:
return mat.groups()[0]
return None | be5676b31ead30e6220bbde0058ef63110f0a53c | 659,627 |
from typing import List
def get_least_numbers(arr: List[int], k: int) -> List[int]:
"""
Offer 40. 最小的 k 个数
:param arr:
:param k:
:return:
"""
if k >= len(arr):
return arr
def quick_sort(left: int, right: int):
"""返回前 k 小的数"""
i, j = left, right
while i ... | 0bac1aba1cef79ceff8c42eb3425565e52e2040e | 659,628 |
def pair_energy(ccdtemp):
"""Electron-hole pair creation energy in silicon."""
T = 273.2 + ccdtemp # Convert to Kelvin.
slope = -0.000131 # From L&S given in %/K
Tref = 270 # L&S figure 4.
Eref = 3.654
Eref_sigma = 0.040 # See LSSTTD-141@JIRA
Epair = (1 + slope*(T - Tref))*Er... | 164fe94c5a5e167ab8c0f8317b3d25115ebeeae3 | 659,629 |
import os
def _get_inventory_path(parsed_args):
"""Return the path to the JavaRole inventory."""
if parsed_args.inventory:
return parsed_args.inventory
else:
return os.path.join(parsed_args.config_path, "inventory") | b842aa748d265bf951a35a293587f09e28689b39 | 659,630 |
def argument_parser(input_args):
"""
Returns a list of tokens for a given argument
:param input_args: input string
:return: argument list
"""
arguments = input_args.split(' ')
if len(arguments) > 1:
return arguments[1:]
else:
return arguments | 8c3256ac7760b67ef00928beb54026788d3159bd | 659,631 |
def empty_string(s: str) -> str:
"""Return an empty string if s is None"""
if str(s).replace(" ", "") == "":
return ""
else:
return str(s) if s else "" | 86a9f2a8fe287f50c24d486459b12f14b8f5b2fc | 659,632 |
def smtp_config_writer_kwargs(kwargs, config, key):
"""
Set server/port/username/password config.
:param kwargs: Values. Refer to `:func:smtp_config_writer`.
:type kwargs: dict
:param config: Configuration dictionary.
:type config: dict
:param key: Key for kwargs and config dict.
:typ... | bc7374063c5c50f70591b1556e21432ce6615e69 | 659,634 |
from typing import List
from typing import Dict
from typing import Any
def _add_conditions(hyperparameters: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Returns a list of conditions in a format that is compatible with the json
reader of the ConfigSpace API.
The conditions are used to activate and de... | 6ea21a08c9bfcc0643759a0bf6ada9ba2920b66d | 659,635 |
def capitalize_first(x):
"""
This function upper-cases only the first letter, unlike
.capitalize() that leaves the other letters uppercase. It
leaves other letters as they were.
"""
return x[0].capitalize() + x[1:] if len(x) > 0 else x | 17e827c6298aa4e9576a75c2591693b2b14e4c12 | 659,636 |
import json
import gzip
def post_body_matcher(params):
"""
Used for verifying post-bodies to mocked endpoints. See the `match`-argument in `rsps.add()`.
"""
def match(request_body):
if request_body is None:
return params is None
else:
decompressed_body = json.l... | 07d548a86a4e5a8b1947f83d1b8a0a464904bb34 | 659,638 |
def getFilePath(id):
"""Retrieves file path and name, given file entry ID
Args:
id (str): File entry ID to get details of
Returns:
dict: Object contains file ID, path and name
"""
return {'id': id, 'path': 'test/test.txt', 'name': 'test.txt'} | 125a678eed3e1e2024c678e4712665ccc04d4903 | 659,639 |
import re
def extract_text(text, left, right):
"""Extract text from HTML"""
result = re.findall("{0}(.*?){1}".format(left, right), text)
if len(result) != 1:
raise Exception("Failed to extract string. "
"Expected 1, found {0}".format(len(result)))
return result[0] | ffba0933c210c35fcd464ccbf75a27dfd74a5e1f | 659,642 |
def lower_case_the_keys(d):
"""Create a dict with keys being lower cased but with a check against collisions
If d is a list of tuple, would recurse into its elements
"""
if not isinstance(d, dict):
assert isinstance(d, (list, tuple))
return d.__class__(
lower_case_the_ke... | 8ebbb2f863163be09c5c687a29962f86a045989a | 659,643 |
def frequent_labels(series, rare_threshold):
"""
series: Pandas Series
Pandas Series where the frequent labels inference will be made
rare_threshold: float
Labels with frequency greater than this value will be considered frequent
returns: Pandas Series
Pandas Series with freque... | 9365e0e7a3cb6bf7ee1cea7b7ca1eba9ba3ab57f | 659,644 |
def width(canv):
"""
gets the height of the canvas
:param canv:
:return: integer height of the canvas
"""
return (canv and len(canv[0])) or 0 | e9c5c229d57b73839e8b985a15aad96342c0fd29 | 659,645 |
def kl_div(mean, logvar):
"""Computes KL Divergence between a given normal distribution
and a standard normal distribution
Parameters
----------
mean : torch.tensor
mean of the normal distribution of shape (batch_size x latent_dim)
logvar : torch.tensor
diagonal log variance of... | 39fc74df4190a023e5b03132cd3102dc562a0401 | 659,646 |
def get_exp_name():
"""
returns name of experiment
for tracking in analysis
"""
return "catboost_2013_2017_1_1_part_d_hcpcs" | 9a59990af41e9cc5033d12a3b44f0df69fc1b158 | 659,647 |
def string_ancilla_mask(location, length):
"""Returns a bit string with a 1 in a certain bit and the 0 elsewhere.
Parameters
----------
location : int
location of the bit which should be set to '1' in the mask
length : int
length of string in the mask
Returns
------... | 0c4365f4bcdfd453062dcc723b17df2e43781a15 | 659,648 |
import _struct
def parse_notify_req(pkt):
"""Parse a notification request.
pkt -- raw packet data (str).
Returns: (service, userid, messid, data)
"""
NOTIFY_REQ_LEN = 12 # Minimum packet size for notifications
if len(pkt) < NOTIFY_REQ_LEN:
raise ValueError("Invalid packe... | 97806e0d8514b19177e91fcf2ba00e60c0cc0539 | 659,649 |
def overlap(x1, x2, y1, y2):
"""
Return True iff [x1:x2] overlaps with [y1:y2]
"""
if not all([isinstance(i, int) for i in [x1, x2, y1, y2]]):
return False
return ((y1 <= x1 <= y2) or
(y1 <= x2 <= y2) or
(x1 <= y1 <= x2) or
(x1 <= y2 <= x2)) | 6bafaf7cbd012fe3ed9e32c6bf510a6298c8d5dc | 659,650 |
def float2transparency(value: float) -> int:
"""
Returns DXF transparency value as integer in the range from ``0`` to ``255``, where ``0`` is 100% transparent
and ``255`` is opaque.
Args:
value: transparency value as float in the range from ``0`` to ``1``, where ``0`` is opaque
a... | 803c6f6f65b43653248a0297532d7f6a5b49f5bf | 659,651 |
def is_in_groups(user, group_names):
"""
Returns True if the user is a member of any groups given their names in group_names
"""
return any(user.groups.filter(name=group_name).exists() for group_name in group_names) | 9d591331819003aa2542cb8b32dc98a13dbcba00 | 659,652 |
def illinois_algorithm(f, a, b, y, margin=1e-5):
"""
Bracketed approach of Root-finding with illinois method.
Parameters
----------
f : callable
Continuous function.
a : float
Lower bound to be searched.
b : float
Upper bound to be searched.
y : float
... | 742ce8d508d5e6895938c1765463be7f84070b9a | 659,653 |
import subprocess
import sys
def scrape_display_info(device, frame_rate):
"""Grab frame rate info via dumpsys display. Return fps as a string."""
target = "" if (device is None or len(device) == 0) else "-s " + device
cmd = "adb {} shell dumpsys display | grep PhysicalDisplayInfo | cut -d ',' -f 2".forma... | 6a96d8c6a2a3dd42ca2133edf4fd978b13e83282 | 659,654 |
import json
def _poll_job(meth, job_id):
"""Has the job manager fetch a registered job.
:param job_id: A job id
:type job_id: kbtypes.Unicode
:ui_name job_id: A job id
:rtype: kbtypes.Unicode
:return: job info
:output_widget: kbaseJobWatcher
"""
meth.stages = 2
meth.advance("F... | 223203ed13dabdecb508febd5b1338f6dc66c6c9 | 659,656 |
def get_choice_menu() -> str:
"""
Display the menu and ask for the choice from the user.
Returns
-------
choice: str
The valid choice enter by the user.
"""
valid_choice_list = ['0', '1', '2', '3']
choice = ''
menu = (
'1. Start new game\n'
... | be8d921d6ec2e555325aae0c4aa48e2e1b95a2ac | 659,658 |
import math
def compute_entropy(_list):
"""
计算熵 https://zh.wikipedia.org/zh-hans/%E7%86%B5_(%E4%BF%A1%E6%81%AF%E8%AE%BA)
https://baike.baidu.com/item/熵/19190273
Calculating entropy
:param _list:
:return:
"""
length = float(len(_list))
frequence = {}
if length == 0:
... | df1f8602d8297c22ae01baa9edf32afb89eff52f | 659,659 |
import sys
def get_requirements():
"""Reads the actual requirements from requirements.txt"""
with open('requirements.txt') as req:
requirements = req.read()
if sys.platform == 'win32':
requirements = requirements.replace('psycopg2', 'psycopg2-binary')
return requirements.s... | 952faaab3abf51130203357f008b10f778aca83b | 659,660 |
def base_n(
num: int, b: int, numerals: str = "0123456789abcdefghijklmnopqrstuvwxyz"
) -> str:
"""
Convert any integer to a Base-N string representation.
Shamelessly stolen from http://stackoverflow.com/a/2267428/1399279
"""
neg = num < 0
num = abs(num)
val = ((num == 0) and numerals[0])... | 8d02a600b328bf8f656187531802a6c869509042 | 659,661 |
def y_ss(n, s, t):
"""Spin observable: y-direction
"""
if s == t:
return 0
else:
return 1.j * (-1)**t | 4e4313cc32a2f410e3f7412066109d6e6e61c755 | 659,662 |
def merge_lines(lines, start, join=" "):
"""Gets a single continuous string from a sequence of lines.
:param list lines: The lines to merge.
:param int start: The start point in each record.
:param str join: The string to join on.
:rtype: ``str``"""
string = join.join([line[start:].strip() for... | 48fc2eb74227d37ec8be5ba30d9548c7d6e7d4d6 | 659,663 |
def generate_module_dictionary(category_to_process, data):
"""
This Function generates module dictionary from the JSON.
We select specific modules we need to process, and use them.
Module indices are mention in the list 'category_to_process'
'data' is the json, which we use to extra... | ab6a351229245614ba5ee255f75f00a595c1b76d | 659,664 |
def MEAN(src_column):
"""
Builtin average aggregator for groupby. Synonym for tc.aggregate.AVG. If
src_column is of array type, and if array's do not match in length a NoneType is
returned in the destination column.
Example: Get the average rating of each user.
>>> sf.groupby("user",
... {'r... | 8230c17d0dec7f277638274041e50290883c9eb9 | 659,665 |
import re
def docstr_defaults(func, i: int):
"""
From ``func`` docstr reads and strips ``i``-th multiline
block of the form (strips it to ``'<...>'`` contents only):
>>> # <...>
>>> # <...>
>>> #
"""
return re.sub(r' +>>> # ', '', re.findall(
r'(?<=>>> # ).+?(?=\r?\n +>>> #\r?... | c05b0a7b913896cb5c0d40d88fa9595f36ec52a4 | 659,666 |
def locate(variant, tx, segments_annotation):
"""Locate a variant in the general gene model."""
if tx.strand == '-':
segments_annotation = list(reversed(segments_annotation))
try:
segment, annotation = next(
(segment, annotation) for segment, annotation in segments_annotation
... | 1ccd4cebd1ec5b869591dd76a0b8179e2d9c1963 | 659,667 |
import pickle
def load_model_pkl(path):
""" loads a model stored as pickle file (e.g. from sklearn) """
with open(path, 'rb') as f:
return pickle.load(f) | f4618e0041d15b35b6653244ff19c732d2ce21aa | 659,668 |
import re
def finish_family_dependency(dep: str, bits: int) -> str:
"""Finish dep if it's a family dependency symbol prefix.
A family dependency symbol prefix is a PSA_WANT_ symbol that needs to be
qualified by the key size. If dep is such a symbol, finish it by adjusting
the prefix and appending the... | 96059b1049166ebc7908d10e1b56aea691ba386a | 659,669 |
def create_lkas_ui(packer, main_on, enabled, steer_alert, defog, ahbc, ahbcramping, config, noipma, stats, persipma, dasdsply, x30):
"""Creates a CAN message for the Ford Steer Ui."""
if enabled:
lines = 0x6
else:
lines = 0xc
values = {
"PersIndexIpma_D_Actl": persipma,
"DasStats_D_Dsply": dasd... | 9db15a260aee5eb785d76c0dccf6e70a98c870f1 | 659,670 |
def from_study_get_instrument(C, Agency, ID):
"""
From a study, get instrument and Mode of Data Collection
"""
d = C.item_to_dict(Agency, ID)
c = C.item_to_dict(d['Data Collection']['Agency'], d['Data Collection']['ID'])
name = c['Name']
mode_list = [c['CollectionEvent']['ModeOfCollection']... | 164f564979b731d273e60034d49c96d26261cbd4 | 659,671 |
import requests
import zipfile
import io
def downloadZipFile(url, directory):
"""
Multimedia Content are stored in cloud in ecar or zip format.
This function downloads a zip file pointed by url location.
The user is expected to have access to the file pointed by url.
The extracted file is availab... | 0422ddf5da24017772c56fe0058ab17b4edf9bef | 659,672 |
def testStatistic(y,z):
"""Checks if two means are different, tempered
by the sample size of 'y' and 'z'"""
tmp1 = tmp2 = 0
for y1 in y.all: tmp1 += (y1 - y.mu)**2
for z1 in z.all: tmp2 += (z1 - z.mu)**2
s1 = (float(tmp1)/(y.n - 1))**0.5
s2 = (float(tmp2)/(z.n - 1))**0.5
delta = z.mu ... | 9935f46b79cf002b4aacccc0aa853baa4e6a51a9 | 659,673 |
def get_discussion_id_map_entry(xblock):
"""
Returns a tuple of (discussion_id, metadata) suitable for inclusion in the results of get_discussion_id_map().
"""
return (
xblock.discussion_id,
{
"location": xblock.location,
"title": xblock.discussion_category.split(... | b5cc1e0bf90719169c56f8c9da6d2021d2e7db63 | 659,674 |
def load_deeplogic_task(fname):
"""Load logic programs from given file name."""
def process_rule(rule):
"""Apply formatting to rule."""
return rule.replace(':-', '.').replace(';', '.').split('.')[:-1]
ss = list()
with open(fname) as f:
ctx, isnew_ctx = list(), False
for l in f:
l = l.strip... | 00f85cf28a3faefb70c2c056711c31c4c8836ce2 | 659,675 |
def parse_directions_response(directions_response):
"""Extract basic information relevant to route from the response.
Args:
directions_response: list of directions in the deserialized
Maps API response format
Returns:
if a valid route is found a tuple containing:
a list of the (lat,lon) points ... | ca32f3582cf65c2eb4cfa981664c5bb117c6c85d | 659,676 |
def _not_null(value, field):
"""Check whether 'value' should be coerced to 'field' type."""
return value is not None or field.mode != 'NULLABLE' | cfe5f11528bd30e1fba580349decaa5b7b9b67e3 | 659,677 |
def to_dict(multi_dict):
"""Converts a multi dict into a dict where only list entries are not flat"""
return {
k: v if len(v) > 1 else v[0]
for (k, v) in multi_dict.to_dict(flat=False).items()
} | cb7ed5ae6cbad15a39250091909e1761c4588060 | 659,678 |
import os
import subprocess
import json
def get_meta_data(filename):
""" Get metadata from lasfile as dictionary """
cmd = ['pdal', 'info', '--metadata', '--input', os.path.abspath(filename)]
out = subprocess.check_output(cmd)
meta = json.loads(out)['metadata']
return meta | 7d308de7c598645f468cfd48aa95f1ba3f107f55 | 659,679 |
from typing import List
async def deliver_card(list_of_lists: List[List[str]]) -> str:
"""Let's make the Cringo! card pretty!"""
final_string = []
for sublist in list_of_lists:
final_string.append('\u200A'.join(sublist))
# add blank emoji to first line to accommodate compact mode w/o resizin... | 494c79e3948ada8fa038c0c4c86095278a80476f | 659,680 |
def _elevation_color(elevation, sea_level=1.0):
"""
Calculate color based on elevation
:param elevation:
:return:
"""
color_step = 1.5
if sea_level is None:
sea_level = -1
if elevation < sea_level/2:
elevation /= sea_level
return 0.0, 0.0, 0.75 + 0.5 * elevation
... | c929d6502f2ed4d843173745ab6082dcddabe1a7 | 659,681 |
def factors_of(number):
"""Get the factors of a given number.
:param number: The number for which the factors will be obtained.
:type number: int
:rtype: list[int]
:raise: TypeError
"""
if type(number) is not int:
raise TypeError("Factors may only be acquired for an integer.")
... | f1e6b2d772544f1c837ba7e96291e36cfd6506e4 | 659,682 |
def to_percentage(number):
"""
Formats a number as a percentage, including the % symbol at the end of the string
"""
return "{:.2%}".format(number) | 0f2b5af0e301503cb0cffc1c5c31f46b1d7803e8 | 659,683 |
from typing import Tuple
def diagonal_distance(pa : Tuple[int, int], pb : Tuple[int, int]) -> int:
"""
Gets manhattan distance with diagonals between points pa and pb.
I don't know what this is called, but the fastest route is to take the
diagonal and then do any excess.
"""
(ax, ay) = pa
... | 5f4fb653ab8d8bb77172b1637af3edb7c2f0b704 | 659,684 |
def create_dt_params_with_mData(columns, search="", start=0, length=10, order=None):
"""Create DataTables input parameters when the data source from the rows
data object/ array is set.
Read more about setting column data source here https://datatables.net/reference/option/columns.data"""
params = {
... | 3d0962ee99566c25627c59c21d0b79fc8bf32008 | 659,685 |
import re
def is_invocation_allowed(command_requested, exact_allowed=[], regex_allowed=[]):
"""
Check if command_requested is an element of exact_allowed or if it
matches a pattern in regex_allowed. If so, then return True.
"""
allowed = False
if command_requested in exact_allowed:
... | e7b3ac061ce714bfe7afe9e709c19786735592ff | 659,686 |
import click
def conditional_argument(condition, *param_decls, **attrs):
"""
Attaches an argument to the command only when condition is True
"""
def decorator(f):
if condition:
f = click.argument(*param_decls, **attrs)(f)
return f
return decorator | 39599ad3aa6ab29e56c3e419304818385f8c26f8 | 659,687 |
def hamming_distance(list1, list2):
"""[Total no. of mismatches bt strings list1 and list2, pos i in kmers list1 and list2 is a mismatch
if the symbols at pos i of the 2 strings are not the same. NOTE: MUST BE EQUAL LENGTH STRINGS.
IF NOT EQUAL LENGTH, USE LEVENSHTEIN DISTANCE]
Args:
li... | 99239af31098dd95dcfeecd4e3db3b3840d3e53c | 659,689 |
def windows_matcher(repository_ctx):
"""Matches Windows."""
if repository_ctx.os.name.lower().find("windows") != -1:
return True
return False | 5d220b29db6495b53f3924edf45c37fac3008069 | 659,690 |
from typing import Tuple
from typing import List
def pad_line_to_ontonotes(line: Tuple[str, ...], domain: str) -> List[str]:
"""
Pad line to conform to OntoNotes representation.
"""
word_ind, word = line[:2]
pos = "XX"
oie_tags = line[2:]
line_num = "0"
parse = "-"
lemma = "-"
... | db9831b4e466e4fe48b2023dfda65e24f1b498e8 | 659,691 |
def UnparsePath(PathParsePath):
"""
Creates string from L{svgpathparse.parsePath<svgpathparse.parsePath>} function output.
This step is performed in order to generate C{d} attribute value compatibile with existing syntax.
@type PathParsePath: list
@param PathParsePath: List of path segments parsed... | 6feb7bbf5d395361617399c6e9bb8afbb577d83b | 659,692 |
def buy_signal(df):
"""Function calculates signal to open long position
Args:
df (pandas.DataFrame): pandas.DataFrame
Returns:
string: return "Buy" if condition is met else False
"""
tsi = df["TSI"]
tsi_ma = df["TSI_MA"]
signal = ""
if ((tsi[-2] < 0 and tsi_ma[-1] < 0)... | a9f950b8059fdbdc89b92e87499b5482ee03f4ed | 659,693 |
def strahler_stream_order(start_arc_id, start_up_node,
nodes_per_arc, arcs_per_node, stream_orders):
"""Calculate the Strahler stream order
This function recursively computes the Strahler stream order using
the algorithm described by Gleyzer et al. (2004). The sequence of
stre... | 32b7c5c5c0e3aee169d97ade6403248494ca591e | 659,694 |
import random
def _add(a, b):
"""
测试函数缓存 的装饰器
:param a:
:param b:
:return:
"""
return a + b + random.randrange(0, 1000) | cf1891fba07fdf852c3afed1a5efd85b193dd600 | 659,695 |
import os
import torch
def load_checkpoint(checkpoint_path, model, optimizer=None, warm_start=False):
"""Loads model from given checkpoint
Args:
model (nn.Module): vocoder model
optimizer (Optimizer): optimizer
"""
assert os.path.isfile(checkpoint_path)
print("Loading checkpoint f... | 33ff77fb408d73823025731171076540ec1a572c | 659,696 |
import math
def _distance(loc1, loc2):
"""
Returns the Euclidean distance between two co-ordinates in
km
"""
R_EARTH = 6378.1
lat1_rad = math.radians(loc1[0])
lat2_rad = math.radians(loc2[0])
lon1_rad = math.radians(loc1[1])
lon2_rad = math.radians(loc2[1])
delta_lat = lat1_ra... | 732208e1ab1e8a8a1737275f678c4d47778eeda0 | 659,697 |
import os
import io
def read(*path):
"""
Cross-platform Python 2/3 file reading.
"""
filename = os.path.join(os.path.dirname(__file__), *path)
return io.open(filename, encoding='utf8').read() | ebe3f6777985f45d471a51e52ee6c842f7dfdf60 | 659,698 |
def _merge(lst1: list, lst2: list) -> list:
"""Return a sorted list with the elements in <lst1> and <lst2>.
Precondition: <lst1> and <lst2> are sorted.
"""
# Use <index1> and <index2> to keep track of where you are
# in each list, and <merged> to store the sorted list to return.
index1 = 0
... | 914f3f7c81d8c851c57104ec4f45fccdce5b2448 | 659,699 |
def load_csv(csv_filename):
"""
Loads the csv file and, based on the ING coding, combines a number of
the included fields into a description.
Returns a list of list of strings with the date, amount, description
and placeholders for payee and category, to be filled in by the
subsequent call of t... | 6cd538605b5d0b085f9b6d4f9a3c310f5ef3218e | 659,700 |
import threading
def get_lock(reentrant=False):
"""Return a unmanaged thread Lock or Rlock"""
if reentrant:
return threading.RLock()
else:
return threading.Lock() | 1fa6d8de40601967945b9f51832f8e53973b5ed5 | 659,701 |
def has_c19_tag (tags):
""" Check if the COVID-19 tag is present """
for tag in tags:
if tag.vocabulary == "99" and tag.code.upper() == "COVID-19":
return True
return False | 6ffddcb3557c923fd9310d5cd550f3d006bb438e | 659,702 |
def item_is_added_to_module(module, item, item_id, url_type):
"""
Tests whether an item has already been added to a module
item is a page or a file.
"""
for module_item in module.get_module_items():
# module_item.type is capitalised
module_item_type = module_item.type.lower()
... | 3d9d7c3eb64316db7a137a46cafbd3136b188dd1 | 659,703 |
def counter_pandas(dataframe):
"""
Counts instances and sorts them by frequency
Parameters
----------
dataframe : Pandas dataframe
A Pandas dataframe with the product information
Returns
-------
comb_sort
Returns a dictionary of func... | 1997e3f34a1fb5185578285e263f894918fe52fd | 659,706 |
def get_weights_arithmetic(n, w_1, order='a'):
"""
:param n:
:param w_1:
:param order: 'a' ascending or 'd' descending.
:return:
"""
weights = []
epsilon = 2 / (n - 1) * (1 / n - w_1)
for i in range(1, n + 1):
weights.append(w_1 + (i - 1) * epsilon)
if 'd' in order:
... | 5528339888c134218c7155b3ea7b3731ae1c2444 | 659,707 |
import json
def load_namelist(namelist_path:str):
"""Given path to `namelist.in` file, load and return as a nested dictionary."""
with open(namelist_path, 'r') as f:
namelist = json.load(f)
return namelist | 00feb59d051891ed78dc39465738718174894d31 | 659,709 |
def exclude_targets(*args):
"""Exclude a test from running on a particular target.
Use this decorator when you want your test to be run over a
variety of targets and devices (including cpu and gpu devices),
but want to exclude some particular target or targets. For
example, a test may wish to be r... | 679ec59718e0ff9228c0373bd530860823931fa9 | 659,710 |
import click
def demander_mouvement(mvmts_possibles: str):
""" Fonction qui demande au joueur le mouvement qu'il souhaite effectuer
Args:
mvmts_possibles (str): Mouvements que le joueur peut faire
Retourne:
str: Mouvement choisi par le joueur
H : Aller vers le Haut
B : Aller vers le Bas
... | 40f06c023e6792bf1b752c2181fcd87a3a0b722f | 659,711 |
import torch
def gpus_for_rank(world_size):
"""Multigpu tests are designed to simulate the multi nodes with multi
GPUs on each node. Nccl backend requires equal #GPUs in each process.
On a single node, all visible GPUs are evenly
divided to subsets, each process only uses a subset.
"""
visible... | 1112ae55e8ca228fd4981743666f89c32718579a | 659,712 |
def shape_attr_name(name, length=6, keep_layer=False):
"""
Function for to format an array name to a maximum of 10 characters to
conform with ESRI shapefile maximum attribute name length
Parameters
----------
name : string
data array name
length : int
maximum length of strin... | a681b460cac8960dd103bfd9c0dc0a8a69721ac0 | 659,713 |
def attention_padding_mask(q, k, padding_index=0):
"""Generate mask tensor for padding value
Args:
q (Tensor): (B, T_q)
k (Tensor): (B, T_k)
padding_index (int): padding index. Default: 0
Returns:
(torch.BoolTensor): Mask with shape (B, T_q, T_k). True element stands for re... | 16fb98c267b7b42f7b02ffaf8c423438b1a86a3b | 659,714 |
def lowercase_dict(original):
"""Copies the given dictionary ensuring all keys are lowercase strings. """
copy = {}
for key in original:
copy[key.lower()] = original[key]
return copy | fd28bd266b1a46aaf522432db38f9b0f1f148746 | 659,715 |
from typing import Sequence
import re
def convert_sequence_to_text(
schema_name: str,
schema_desc: str,
sequence: Sequence[str],
) -> str:
"""Converts sequence to text to use as GPT-2 input.
Args:
schema_name: Name of schema to run on.
schema_desc: Description / definition of the ... | 83af1ab73cb508171c2487503f1158fc83dfd1c3 | 659,716 |
import argparse
def parse_args():
"""Parses the arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--config',
dest='config',
help='the base configuration file used for edit',
default=None,
type=str
)
parser.add_argument(
'--grid',... | d9de7b119bba8019eade7b3f2e4b0f76cda4e643 | 659,717 |
import os
def mkdirs(path):
"""
辅助函数:创建文件夹
"""
# 去除首末的空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\\")
'''
windows下文件名中不能含有:\ / : * ? " < > | 英文的这些字符 ,这里使用"'"、"-"进行替换。
:?| 用-替换
"<> 用'替换
'''
# 对于文件夹,有没有.好像都是同一个文件
# replace方法默认替换所有匹配项
path = path.re... | 3f528a49e4c2ed4fbb0b04c7c0e405f93f4d94d1 | 659,718 |
import re
def get_error_from_html(html_error, v1=False):
"""This function parses an error message from Khoros displayed in HTML format.
.. versionchanged:: 2.0.0
Added the ``v1`` Boolean argument
:param html_error: The raw HTML returned via the :py:mod:`requests` module
:type html_error: str
... | d6587b9253c3902a02e5b9a3adcf50e1c75182f6 | 659,719 |
def _break_crt_chain(buffer):
"""Breaks the certificate chain string into a list.
Splits the cert chain with "-----END CERTIFICATE-----".
There are two cases to consider:
1) Certificates ending on "-----END CERTIFICATE-----"
2) Certificates ending on "-----END CERTIFICATE-----\n"
In case (1),... | 04f25569cf7cdd6049904a569ac6233a8b400b80 | 659,722 |
def mkfile(name, meta={}):
"""Return file node."""
return {
'name': name,
'meta': meta,
'type': 'file'
} | 5dc7ce835bef23abec93d989bff1445df5988f10 | 659,723 |
def get_L_dashdash_ba2_d_t(L_dash_ba2_d_t):
"""1時間当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/h) (4g)
Args:
L_dash_ba2_d_t(ndarray): 1時間当たりの浴槽追焚時における節湯補正給湯負荷 (MJ/h)
Returns:
1時間当たりの浴槽追焚時における太陽熱補正給湯負荷 (MJ/h)
"""
return L_dash_ba2_d_t | ba7e0560cc575b575f262a06e0df98d09c6b0b5c | 659,724 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.