content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_percentage(part, whole):
""" Input a part, then the whole. Returns percent as a float. """
if whole == 0:
return 0
else:
return 100 * round(float(part)/float(whole), 2) | 4ff4229b1e8d9a96ff48877d3a1bc70999cde9b0 | 589,929 |
def is_in_combat(character):
"""
Returns true if the given character is in combat.
Args:
character (obj): Character to determine if is in combat or not
Returns:
(bool): True if in combat or False if not in combat
"""
return bool(character.db.combat_turnhandler) | 0aaa73d15df3019df8d9bf0dfcc1329e386d27b5 | 589,933 |
def IOU(box1, box2):
"""
:param box1:[x1,y1,x2,y2] 左上角的坐标与右下角的坐标
:param box2:[x1,y1,x2,y2]
:return: iou_ratio--交并比
"""
width1 = abs(box1[2] - box1[0])
height1 = abs(box1[1] - box1[3]) # 这里y1-y2是因为一般情况y1>y2,为了方便采用绝对值
width2 = abs(box2[2] - box2[0])
height2 = abs(box2[1] - box2[3])
... | c87c76415d7953590d79861a27afb94cd3327011 | 589,935 |
def textNode(parent, childAsString):
"""return the text value from a single child element with the given name"""
return parent.getChild(childAsString)[0].getText() | e44d3ea25addf22e25ccb69a468f8bef4c153a43 | 589,936 |
def binary_search(lst, seek):
"""
DESCRIPTION: returns the index of element seek in the list lst
if seek is present in lst.
Return None if seek is not an element of the list lst
lst is the list in which to search
seek is the element to find
NB: lst must be a sorted li... | 3db0a8330c00dbb5d133e1e39ed8df8e67eec4b5 | 589,938 |
import re
def text_is_all_uppercase(text: str) -> bool:
"""Return True if every character is uppercase.
Excludes punctuation, spaces, and digits.
"""
return all([char.isupper() for char in re.sub(r"[^A-Za-z]", "", text)]) | 21f4b01f65820df1628ba993b6c9bd62f953e4c2 | 589,940 |
def make_abstract_model(db):
"""Taken from
https://datastax.github.io/python-driver/cqlengine/models.html#model-inheritance
but where we want the base classes to be in separate tables
"""
class Pet(db.Model):
__abstract__ = True
# __table_name__ = 'pet'
owner_id = db.columns... | 732620bdc8f30359d95d7f4f039978e9d95e5006 | 589,943 |
def default_field_resolver(source, info, **args):
"""Default field resolver.
If a resolve function is not given, then a default resolve behavior is used
which takes the property of the source object of the same name as the field
and returns it as the result, or if it's a function, returns the result
... | 9737cd17d7bf2e5ea80ed6872433c8bc0295f5bc | 589,946 |
from typing import List
from pathlib import Path
def all_filepaths_exist(filepaths: List['Path']):
"""
Returns True if all filepaths exist, otherwise returns False.
"""
return all([f.is_file() for f in filepaths]) | e9ddc589d518838c49c8ed3e1af353c8752ff32f | 589,953 |
def load_urdf(pybullet_client, file_path, *args, **kwargs):
"""Loads the given URDF filepath."""
# Handles most general file open case.
try:
return pybullet_client.loadURDF(file_path, *args, **kwargs)
except pybullet_client.error:
pass | f686a3c6e98960feda3abf888fd302997fbda825 | 589,954 |
def setattr_(obj, name, value):
"""Similar to setattr except it returns back the modified object.
"""
setattr(obj, name, value)
return obj | e047bb3d23b24ecb9be898177aaa5427fce92538 | 589,956 |
def shift_hue(image, hue):
"""
Shifts the hue of an image in HSV format.
:param image: PIL Image to perform operation on
:param hue: value between 0 and 2.0
"""
hue = (hue - 1.0) * 180
img = image.copy().convert("HSV")
pixels = img.load()
for i in range(img.width):
for j in r... | 29a010bea012b73743d711cfc01ed5d33e7ca240 | 589,957 |
import base64
import hashlib
def sha256_encode(message):
"""
Encode a message with SHA256 as base64
"""
return base64.b64encode(hashlib.sha256(message.encode()).digest()).decode() | 5890c610b1b8eef5048fb524a3041391fd88994d | 589,959 |
def is_instance(instance, expected_types):
"""Check instance type is in one of expected types.
:param instance: instance to check the type.
:param expected_types: types to check if instance type is in them.
:type expected_types: list of type
:returns: True if instance type is in expect_types.
... | c8b473dc0450be71b5614efa80c39f600f47efad | 589,961 |
def get_file_type(filename):
"""Get type of file
:param filename: The file name
:type filename: str
:return: The file's type
:rtype: str
"""
file_ext = filename.split(".")[-1]
img_ext = ["jpeg", "png", "gif", "tiff"]
txt_ext = ["css", "csv", "html", "xml"]
file_type = "text/pl... | 1a2542468b02b8f119812b258abfad6826bfa327 | 589,962 |
def get_mean(my_list):
""" Gets the mean or average of a list."""
assert len(my_list) > 0
return sum(my_list) / len(my_list) | 1162426101850c6b9f15989cffd80d7859a68078 | 589,964 |
def get_aF(r1_norm, r2_norm):
"""
Computes the semi-major axis of the fundamental ellipse. This value is
kept constant for all the problem as long as the boundary conditions are not
changed.
Parameters
----------
r1_norm: float
Norm of the initial vector position.
r2_norm: float... | 739a5c8d61ccde8db0eb7df10335940c338353c7 | 589,966 |
def get_sha512_from_manifest(manf):
"""
Retrieve asset name and hash from MANIFEST.MF file.
:param manf: Content of MANIFEST.MF file, in bytes.
:type manf: list(bytes)
"""
alist = []
for idx, line in enumerate(manf):
if line.endswith(b"signed"):
alist.append(manf[idx])
... | 0cd399bdfdaba639eec90caba2bb8b13cad4cd24 | 589,967 |
def is_sound_valid(wav_file: str) -> bool:
"""Asserts if sound file is valid.
Args:
wav_file (str): Path to wav file
Returns:
bool: If file is valid
"""
return wav_file.endswith(".wav") | 5d25049547245df830ef46d2d54ba4539f4295ae | 589,969 |
from typing import Any
from typing import Dict
from typing import Union
from typing import Tuple
from typing import OrderedDict
def create_on_off_val_mapping(on_val: Any = True, off_val: Any = False
) -> Dict[Union[str, bool], Any]:
"""
Returns a value mapping which maps inputs w... | 39e406c6084aeedd4600f3ea4a7e23553dcdde16 | 589,971 |
def compute_sigmac_physical_constant(lightspeed, gnewt, msun, pc_to_m):
""" Computes physical constant used to in Sigma_crit
Parameters
----------
lightspeed,: float
Lightspeed in km/s
gnewt: float
Gravitational constant in m^3/(km s^2)
msun: float
Solar mass in kg
p... | 15be2994b580f59453b1768e2415048cae4254d8 | 589,973 |
import torch
def calculate_image_distance(im1, im2):
"""
Calculates L2 and L_inf distance between two images
"""
# Calculate L2 distance
l2_dist = torch.dist(im1, im2, p=2).item()
# Calculate Linf distance
diff = torch.abs(im1 - im2)
diff = torch.max(diff, dim=2)[0] # 0-> item, 1-> p... | cac212263919aad4b7ba6d3d169676760669b4c4 | 589,974 |
def compute_n_trays_factor(N_T):
"""
Return the cost factor for number of trays, F_NT.
Parameters
----------
N_T: Number of trays
Notes
-----
The cost factor is given by [1]_. See source code for details.
"""
if N_T < 20:
F_NT = 2.25/1.0414**N_T
else:
... | fc9fa148d20047f9b9399ec9d6aa22f2c83da424 | 589,979 |
def get_play_fair_row_col(playfair_grid,letter):
"""[get which row, col a letter is within a playfair grid]
Args:
playfair_grid ([list]): [playfair grid]
letter ([str]): [letter you wan the row/column for]
Returns:
[row, col]: [the row and column for the letter passed in
us... | 7a3165e09786ad21526c82cec1f820e5481c8f06 | 589,982 |
def count_failed_students (student_scores):
"""Count the number of failing students out of the group provided.
:param student_scores: list of integer student scores.
:return: integer count of student scores at or below 40.
"""
count = 0
for element in student_scores:
if element <= 40:... | cf744bdbba15dc62306931e1f05fa4b3e7de8740 | 589,985 |
def to_internal_byte_order(rpc_byte_order):
"""
Returns a given RPC byte order hash (bytes) to the format expected by
Bitcoin primitives (blocks, transactions, etc.)
"""
return rpc_byte_order[::-1] | 72116e3f14572f58553fc830cd4d4b5138534cc1 | 589,988 |
def indent(string: str, n=4) -> str:
"""Indent a multi-line string by given number of spaces."""
return "\n".join(" " * n + x for x in str(string).split("\n")) | 3571906ad7a5f0bed26c3d4f4ba8252831a4918d | 589,989 |
def time_to_mss(sectime):
"""
Converts a number of seconds to m:ss format
:param sectime: int, a number of seconds
:return: str, sectime in m:ss
"""
n_min = int(sectime / 60)
n_sec = int(sectime % 60)
if n_sec == 0:
return '{0:d}:00'.format(n_min)
elif n_sec < 10:
r... | 86d86ef386c4f1736ec5fd3d1711155b4c613bc0 | 589,991 |
def split_positional_keyword_arguments(*args):
""" Create a list of positional arguments and a dictionary of keyword arguments
"""
# Distinguish between positional and keyword arguments
val_args = ()
for i, a in enumerate(args):
if a.has_keyword:
args, val_args = args[:i], args[... | 26aea2b027401959012fd635baaaa08a8c649c79 | 589,992 |
def store_in_file(service):
"""Sets ``store_in_file`` attribute to ``True``"""
service.store_in_file = True
return service | e30c4da8ed2b550b6ae4f79b6b15daf600cb28db | 589,994 |
from typing import OrderedDict
def series_to_yaml_safe(series, ordered=False):
"""
Convert a pandas Series to a dict that will survive YAML serialization
and re-conversion back to a Series.
Parameters
----------
series : pandas.Series
ordered: bool, optional, default False
If True... | 95636063e8c9212ca89208abce8853967c5bc56c | 589,995 |
def insert_mal_anime_detail(data):
"""
Returns tuple (query, values) necessary for inseting
data into the MAL_Anime_Details table.
"""
query = """
INSERT INTO MAL_Anime_Details
(
MAL_Id,
Title,
AltNameEnglish,
AltNameSynonyms,
Synopsis,
Me... | f6d515207723e8efa1c28435828975e6c7d18968 | 589,999 |
def _shape_setup(shape):
"""Array shape preprocessing, return (shape,) if shape is an integer."""
return (shape,) if isinstance(shape, int) else shape | d8bed9972c92209cd5c27599b3fe96ca7692c980 | 590,000 |
def is_dict(object):
"""Check if the given object is a dictionary"""
return isinstance(object, dict) | 2c112741e5aa9fa1d67501ce87f07992e707175f | 590,001 |
def is_in_interval(num1: float, num2: float, frac: float = 0.1) -> bool:
"""Check that the num1 is in the interval defined by num2 and its fraction."""
num2_frac = num2 * frac
_min = num2 - num2_frac
_max = num2 + num2_frac
return _min <= num1 <= _max | b11e00be2d2346ddeea08b5fe789db4f09ee568a | 590,002 |
import math
def logistic(x):
"""
Returns a value between 0 and 1 for x in the range [0, inf] and -1 to 1
for x in the range [-inf, inf].
"""
return 2.0 / (1 + math.exp(-x)) - 1.0 | 1657ac7d774d94cd8d99d3da09cf582cd8b39385 | 590,004 |
def get_variables (phrase):
"""Get all variables from a phrase."""
for char in '()&~|<>':
phrase = phrase.replace(char,' ')
phrase = phrase.split(' ')
phrase = list(set([x for x in phrase if x and x!='!allnotes!']))
return phrase | fdb37313f4a5e2ca5d91ff2f4c6310f97f0548dc | 590,010 |
import math
def polygon_area(side_length, amount_of_sides):
"""
area of a polygon of
:param side_length: side_length of a side of the polygon
:param amount_of_sides: Amount of sides the polygon has
:return: the area of the polygon
"""
angle = 180 / amount_of_sides
return 0.25 * amount... | 7831eba569cbfd291dbf6b0177aaa287e2d35794 | 590,012 |
from typing import Dict
import yaml
def read_yaml(path: str) -> Dict:
"""Reads YAML
Args:
path: path to yaml with file_name.y(a)ml
Returns:
parsed yaml as dict
"""
with open(path, 'r') as stream:
file = yaml.safe_load(stream)
return file | a168a005576c2ea8944c6732cba3f33a1ededf20 | 590,013 |
def cut_prefix(s, prefix):
"""Cuts prefix from given string if it's present."""
return s[len(prefix):] if s.startswith(prefix) else s | 23793c7e18f39ddd55b74701dcecbf0f86027608 | 590,015 |
def InsightsConfig(sql_messages,
insights_config_query_insights_enabled=None,
insights_config_query_string_length=None,
insights_config_record_application_tags=None,
insights_config_record_client_address=None):
"""Generates the insights confi... | 041ebaef9422569065b7d3198433729f3e3909f4 | 590,019 |
def find_edge_in_between(demand1, demand2):
"""
Return the index of an edge in between demand1 and demand2. Assumes i <= k and (i == k implies j < l)
:param demand1: indices of first demand
:param demand2: indices of second demand
:return: index of an edge in between
"""
i, j = demand1
k... | ceb82a33d202360e6833a760e8a3473be04bf8c2 | 590,021 |
import string
def base62_decode(str_value):
"""Decode a base62 string (all digits + a-z + A-Z) to a number."""
base62chars = string.digits + string.ascii_letters
return sum([base62chars.index(char) * (62 ** (len(str_value) - index - 1))
for index, char in enumerate(str_value)]) | c9d4c776ac4086ec587f98a4497714be3d61f972 | 590,022 |
def group_split(items, group_size):
"""Split a list into groups of a given size"""
it = iter(items)
return list(zip(*[it] * group_size)) | 0fdb7eeaf29513b9c331aa19015a47e964ad19fc | 590,023 |
def get_broker_leader_weights(brokers):
"""Get a list containing the weight from leaders on each broker"""
return [broker.leader_weight for broker in brokers] | 64df9685168e6e000bdf69ae577291041160967e | 590,028 |
def get_client_browser(request):
"""
Returns client browser
"""
return request.META.get('HTTP_USER_AGENT') | 9142f2a3331a8b6b8691aa932ff0d3631db00fcc | 590,030 |
def convert_branch(branch):
"""
Convert release branch to MediaSDK and Media-driver branches
:param branch: Branch name
:type branch: String
:return: MediaSDK branch, Media-driver branch
:rtype: tuple
"""
if branch == 'mss2018_r2':
return branch, 'master'
if 'sdk' in bran... | 570de20aa5e15bb797ceb0b09cae1b212fe44303 | 590,031 |
def mocked_on_commit(mocker):
"""
Patch on_commit to execute immediately instead of waiting for transaction to commit.
Since tests run inside transactions this will delay execution until after the test.
Since uses of on_commit are usually meant to delay executing tasks, and since
tasks are executed ... | eee4260dd25ff919a034e463c8a8aa98ede98de4 | 590,038 |
import requests
def get_model_id(access_token, model_name):
"""Gets 3D printing company model id using model name
Args:
access_token (str): Current access token for business account
model_name (str): Model name stored with 3D printing company
Returns:
model_id (str): Model ID matching the parameter ... | 9cf08420ec0bbea6dbd5e0be837b4b86e8db0040 | 590,040 |
def get_string_event_attribute_rep(event, event_attribute):
"""
Get a representation of the feature name associated to a string event attribute value
Parameters
------------
event
Single event of a trace
event_attribute
Event attribute to consider
Returns
------------
... | c97cf3b34bed1b350ba2bce7a05966d8ddbfbeef | 590,042 |
def reverse_string(string: str) -> str:
"""
Returns a new reversed string
:param string: String to reverse
:return: str
Example:
>>> reverse_string("test")
>>> "tset"
"""
return string[::-1] | c2e478e2c47726a36e68008c8fc66be621fe2c86 | 590,046 |
def prepare_data(items, rcn):
"""Append the project code ('RCN') to each "row" (dict) of data (list)"""
return [dict(project_rcn=rcn, **item) for item in items] | 5a4510e1b615c1549ab7231bab24f57dd053a62a | 590,050 |
from operator import sub
def vsub(V1,V2):
""" subtract the components of 2 vectors
<div class=jython>
VSUB (V1, V2) = [ u1-u2, v1-v2 ]
</div>
"""
return sub(V1,V2) | 0813c42b088f7d8c09a24d1a8aa9abed80c649f3 | 590,052 |
def num_infinitive_phrases(stanza_doc):
# Ref: https://www.grammar-monster.com/glossary/infinitive_phrase.html
# NOTE: This feature is available only for English for now
"""Returns the number of infinitive phrases
Args:
stanza_doc (Stanza): The Stanza document object
Returns
num_inf_phrases (int... | 5ffe439631e912cd0788ef0914fc7dbfb16f3fa2 | 590,054 |
import random
def random_list(n: int):
"""Returns a list of n random int -> list"""
randoms = [random.randint(0, n) for _ in range(n)]
return randoms | 5805c505fceedd49c4da27066e30ff83a2e035cb | 590,056 |
def profile_maker(profile, username, password):
"""
This method is similar to switch statement. It will render the dict with the given data and
returns the matched profile name
:param profile: Name of the profile to return.
:param username: Username to authenticate OpenStack.
:param password: Pa... | 6779a50e72e39ea71bebf010c6ee4dd17a30dc50 | 590,057 |
import torch
def nb_llik(x, mean, inv_disp):
"""Return the log likelihood of x distributed as NB
See Hilbe 2012, eq. 8.10
mean - mean (> 0)
inv_disp - inverse dispersion (> 0)
"""
return (x * torch.log(mean / inv_disp) -
x * torch.log(1 + mean / inv_disp) -
inv_disp * torch.log(1 + ... | c0e692028388774909c2b32b794307aa62e8afd2 | 590,059 |
def Current(context):
"""
Implementation of current().
Returns a node-set that has the current node as its only member.
"""
return [context.currentNode] | 02d1bcef808e021c60ee8eb01157b0b8456a022c | 590,060 |
import random
def weighted_choice(choices):
"""
Return a single element from a weighted sample.
`choices` is a dictionary with labels (buckets) as keys and weights (probabilities) as values.
"""
total = sum(choices.values())
r = random.uniform(0, total)
items = sorted(choices.items(), key... | 4ff1a91cfd977a5c46e5019b2687aa160e3625ad | 590,070 |
def recall_at_k(y_true, y_pred, k=None):
"""Recall at K.
Args:
y_true (list or np.array): True values.
y_pred (list or np.array): Predicted values.
k (int): Limit of predicted values.
Returns:
float: recall at k (max=1, min=0)
Examples:
>>> y_true =... | 11b592374d5a9da1b2726ed125ae8b646d62abba | 590,071 |
def digit_to_character(digit):
"""
Convert a digit to character.
"""
return chr(digit+48) | 813622d1c503b63ae20535ea8e0411476417696a | 590,073 |
def get_vars_for_dims(ds, dims, invert=False):
"""
Return a list of all variables in `ds` which have dimensions `dims`.
Parameters
----------
ds : xarray.Dataset
dims : list of str
The dimensions that each variable must contain.
invert : bool, optional
Whether to return the ... | b2e5bcc411bc83674d133f7ec8e41382acd9509e | 590,081 |
import sympy
def field_linear(theta):
"""Jones vector for linear polarized light at angle theta from horizontal plane."""
return sympy.Matrix([sympy.cos(theta), sympy.sin(theta)]) | 4ae21f61e0263f5e51ef6a390004bcdf4b9d763d | 590,084 |
import itertools
def imapchain(*a, **kwa):
""" Like map but also chains the results. """
imap_results = map(*a, **kwa)
return itertools.chain(*imap_results) | 92df83f043051f6bbbd6101f209b3a21ddf66837 | 590,089 |
def conv_output_length(input_length, filter_size, stride, pad=0):
"""Helper function to compute the output size of a convolution operation
From Lasagne
"""
if input_length is None:
return None
if pad == 'valid':
output_length = input_length - filter_size + 1
elif pad == 'full':
... | 84a276824a5f9c0e36363fa2e686ad1750f7639b | 590,092 |
from typing import Tuple
def parse_version_info(version_str: str) -> Tuple:
"""Parse version from a string.
Args:
version_str (str): A string represents a version info.
Returns:
tuple: A sequence of integer and string represents version.
"""
version_info = []
for x in version... | cce97e3b83700159ac700687be947f535dc9d542 | 590,093 |
def _instruction(asm_line):
"""Return the instruction found in input
`asm_line`, a line of AVR Assembly code.
Example:
' 1b6: ff cf rjmp .-2 ;'
Returns the string: "rjmp"
"""
# Lines are tab-separated.
# Instruction is always the 3rd word.
return asm_line.split('\t')[2].strip(... | 432b032dbdbffd0fd981eb5c94ddc7a2619b8350 | 590,095 |
def readFile(fn, binary=0):
"""Return the contents of the file named <fn>."""
f = open(fn, ['r', 'rb'][binary])
try:
return f.read()
finally:
f.close() | c7ac000a34cda51f00335f9bbdd3f91595a3da68 | 590,098 |
def apply_threshold(pred_prob_labels, threshold):
"""Sends every prediction in the list below the threshold
(exclusive) to zero and everything above it (inclusive) to one.
In the parlance of this file, turns predicted probablistic labels
into predicted labels. Returns a list."""
return list(map(lam... | 34d35fb4ed04e303c4eb555818805cbc72261c05 | 590,099 |
def intersect(seq1, seq2):
"""
Return all items in both seq1 and seq2
"""
return [item for item in seq1 if item in seq2] | 759d23303f4622a92e68a4c54e4757ee02c5b3c2 | 590,102 |
def art_qi1(airmask, artmask):
"""
Detect artifacts in the image using the method described in [Mortamet2009]_.
Caculates **q1**, as the proportion of voxels with intensity corrupted by artifacts
normalized by the number of voxels in the background. Lower values are better.
:param numpy.ndarray air... | 2b19e6c7dcf2dc767fc535a7954e2957b86fde75 | 590,104 |
def _GetFailedCountDetails(step):
"""Build a string with status count sums for a step's testSuiteOverviews."""
if not step.testExecutionStep:
return 'Unknown failure'
total = 0
error = 0
failed = 0
skipped = 0
for overview in step.testExecutionStep.testSuiteOverviews:
total += overview.totalCount ... | 6dce2187274b83336bcc52267fd4befe513a2554 | 590,108 |
def typeof(variate):
"""
Detect the type of a variable.
"""
var_type = None
if isinstance(variate, int):
var_type = 'int'
elif isinstance(variate, str):
var_type = 'str'
elif isinstance(variate, float):
var_type = 'float'
elif isinstance(variate, list):
va... | 69a78221281baf94fbcfd08f280b1d4060f8cbaf | 590,111 |
def calc_check_digit(number):
"""Calculate the check digit for personal codes. The number passed
should not have the check digit included."""
# note that this algorithm has not been confirmed by an independent source
weights = (2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9)
check = sum(w * int(n) for w, n in z... | eef5e2c58d56c1929fc2503537a63b0455cf8976 | 590,113 |
def get_guess() -> str:
"""Get a letter from the user.
Returns:
str: Return the validated letter.
"""
while True:
user_input = input("Please enter a letter: ")
if not isinstance(user_input, str):
print("Please enter a letter between a and z")
continue
... | 4217af428e50d7ac86de1aa6d15a41bd0eee40bb | 590,118 |
def traverse(data):
"""
Recursively traverse a nested dictionary (with potential nested values of dict, list, string;
'final' values are all strings). This function can deal with nested dicts, lists of lists,
lists of dicts, dicts of lists of lists, etc.
Returns a dict of flattened key/value pairs.... | ba5342202dc549e5562bbb2c64a1b403de71df36 | 590,119 |
def field(field_var):
""" Render a field based on template
https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#inclusion-tags
Possibly add parameter for custom classes
:param field_var: the field variable
:return: the template context
"""
return {'field': field_var} | 7b48d67f83098cf8d3e4ec004bfdccc25c2565e6 | 590,120 |
def parse_sequence(lines, constructor="".join):
"""Parses a GenBank sequence block. Doesn't care about ORIGIN line."""
result = []
exclude = b"0123456789 \t\n\r/"
strip_table = dict([(c, None) for c in exclude])
for i in lines:
if i.startswith("ORIGIN"):
continue
result... | 85699e393d45f569fc9819b5d42c2519506cf0d0 | 590,121 |
def validate_request(raw):
"""Checking for exists of 'action' and 'time' in request."""
return True if 'action' in raw and 'time' in raw else False | a8d612508e8f97b15186b2265e029c67711d106a | 590,124 |
from typing import Hashable
def is_hashable(o: object) -> bool:
"""
:param o: An object.
:return: `True` if ``o`` is hashable, else `False`.
"""
return isinstance(o, Hashable) | 50167e4c10955fb1f490f0e9106f81cbb6e8ccc7 | 590,128 |
from typing import Dict
import re
def parse_docstring(docstring: str) -> Dict[str, str]:
""" Parse a docstring into a dict mapping argument name to docstring """
argument_pattern = re.compile(r" *:param ([a-zA-Z0-9_]*)( *)(.*?):( *)(.*)")
return {match.group(1): match.group(5) for line in docstring.split(... | 26b2f8ac32cdcfa605069d8ae9c2c1cb85b9f754 | 590,131 |
def extract_metas(bs4):
"""Extracting meta tags from BeautifulSoup object
:param bs4: `BeautifulSoup`
:return: `list` List of meta tags
"""
meta_tags = []
metas = bs4.select('meta')
for meta in metas:
meta_content = {}
meta_attrs = [
'charset',
'... | 2ffb40bccd1c00762d59c85cfb6b0878a1f75a4f | 590,136 |
def write_header(outfile):
""" Write Header of ARFF file
:Parameters:
`outfile` : file
file descriptor to write
"""
outfile.write("""% Adult Data Set / Census Income Data Set
% http://archive.ics.uci.edu/ml/datasets/Adult
% http://archive.ics.uci.edu/ml/datasets/Census+Income
... | d2e38cf351e32c45caa7e8e9fae3aad2183ff9c6 | 590,137 |
def get_scale_from_size(input_size, output_size):
"""Get the scale factor given input size and output size.
Args:
input_size (tuple(int)): The size of the input image.
output_size (tuple(int)): The size of the output image.
Returns:
list[float]: The scale factor of each dimension.
... | d90bb420759258b37f4cff320cdae29a706a98ee | 590,139 |
def load_file(filename: str) -> list:
"""Load and parse the instruction list from a file
:param filename: Location of the input file
:return: Parsed instruction list
"""
with open(filename) as f:
raw_instructions = f.readlines()
instructions = [path.split(',') for path in raw_instructio... | 47115411e27c16ab9a891d0e461d4f2febf4e0c7 | 590,140 |
def dotClose(input,footer): #OLDNAME dot_close
"""
Close the graphiz config file
Return final output to be written
"""
input.extend(footer)
input.append("}")
output = ''.join(input)
return output | c46ab220d051fb238b5f632284a247e124152fc8 | 590,142 |
def powerset(a):
"""
Return the set of all subsets of a.
"""
if len(a) == 0:
return set([frozenset()])
accumulator = set()
a = set(a)
element = a.pop()
for subset in powerset(a):
accumulator.add(subset)
accumulator.add(frozenset(set([element]) | subset))
retur... | ac1642b27d1d1655518a499bc978849ca93a35de | 590,150 |
def overlaps(a, b):
"""
Return the amount of overlap, in bp
between a and b.
If >0, the number of bp of overlap
If 0, they are book-ended.
If <0, the distance in bp between them
"""
return min(a[1], b[1]) - max(a[0], b[0]) | e6e292920c57c24ddc526e488d4fe31f3ec39dce | 590,155 |
def handle_extensions(extensions):
"""
Organizes multiple extensions that are separated with commas or passed by
using --extension/-e multiple times.
For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
would result in an extension list: ['.js', '.txt', '.xhtml']
>>> handle_e... | 13cade11a4a7a5093a629dbd301751de47cdb6ed | 590,156 |
def _adjust(x):
"""Adjust x for sorting in a lambda function. If x is less than 0
then add 3600 to it else just edit it as normal.
:param x: a string to be evaluated and compared.
:return: the adjusted value.
"""
if eval(x) > 0:
return eval(x)
else:
return eval(x)+3600 | 4d167f7d785a907094798e2abbc59a44c4d14019 | 590,157 |
def reverse_list(lst):
"""
>>> reverse_list([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]
"""
lst = lst[::-1]
return lst | 67547a3511f86316ddb5aab00c61906559289283 | 590,159 |
def sample_points(image, region, scale, num_pix, geom=True, seed=1234):
"""Sample points from dataset
Args:
image: image to sample from
region: region to sample from
scale: pixel size in meters
num_pix: number of pixels to be sampled
geom: whether to add the center of th... | 1f39a55e75629766ac5e1c723516b530d9bc31a4 | 590,160 |
import re
def assign_arg_prefix(arg_name, prefix=None):
"""
Assign a parameter prefix to a given argument name. (e.g --prefix_<arg_name>)
`arg_name`: the argument name to prefix
`prefix`: the prefix
return: the prefixed argument name
"""
return arg_name if prefix is None else re.sub(r'^(-{... | b812970cab3e327d3b17b48fd0e03a6012c01b93 | 590,161 |
from typing import Collection
from typing import Tuple
from typing import List
from typing import Set
def book_meetings(
meetings: Collection[Collection[int]],
) -> Tuple[List[List[int]], Collection[int]]:
"""Calculate meetings that maximizes non-conflicting attendees
Non-conflicting means no attendee ap... | 9376774eb306d747dc32fbe320188718d7c3335c | 590,162 |
def api_url(host):
"""
Make api url to obtain configuration
:param host: str
:return: str
"""
return '{}/api/serializers/'.format(host) | 6b1b605023653a60be0c0ea27c28a87f8d1816c5 | 590,171 |
def adjency_to_edges(network, i_map):
"""
Returns array containing the tuples of the edges from a (pseudo)-adjency list of the topology
i.e. a len(leaf_nodes)xlen(root_nodes) matrix with
0 and 1's
:param network: peepo_network
:param i_map: a matrix of shape (len(leaf_nodes),len(root_nodes)) co... | faf44c7539da3d7e5d51359da354634d0423feb6 | 590,173 |
import re
def filter_text(text):
""" filter the text: keep letters and numbers"""
filtered_text = re.findall('\w+', str(text), re.UNICODE)
return filtered_text | f27017558d7b014efb0606e7dddc5fd2ea69c129 | 590,180 |
def capitalify(item: str) -> str:
"""Converts a snake case str to capital case.
Args:
item (str): str to convert.
Returns:
str: 'item' converted to capital case.
"""
return item.replace('_', ' ').title().replace(' ', '') | e1c1238e351f8a116fdacd17138bbce4b6c1d57a | 590,181 |
def get_bitstring_bit(bitstring, bitnum):
"""returns a single bit from within a bitstring, 0 = MSB"""
bytepos = bitnum >> 3
bitpos = 7 - (bitnum % 8)
# we want to return 0 or 1. I'll AND 2^bitpos and then divide by it
return (bitstring[bytepos] & (2 ** bitpos)) >> bitpos | ec6f648a6aaf46f1a337c0fa337a4dc87dcda936 | 590,184 |
def _count_str(string):
"""count rows and columns of a string"""
lines = string.split('\n')
cols = len(lines)
rows = 0
for line in lines:
rows = max(rows, len(line))
return rows, cols | b39b949abc94cd4c533fed669bc4c93a56d5519b | 590,188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.