content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_stateful(change, stateful_resources):
""" Boolean check if current change references a stateful resource """
return change['ResourceType'] in stateful_resources | 055465870f9118945a9e5f2ff39be08cdcf35d31 | 5,182 |
import difflib
def _get_diff_text(old, new):
"""
Returns the diff of two text blobs.
"""
diff = difflib.unified_diff(old.splitlines(1), new.splitlines(1))
return "".join([x.replace("\r", "") for x in diff]) | bd8a3d49ccf7b6c18e6cd617e6ad2ad8324de1cc | 5,185 |
import argparse
from datetime import datetime
def get_args(args):
"""Get the script arguments."""
description = "tvtid - Feteches the tv schedule from client.dk"
arg = argparse.ArgumentParser(description=description)
arg.add_argument(
"-d",
"--date",
metavar="datetime",
... | 0068f54fc5660896a8ab6998de9da3909c8e1a6b | 5,186 |
def ft2m(ft):
"""
Converts feet to meters.
"""
if ft == None:
return None
return ft * 0.3048 | ca2b4649b136c9128b5b3ae57dd00c6cedd0f383 | 5,187 |
from typing import Dict
def _get_setup_keywords(pkg_data: dict, keywords: dict) -> Dict:
"""Gather all setuptools.setup() keyword args."""
options_keywords = dict(
packages=list(pkg_data),
package_data={pkg: list(files)
for pkg, files in pkg_data.items()},
)
keyw... | 34f2d52c484fc4e49ccaca574639929756cfa4dc | 5,188 |
def release_date(json):
"""
Returns the date from the json content in argument
"""
return json['updated'] | 635efd7140860c8f0897e90433a539c8bd585945 | 5,190 |
import argparse
def parse_arguments():
"""Argument parser for extract_branch_length"""
parser = argparse.ArgumentParser(
description="extract_branch_length.py: extract the branch length of the "
" common ancestor of a set of species"
)
parser.add_argument(
"-t",
"--tree... | 2ee5fcce15420e77307e4444b86b51e18b0fadb7 | 5,191 |
def part_1_solution_2(lines):
"""Shorter, but not very readable.
A good example of "clever programming" that saves a few lines of code, while
making it unbearably ugly.
Counts the number of times a depth measurement increases."""
return len([i for i in range(1, len(lines)) if lines[i] > lines[i - 1]... | d393f0385a1afbea4c2f3b4d3f51d8e7d0ade204 | 5,192 |
import six
def bool_from_string(subject, strict=False, default=False):
"""
将字符串转换为bool值
:param subject: 待转换对象
:type subject: str
:param strict: 是否只转换指定列表中的值
:type strict: bool
:param default: 转换失败时的默认返回值
:type default: bool
:returns: 转换结果
:rtype: bool
"""
TRUE_STRINGS ... | 3c6efa416471da391e60b82aec3753d823ee2878 | 5,195 |
import argparse
def arguments_parser() -> argparse.Namespace:
""" Parses arguments. """
parser = argparse.ArgumentParser(description="Input File containing list of repositories url's")
parser.add_argument("-u", "--username", default='Luzkan',
help="GitHub Username. \
... | 1c3eafc82ac2014c205f1fe5a9356ef47fe9b864 | 5,197 |
def find_used_modules(modules, text):
"""
Given a list of modules, return the set of all those imported in text
"""
used = set()
for line in text.splitlines():
for mod in modules:
if 'import' in line and mod in line:
used.add(mod)
return used | 0b1b2b31f60a565d7ba30a9b21800ba7ec265d0c | 5,198 |
def string2mol2(filename, string):
"""
Writes molecule to filename.mol2 file, input is a string of Mol2 blocks
"""
block = string
if filename[-4:] != '.mol2':
filename += '.mol2'
with open(filename, 'w') as file:
file.write(block)
return None | 51043e7f4edde36682713455dc33c643f89db397 | 5,199 |
from datetime import datetime
def tradedate_2_dtime(td):
""" convert trade date as formatted by yfinance to a datetime object """
td_str = str(int(td))
y, m, d = int(td_str[:4]), int(td_str[4:6]), int(td_str[6:])
return datetime(y, m, d) | 29db7ed41a5cac48af1e7612e1cd2b59ab843a1f | 5,200 |
from typing import Callable
from typing import Optional
def _get_utf16_setting() -> Callable[[Optional[bool]], bool]:
"""Closure for holding utf16 decoding setting."""
_utf16 = False
def _utf16_enabled(utf16: Optional[bool] = None) -> bool:
nonlocal _utf16
if utf16 is not None:
... | 1f0caeab03047cc847d34266c1ed53eabdf01a10 | 5,201 |
import requests
def get(target: str) -> tuple:
"""Fetches a document via HTTP/HTTPS and returns a tuple containing a boolean indicating the result of the request,
the URL we attempted to contact and the request HTML content in bytes and text format, if successful.
Otherwise, returns a tuple containing ... | 1d9d650d77776419318cbd204b722d8abdff94c5 | 5,204 |
import torch
def f_score(pr, gt, beta=1, eps=1e-7, threshold=.5):
"""dice score(also referred to as F1-score)"""
if threshold is not None:
pr = (pr > threshold).float()
tp = torch.sum(gt * pr)
fp = torch.sum(pr) - tp
fn = torch.sum(gt) - tp
score = ((1 + beta ** 2) * tp + eps) \
... | 2c54fd24cd04ac2b41a9d5ca4bf8a7afc5e88640 | 5,205 |
def makeSatelliteDir(metainfo):
"""
Make the directory name for the 'satellite' level.
"""
satDir = "Sentinel-" + metainfo.satId[1]
return satDir | dfbb43f235bc027f25fc9b624097e8f2e0dee4f9 | 5,206 |
import os
import re
def parse_requirements(file_name):
"""Taken from http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy"""
requirements = []
for line in open(os.path.join(os.path.dirname(__file__), "config", file_name), "r"):
line = line.strip()
# comments and blank lines
if re.match(r"(^#)|(^$)",... | f34892163087cecdf84aa7f14da4fc5e56e9f100 | 5,207 |
def grid_id_from_string(grid_id_str):
"""Convert
Parameters
----------
grid_id_str : str
The string grid ID representation
Returns
-------
ret : tuple of ints
A 4-length tuple representation of the dihedral id
"""
return tuple(int(i) for i in grid_id_str.split(',')) | cec058302aae701c1aa28fcb4c4a9d762efa724e | 5,208 |
import re
def safe_filename(name: str, file_ending: str = ".json") -> str:
"""Return a safe version of name + file_type."""
filename = re.sub(r"\s+", "_", name)
filename = re.sub(r"\W+", "-", filename)
return filename.lower().strip() + file_ending | 98a887788046124354676a60b1cf7d990dbbc02f | 5,211 |
def text_editor():
"""Solution to exercise R-2.3.
Describe a component from a text-editor GUI and the methods that it
encapsulates.
--------------------------------------------------------------------------
Solution:
--------------------------------------------------------------------------
... | 39fd3f41cbc28d333dd5d39fc8d1967164bd7bc4 | 5,213 |
import os
def env_path_contains(path_to_look_for, env_path=None):
"""Check if the specified path is listed in OS environment path.
:param path_to_look_for: The path the search for.
:param env_path: The environment path str.
:return: True if the find_path exists in the env_path.
:rtype: bool
"... | 75d650ed6ef21c479404def73edca5cdee4a4bb4 | 5,215 |
def _epsilon(e_nr, atomic_number_z):
"""For lindhard factor"""
return 11.5 * e_nr * (atomic_number_z ** (-7 / 3)) | 8c6115b77ce3fb4956e5596c400c347e68382502 | 5,216 |
import six
def find_only(element, tag):
"""Return the only subelement with tag(s)."""
if isinstance(tag, six.string_types):
tag = [tag]
found = []
for t in tag:
found.extend(element.findall(t))
assert len(found) == 1, 'expected one <%s>, got %d' % (tag, len(found))
return found... | fd4ec56ba3e175945072caec27d0438569d01ef9 | 5,217 |
import os
def GetFilesSplitByOwners(files):
"""Returns a map of files split by OWNERS file.
Returns:
A map where keys are paths to directories containing an OWNERS file and
values are lists of files sharing an OWNERS file.
"""
files_split_by_owners = {}
for action, path in files:
dir_with_owner... | a7c61be189b628a025bb6cff3e67430dfab122b8 | 5,218 |
def get_url(city):
"""
Gets the full url of the place you want to its weather
You need to obtain your api key from open weather, then give my_api_key the value of your key below
"""
my_api_key = 'fda7542e1133fa0b1b312db624464cf5'
unit = 'metric' # To get temperature in Celsius
weat... | 9454a9ad4a2baacb7988216c486c497a0253056c | 5,219 |
def verse(day):
"""Produce the verse for the given day"""
ordinal = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
'tenth',
'eleventh',
'twelfth',
]
gifts = [
... | 027cedf0b1c2108e77e99610b298e1019629c880 | 5,220 |
def mode(lyst):
"""Returns the mode of a list of numbers."""
# Obtain the set of unique numbers and their
# frequencies, saving these associations in
# a dictionary
theDictionary = {}
for number in lyst:
freq = theDictionary.get(number, None)
if freq == None:
# number... | bccf7955741ad4258dea7686559b9cb0bf934ab4 | 5,222 |
def visit_bottomup(f, d):
"""Visits and rewrites a nested-dict ``d`` from the bottom to the top,
using the ``f`` predicate."""
if isinstance(d, dict):
return f({k: visit_bottomup(f, v) for (k, v) in d.items()})
else:
return f(d) | 9fb4884f1280afe06a1819a44e3055c1173284b1 | 5,223 |
def valid_flavor_list():
"""
this includes at least 'BIAS', 'LIGHT' based on forDK.tar.gz samples
capitalization inconsistent in forDK.tar.gz samples
need to keep an eye out for additional valid flavors to add
"""
# not sure how to deal with reduced image flavors that I've invented:
# R... | b12451ff4725f5fcea3592373ef6e53cbe04b23c | 5,224 |
def pairs_to_annotations(annotation_pairs):
"""
Convert an array of annotations pairs to annotation array.
:param annotation_pairs: list(AnnotationPair) - annotations
:return: list(Annotation)
"""
annotations = []
for ap in annotation_pairs:
if ap.ann1 is not None:
annota... | b0e08889f541b14d596616d08b366f59b7f8ddd3 | 5,226 |
def default_meta(inherit=True):
"""Initialize default meta for particular plugin.
Default Meta is inherited by all children comparing to Meta which is unique
per plugin.
:param inherit: Whatever to copy parents default meta
"""
def decorator(plugin):
plugin._default_meta_init(inherit)... | 174b37f389160c007e7a609a78b5071031970004 | 5,227 |
def get_infection_probas_mean_field(probas, transmissions):
"""
- probas[i,s] = P_s^i(t)
- transmissions = csr sparse matrix of i, j, lambda_ij(t)
- infection_probas[i] = sum_j lambda_ij P_I^j(t)
"""
infection_probas = transmissions.dot(probas[:, 1])
return infection_probas | 70d5585b405bdff54f65bced166dead6ae45d26b | 5,228 |
def binom(n, k):
"""Binomial coefficients for :math:`n choose k`
:param n,k: non-negative integers
:complexity: O(k)
"""
prod = 1
for i in range(k):
prod = (prod * (n - i)) // (i + 1)
return prod | 73e06e4c312f6634d9a97914f330ade845a9ce00 | 5,229 |
def find_project(testrun_url):
"""
Find a project name from this Polarion testrun URL.
:param testrun_url: Polarion test run URL
:returns: project name eg "CEPH" or "ContainerNativeStorage"
"""
url_suffix = testrun_url[59:]
index = url_suffix.index('/')
return url_suffix[:index] | a19019846fa084398a4967cb99417e7aebc90499 | 5,230 |
def c2ip(c2, uname):
""" return complete ip address for c2 with substituted username """
return c2['ip_address'].replace('USER', uname) | c6f79b2330e78c8ebc85a3fb99ce1c5be407f158 | 5,231 |
def t_returns(inv, pfl, prices, date):
""" Computes the total return of a portfolio.
Parameters:
- `inv` : :class:`list` investment session `db` row
- `pfl` : :class:`string` name of the portfolio
- `prices` : :class:`dict` latest investment's ticker prices
- `date` ... | 8a928e0806b0e87d2a0539ff905112ad0d3d66ae | 5,232 |
def read_words(file="words.txt"):
"""
Reads a list of words from a file.
There needs to be one word per line, for this to work properly.
Args:
file: the file to read from
Returns:
An array of all the words in the file
"""
with open(file, "r") as f:
return f.read().... | d3d82c4f9afc7db73b4f82f4715cab9b2e99973c | 5,233 |
def get_intersphinx_label(is_map, cur_project_dir):
"""
The top set of keys in the intersphinx map are shortname labels that intersphinx uses to identify different projects
A sub-tuple in the dict (here invdata[1]) is a list of possible locations for the project's objects.inv file
This utility checks a... | 87115f45c966b838566d6909d3a66af5359a2a1d | 5,234 |
import asyncio
async def run_command(*args, **kwargs):
"""Shortcut for asyncronous running of a command"""
fn = asyncio.subprocess.create_subprocess_exec
if kwargs.pop("shell", False):
fn = asyncio.subprocess.create_subprocess_shell
check = kwargs.pop("check", False)
process = await fn(*ar... | 948ccb127afb8cf1c2a1731a5198bc493a1e9fe4 | 5,236 |
def convert_2d_list_to_string(data):
"""Utility function."""
s = ''
for row in data:
c = '{'
for e in row:
c += str(e) + ','
s += c[:-1] + '},\n'
return s[:-2] | a6ac2c05f481a339c68ffc3543baba1f1d0d5e8e | 5,238 |
def PyMapping_Keys(space, w_obj):
"""On success, return a list of the keys in object o. On failure, return NULL.
This is equivalent to the Python expression o.keys()."""
return space.call_function(space.w_list,
space.call_method(w_obj, "keys")) | 452b384a421fd675a53ff20d868b8f7353eb3d79 | 5,240 |
import re
def is_arabicrange(text):
""" Checks for an Arabic Unicode block characters
@param text: input text
@type text: unicode
@return: True if all charaters are in Arabic block
@rtype: Boolean
"""
if re.search(u"([^\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff\u0750-\u077f])", text):
... | 70862e901236eb94fec95ac6f7eb673729397e49 | 5,241 |
def str_repeat(space, s, repeat):
"""Repeat a string."""
return space.newstr(s * repeat) | 3e947da1fa3bf403b0836bd4e7ae0052d310636e | 5,242 |
import json
def file_to_dict(file: str):
"""Dump json file to dictionary"""
try:
with open(file) as json_file:
return json.load(json_file)
except json.decoder.JSONDecodeError:
print(f'File {file} is not a valid json file. Returning empty dict')
return {}
except File... | 2265f2ad5e10931e93a08bafd8e8a7e20c91ae93 | 5,243 |
from typing import Dict
def basic_extractor(
data: Dict,
) -> list:
"""
Returns list of the total_recieved token, the total sent token and the number of transactions the wallet participated in.
"""
return [data["total_received"],data["total_sent"],data["n_tx"]] | 946611423cf98c6104fa49e0ccb82308d741f900 | 5,245 |
def replace_if_present_else_append(
objlist,
obj,
cmp=lambda a, b: a == b,
rename=None):
"""
Add an object to a list of objects, if that obj does
not already exist. If it does exist (`cmp(A, B) == True`),
then replace the property in the property_list. The names
are c... | f76b3a76fe973ef91176f8ff4afd34d52ce89317 | 5,247 |
def rating_value(value):
"""Check that given value is integer and between 1 and 5."""
if 1 <= int(value) <= 5:
return int(value)
raise ValueError("Expected rating between 1 and 5, but got %s" % value) | cadb45a131a423940e1b3a763935f5e40d84285b | 5,248 |
def find_largest_digit_helper(n, max_n=0):
"""
:param n: int,待判別整數
:param max_n: int,當下最大整數值
:return: int,回傳n中最大之 unit 整數
"""
# 特殊情況:已達最大值9,就不需再比了
if n == 0 or max_n == 9:
return max_n
else:
# 負值轉換為正值
if n < 0:
n *= -1
# 用餘數提出尾數
unit_n = n % 10
# 尾數比現在最大值
if unit_n > max_n:
max_n = unit_n
... | cd60a0cdb7cdfba6e2374a564bb39f1c95fe8931 | 5,249 |
def sous_tableaux(arr: list, n: int) -> list:
"""
Description:
Découper un tableau en sous-tableaux.
Paramètres:
arr: {list} -- Tableau à découper
n: {int} -- Nombre d'éléments par sous-tableau
Retourne:
{list} -- Liste de sous-tableaux
Exemple:
>>> sous_ta... | 4f0a627ea00beafb5b6bc77490e71631e8a55e28 | 5,251 |
import json
def normalize_cell_value(value):
"""Process value for writing into a cell.
Args:
value: any type of variable
Returns:
json serialized value if value is list or dict, else value
"""
if isinstance(value, dict) or isinstance(value, list):
return json.dumps(value)... | 8ef421814826c452cdb6528c0645133f48bd448a | 5,254 |
def mongodb():
"""
Simple form to get and set a note in MongoDB
"""
return None | a6de90429bb3ad3e23191e52e1b43484435747f9 | 5,255 |
import os
def list_subdir(path):
""" list all subdirectories given a directory"""
return [o for o in os.listdir(path) if os.path.isdir(path / o)] | d99760b6ec914d59cdbf5b8f4bc2bb8b0a30f9e8 | 5,257 |
def genBinaryFileRDD(sc, path, numPartitions=None):
"""
Read files from a directory to a RDD.
:param sc: SparkContext.
:param path: str, path to files.
:param numPartition: int, number or partitions to use for reading files.
:return: RDD with a pair of key and value: (filePath: str, fileData: Bina... | 85ef3c657b932946424e2c32e58423509f07ceae | 5,259 |
def extract_year_month_from_key(key):
"""
Given an AWS S3 `key` (str) for a file,
extract and return the year (int) and
month (int) specified in the key after
'ano=' and 'mes='.
"""
a_pos = key.find('ano=')
year = int(key[a_pos + 4:a_pos + 8])
m_pos = key.find('mes=')
month... | b52dc08d393900b54fca3a4939d351d5afe0ef3c | 5,260 |
def parentheses_cleanup(xml):
"""Clean up where parentheses exist between paragraph an emphasis tags"""
# We want to treat None's as blank strings
def _str(x):
return x or ""
for em in xml.xpath("//P/*[position()=1 and name()='E']"):
par = em.getparent()
left, middle, right = _st... | b5a476cd6fd9b6a2ab691fcec63a33e6260d48f2 | 5,261 |
import numpy
def filter_atoms(coordinates, num_atoms=None, morphology="sphere"):
"""
Filter the atoms so that the crystal has a specific morphology with a given number of atoms
Params:
coordinates (array): The atom coordinates
num_atoms (int): The number of atoms
morphology (str):... | 9763f2c7b14a26d089bf58a4c7e82e2d4a0ae2bd | 5,262 |
def create_list(value, sublist_nb, sublist_size):
"""
Create a list of len sublist_size, filled with sublist_nb sublists. Each sublist is filled with the value value
"""
out = []
tmp = []
for i in range(sublist_nb):
for j in range(sublist_size):
tmp.append(value)
out.... | 1ecf6c88390167584d1835430c359a7ed6d6b40b | 5,264 |
def gen_r_cr():
"""
Generate the R-Cr table.
"""
r_cr = [0] * 256
for i in range(256):
r_cr[i] = int(1.40199 * (i - 128))
return r_cr | 43e014bb62c40d038c5fbd124e834e98e9edb5e3 | 5,265 |
def getGpsTime(dt):
"""_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime
"""
total = 0
days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc.
total += days*3600*24
total += dt.hour * 3600
total += dt.minute * 60
total += dt.second
return(tot... | 16caa558741d8d65b4b058cf48a591ca09f82234 | 5,266 |
def _round_to_4(v):
"""Rounds up for aligning to the 4-byte word boundary."""
return (v + 3) & ~3 | c79736b4fe9e6e447b59d9ab033181317e0b80de | 5,267 |
def lower_threshold_projection(projection, thresh=1e3):
"""
An ugly but effective work around to get a higher-resolution curvature
of the great-circle paths. This is useful when plotting the great-circle
paths in a relatively small region.
Parameters
----------
projection : class
... | 165c657f1ec875f23df21ef412135e27e9e443c6 | 5,269 |
def has_param(param):
"""
Generate function, which will check `param` is in html element.
This function can be used as parameter for .find() method in HTMLElement.
"""
def has_param_closure(element):
"""
Look for `param` in `element`.
"""
if element.params.get(param,... | 6800725c378714b5161772f0a2f9ef89ae278400 | 5,273 |
def get_all_keys(data):
"""Get all keys from json data file"""
all_keys = set(data[0].keys())
for row in data:
all_keys = set.union(all_keys, set(row.keys()))
return list(all_keys) | 5532af993f87bf4e00c7bec13eb971e0114e736c | 5,274 |
def _ngl_write_atom(
num,
species,
x,
y,
z,
group=None,
num2=None,
occupancy=1.0,
temperature_factor=0.0,
):
"""
Writes a PDB-formatted line to represent an atom.
Args:
num (int): Atomic index.
species (str): Elemental species.
x, y, z (float): Ca... | 92a5d62f3c4f6d927aa5a6010b217344d0d241d3 | 5,275 |
def get_insert_components(options):
""" Takes a list of 2-tuple in the form (option, value) and returns a
triplet (colnames, placeholders, values) that permits making a database
query as follows: c.execute('INSERT INTO Table ({colnames}) VALUES
{placeholders}', values). """
col_names = ','.join(opt[0] for opt in o... | 3e1deecd39b0e519124278f47713d5b3a1571815 | 5,276 |
def enumerate_trials(perievents):
"""
adds an index to perievents_2D that counts the number of trials per session and event
starting with 1, removes FrameCounter index
:param perievents: perievents df, non-column based format
:return: perievents df with additional index Trial
"""
# unstack i... | d469a823b6af60d305dc37b1ce42176f16b21f8d | 5,278 |
import torch
def add_dims_right(tensor, ndims, right_indent=0):
""" Add empty dimensions to the right of tensor shape
"""
assert right_indent >= 0
for i in range(ndims):
tensor = torch.unsqueeze(tensor, -1-right_indent)
return tensor | 7d4c1b47eb659f0bcfc9dbcf7f7b04c1ccbafb80 | 5,279 |
def get_submodel_name(history = 60, lag = 365, num_neighbors = 20, margin_in_days = None, metric = "cos"):
"""Returns submodel name for a given setting of model parameters
"""
submodel_name = '{}-autoknn-hist{}-nbrs{}-margin{}-lag{}'.format(metric,
... | 69fa276a86c39f342ffceba72408ab6970dd0a41 | 5,280 |
def compress_public_key(public_key):
"""Compresses a given uncompressed public key.
:param public_key: the key to compress, as bytes
:return: the compressed key, as bytes
"""
if public_key[0] != 0x04 or len(public_key) != 65:
raise ValueError('invalid uncompressed public key')
# We take... | 8ff7c609a216e29b9cc31584e3cd824f7ab2879d | 5,281 |
def forward(layers, x):
"""
function for performing forward propagation in all the layers
Parameters:
layers : list
x : numpy array
Returns:
list : (contains output of all layers in the form of numpy arrays)
"""
conv = layers[0]
pool = layers[1]
de... | 2e7ae3c8ab513ca5f138c77a868783dc942063ee | 5,283 |
def __same_axes(x_axis, y_axis, xlim, ylim):
"""Check if two axes are the same, used to determine squared plots"""
axes_same_and_not_none = (x_axis == y_axis) and (x_axis is not None)
axes_same_lim = xlim == ylim
return axes_same_and_not_none and axes_same_lim | ce7538ffa17e15df0fc055809103bf69af88e7aa | 5,284 |
import csv
def create_column_dicts(path_to_input):
"""Creates dictionaries: {column_index, column_name} and
{column_name, column_index}"""
cols = {}
with open(path_to_input, newline="") as csvfile:
inputreader = csv.reader(csvfile, delimiter=",")
row = next(inputreader)
for i, ... | 13bf2e3c99fea9b1d2580b7bfc34e445af8b7e98 | 5,285 |
import string
def get_sentiment(text, word_map):
"""
Identifies the overall sentiment of the text by taking the average
of each word.
Note: Words not found in the word_map dict are give zero value.
"""
# remove all punctuation
text = text.translate(str.maketrans("", "", string.punctuatio... | ee9e57c999539c0126e5c0d38711a617e82dab10 | 5,286 |
def handle_all_serials(oid, *args):
"""Return dict of oid to serialno from store() and tpc_vote().
Raises an exception if one of the calls raised an exception.
The storage interface got complicated when ZEO was introduced.
Any individual store() call can return None or a sequence of
2-tuples where... | f2ff56d43f40f4bad5a802acbbe7a8fa869831d3 | 5,288 |
def remove_null_fields(data):
"""Remove all keys with 'None' values"""
for k, v in data.items():
if isinstance(v, dict):
remove_null_fields(v)
if isinstance(v, list):
for element in v:
remove_null_fields(element)
if not data[k]:
del dat... | 3dc90d215d899afb2316acb92b5755fd93da204f | 5,289 |
def find_recipes(rounds):
"""
Calculate the last ten recipes in the sequence.
:param rounds: the number of rounds
:return: a list of the last 10 recipes in the sequence
>>> find_recipes(5)
[0, 1, 2, 4, 5, 1, 5, 8, 9, 1]
>>> find_recipes(18)
[9, 2, 5, 1, 0, 7, 1, 0, 8, 5]
>>> find_re... | 281cd92094cf9c4be608de5a57075f7f38a531d0 | 5,290 |
def query_abs_over_wiki(abstract):
"""
query from es with the document is wiki_entity
"""
return {
"track_total_hits": "true",
"version": "true",
"size": 1000,
"sort": [{
"_score": {
"order": "desc"
}
}],
"_source": ... | 7e35af5b210cd3485113d7cb5b72f7dd32745d94 | 5,291 |
from six.moves import urllib
def has_internet():
"""
Test if Internet is available.
Failure of connecting to the site "http://www.sagemath.org" within a second
is regarded as internet being not available.
EXAMPLES::
sage: from sage.doctest.external import has_internet
sage: has_... | d9cacc17a315abe85022e9a889d4a1da3c9b6a49 | 5,293 |
def read_warfle_text(path: str) -> str:
"""Returns text from *.warfle files"""
try:
with open(path, "r") as text:
return text.read()
except Exception as e:
raise Exception(e) | ba15fe6a62fbefe492054b0899dcdbff35462154 | 5,294 |
import os
def avi_common_argument_spec():
"""
Returns common arguments for all Avi modules
:return: dict
"""
return dict(
controller=dict(default=os.environ.get('AVI_CONTROLLER', '')),
username=dict(default=os.environ.get('AVI_USERNAME', '')),
password=dict(default=os.envir... | 5bed3408a2f843053271656d98f5919feaee4b02 | 5,295 |
import os
def get_largest_files_new(directory: str, num: int) -> list:
"""
Return a sorted list containing up to num of the largest files from the directory.
Preconditions:
- num > 0
"""
# ACCUMULATOR: Priority queue so far
list_so_far = []
for root in os.walk(directory):
p... | a9966a03166d1102cc2567fbb5bc19f336893b35 | 5,296 |
def _full_url(url):
"""
Assemble the full url
for a url.
"""
url = url.strip()
for x in ['http', 'https']:
if url.startswith('%s://' % x):
return url
return 'http://%s' % url | cfb56cf98d3c1dd5ee2b58f53a7792e927c1823f | 5,297 |
def encodeUcs2(text):
""" UCS2 text encoding algorithm
Encodes the specified text string into UCS2-encoded bytes.
@param text: the text string to encode
@return: A bytearray containing the string encoded in UCS2 encoding
@rtype: bytearray
"""
result = bytearray()
for b in ... | da2243ffc959db64a196a312522f967dce1da9d1 | 5,298 |
import argparse
def get_parser():
""" Builds the argument parser for the program. """
parser = argparse.ArgumentParser()
parser.add_argument('-c', type=str, dest='clf_key', default='dt', choices=['dt', 'xts', 'rf'], help='A classifier to use.')
parser.add_argument('-m', type=str, dest='mode', default=... | 6246e9105d1435715b5297afe87de15288b5f7ea | 5,299 |
def units_to_msec(units, resolution):
"""Convert BLE specific units to milliseconds."""
time_ms = units * float(resolution) / 1000
return time_ms | 49588d7961593b2ba2e57e1481d6e1430b4a3671 | 5,300 |
def is_data(data):
""" Check if a packet is a data packet. """
return len(data) > 26 and ord(data[25]) == 0x08 and ord(data[26]) in [0x42, 0x62] | edb2a6b69fde42aef75923a2afbd5736d1aca660 | 5,302 |
def get_tf_metric(text):
"""
Computes the tf metric
Params:
text (tuple): tuple of words
Returns:
tf_text: format: ((word1, word2, ...), (tf1, tf2, ...))
"""
counts = [text.count(word) for word in text]
max_count = max(counts)
tf = [counts[i]/max_count for i in range(0, len(counts))]
return text, tf | 6397e150fa55a056358f4b28cdf8a74abdc7fdb6 | 5,303 |
def getKeyFromValue(dictionary, value):
"""
dictionary内に指定したvalueを持つKeyを検索して取得
"""
keys = [key for key, val in dictionary.items() if val == value]
if len(keys) > 0:
return keys[0]
return None | d2bb42938a809677f4a96e869e9e03c194a28561 | 5,306 |
import struct
def incdata(data, s):
"""
add 's' to each byte.
This is useful for finding the correct shift from an incorrectly shifted chunk.
"""
return b"".join(struct.pack("<B", (_ + s) & 0xFF) for _ in data) | 89633d232d655183bee7a20bd0e1c5a4a2cc7c05 | 5,308 |
import string
def strip_non_printable(value):
"""
Removes any non-printable characters and adds an indicator to the string
when binary characters are fonud
:param value: the value that you wish to strip
"""
if value is None:
return None
# Filter all non-printable characters
#... | 279ea769bd7d57ee3e4feb9faf10f2a3af3aa657 | 5,309 |
import math
def tangent_circle(dist, radius):
"""
return tangent angle to a circle placed at (dist, 0.0) with radius=radius
For non-existing tangent use 100 degrees.
"""
if dist >= radius:
return math.asin(radius/float(dist))
return math.radians(100) | bcde88456a267239566f22bb6ea5cf00f64fa08e | 5,310 |
def state_transitions():
"""Simplified state transition dictionary"""
return {
"E": {"A": {"(0, 9)": 1}},
"A": {"I": {"(0, 9)": 1}},
"I": {"H": {"(0, 9)": 1}},
"H": {"R": {"(0, 9)": 1}}
} | f8c79f8071f2b61ceacaacf3406a198b2c54c917 | 5,311 |
from datetime import datetime
def TimeSec():
"""[Takes current time in and convert into seconds.]
Returns:
[float]: [Time in seconds]
"""
now = datetime.now()
return now.second+(now.minute*60)+(now.hour*60*60) | 58892b89feb05a56c27d4fd62ba174f9d1c09591 | 5,313 |
import re
def server_version(headers):
"""Extract the firmware version from HTTP headers."""
version_re = re.compile(r"ServerTech-AWS/v(?P<version>\d+\.\d+\w+)")
if headers.get("Server"):
match = version_re.match(headers["Server"])
if match:
return match.group("version") | 24151f3898430f5395e69b4dd7c42bd678626381 | 5,314 |
def es_subcadena(adn1, adn2):
"""
(str, str) -> bool
>>> es_subcadena('gatc', 'tta')
False
>>> es_subcadena('gtattt', 'atcgta')
False
:param:adn1:str:primera cadena a comparar
:param:adn2:str:segunda cadena a comparar
:return:bool:verificacion si una es subcadena de la otra
"""... | 9c3605e74e1c9dbf227695a4f0f6431cc845a5f1 | 5,315 |
def get_labels_and_features(nested_embeddings):
""" returns labels and embeddings
"""
x = nested_embeddings[:,:-1]
y = nested_embeddings[:,-1]
return x,y | 302505bd3aa769570fa602760f7da1ddd017e940 | 5,316 |
def parse_locator(src):
""" (src:str) -> [pathfile:str, label:either(str, None)]
"""
pathfile_label = src.split('#')
if len(pathfile_label)==1:
pathfile_label.append(None)
if len(pathfile_label)!=2:
raise ValueError('Malformed src: %s' % (src))
return pathfile_label | 970bc1e2e60eec4a54cd00fc5984d22ebc2b8c7a | 5,317 |
def detect_seperator(path, encoding):
"""
:param path: pathlib.Path objects
:param encoding: file encoding.
:return: 1 character.
"""
# After reviewing the logic in the CSV sniffer, I concluded that all it
# really does is to look for a non-text character. As the separator is
# determine... | 8436359a602d2b8caf72a6dbdac4870c502d1bad | 5,318 |
from typing import List
from typing import Optional
def check(s: str) -> None:
"""
Checks if the given input string of brackets are balanced or not
Args:
s (str): The input string
"""
stack: List[str] = []
def get_opening(char: str) -> Optional[str]:
"""
Gets the... | 720018e5b39e070f48e18c502e8a842feef32840 | 5,319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.