content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def avoid_keyerror(dictionary, key):
""" Returns the value associated with key in dictionary. If key
does not exist in the dictionary, print out 'Avoid Exception' and
map it to the string 'no value'.
>>> d = {1: 'one', 3: 'three', 5: 'five'}
>>> avoid_keyerror(d, 3)
'three'
>>> avoid_keyer... | 7c55a5ea9c682547a1ab72474d488b2d24bdaca5 | 674,087 |
def getCoOrdinates(xValue, yValue):
"""
retuns an object with x any y values
"""
return {"x": xValue, "y": yValue} | 26b6da55f28ee56173bc35a361a5af73dbf8be66 | 674,088 |
def string_boolean(value):
"""Determines the boolean value for a specified string"""
if value.lower() in ('false', 'f', '0', ''):
return False
else:
return True | b6da9f2802fba2014e2bc2b2eb97791c23aee4bb | 674,089 |
import glob
import json
def merge_single_files(file='histogis-dump.jsonl', source_path='single_files', verbose=True):
"""
writes all geojson from the given folder into a JSONL file
:path: Path to folder containing the .geojson files
:return: A JSONL file.
"""
files = sorted(glob.glob(f"./{sour... | cd4c70a9f2ecf839154b79345b60da4c1e838bb1 | 674,090 |
def add_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
# Training settings
parser.add_argument('--gpu_server_num', type=int, default=1,
help='gpu_server_num')
parser.add_argument('--gpu_num_per_server', type=int... | 0bdd95df5cb806519fb8ebf4db8737144eb6fd66 | 674,091 |
def check_http_and_https(url, ts, pages_dict):
"""Checks for http and https versions of the passed url
in the pages dict
:param url to check, pages_dict the user passed
:returns: True or False depending on if a match was found
:rtype: boolean
"""
parts = url.split(":", 1)
if len(parts) <... | 374cafb9a7f16e8d9304e9cd7d01e03777f92619 | 674,092 |
import torch
def cosine_similarity(x, y=None, eps=1e-8):
"""Calculate cosine similarity between two matrices;
Args:
x: N*p tensor
y: M*p tensor or None; if None, set y = x
This function do not broadcast
Returns:
N*M tensor
"""
w1 = torch.norm(x, p=2, dim=1, keepdim=True)
if y is None... | 68faf837293556409899487b47de072d013a1f42 | 674,093 |
def problem_joint_fitness(x, y):
"""This is the problem-specific joint fitness evaluation.
"""
# MTQ problem.
cf = 10 # Correction factor that controls the granularity of x and y.
h_1 = 50
x_1 = 0.75
y_1 = 0.75
s_1 = 1.6
f_1 = h_1 * \
(1 - ((16.0/s_1) * pow((x/cf - x_1), 2)... | 5362cd630dab87400ada5051cb16faf4aadac0e7 | 674,094 |
def all_same(L):
"""Check if all elements in list are equal.
Parameters
----------
L : array-like, shape (n,)
List of objects of any type.
Returns
-------
y : bool
True if all elements are equal.
"""
y = len(L) == 0 or all(x == L[0] for x in L)
return y | 8ceee5400f348de205a769fb1553901e4dd6a62e | 674,095 |
def _IsDuplicateInterestedUser(url_entity, bots_user_key):
"""Checks if bots_user_key exist in interested_users.
Args:
url_entity: BotsUrl Entity to check for.
bots_user_key: bots_user entity key (db.Key).
Returns:
True if bots_user_key exist in interested_users, else False.
"""
return str(bots_... | 974580702e0cc05d28a285062447c050a5593444 | 674,096 |
def defined_or_defaut_dir(default, directory):
"""
if given a directory it will return that directory, otherwise it returns the default
"""
if directory:
return directory
else:
return default | 6d8227cb215e2eb8f44a806c21476b9467471672 | 674,097 |
import argparse
def read_flags():
"""Returns global variables"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="resize image and adjusts coordinates")
parser.add_argument(
"--src_csv",
default="data/labels_crowdai.csv... | a41e36159bb1c02f477eb4b4624d41e053c444d9 | 674,098 |
def display_timedelta(minutes):
"""Converts timedelta in minutes to human friendly format.
Parameters
----------
minutes: int
Returns
-------
string
The timedelta in 'x days y hours z minutes' format.
Raises
------
ValueError
If the timedelta is negative.
"... | c8606cf6defcc38e5a12dc88cfc65d7c21aefd69 | 674,099 |
def scrape_seed_metadata(soup):
"""Scrapes the seed metadata from an Archive-It results page stored in the
BeautifulSoup object `soup`.
"""
data = []
for item in soup.find_all("div", "result-item"):
itemdict = {}
for entry in item.find_all("h3", "url"):
if 'URL:'... | e593d630dc88f39b202155f6ee35eb123c12a0ad | 674,100 |
import math
def gaussian_kernel(d, sigma_sq):
"""Compute the guassian kernel function of a given distance
@param d the euclidean distance
@param sigma_sq sigma of the guassian, squared.
"""
return math.exp(-(d*d)/(2*sigma_sq)) | c80375e897348eb9b1a7bd9b3a121ef3dc13603f | 674,101 |
def obs_model_parameter_values(values):
"""
Return a list containing all of the values for a single parameter.
:param values: The values for the parameter.
:type values: Union[List[Any], Any]
"""
if isinstance(values, list):
return values
else:
return [values] | bcd8fe5847cf52c13795621842fff2154c91b693 | 674,102 |
import ast
def subscript_type_to_string(subscript: ast.Subscript) -> str:
"""
Returns a string representation of a subscript.
For example, if the subscript is Optional[int] it returns "Optional[int]".
"""
return ast.unparse(subscript) | 2c6f20df7d655858c5c3bfa7f992448f8012d856 | 674,103 |
from collections import OrderedDict
from io import BytesIO
from tokenize import NAME, tokenize
from typing import Callable
from typing import Any
def _expr_to_lambda(expr: str) -> Callable[..., Any]:
"""
Converts a string expression like
"a+b*np.exp(-c*x+math.pi)"
into a callable function with 1 v... | f71633acecf40e753b0cdd37f105975225475acb | 674,104 |
import random
def makelist(random_int):
"""Creates a list of random float values of total list length
random_int (specified as function param)"""
num_list = []
for count in range(random_int):
num_list.append(random.random())
return num_list | 8479ae3b52b6a8f7723ffe7bd71caca9f5ab9c18 | 674,105 |
def listparams_sampling(dms=[0], sizes=[50], windows=[5], mincounts=[2],
samples=[1e-5], negatives=[5], hses=[0], workers=4, epochs=100):
"""
return: a list of parameter combinations
"""
return [{
'dm': dm,
'size': size,
'window': window,
'min_count':... | 7616a85f3c449326748470c3d3af04091b8d7c6a | 674,106 |
import re
def acs_trt_split(data, feature):
"""
Extract keys from ACS identifier column for census tract level data
Parameters
----------
data: pd.DataFrame
Dataframe to make changes to
feature: str
Name of identifier column to extract information from
"""
data = d... | d91c965a6f046e67fb02c65bf9887c1931de49ab | 674,107 |
def get_table_headers(table):
"""Given a table soup, returns all the headers"""
headers = []
for th in table.find("tr").find_all("th"):
headers.append(th.text.strip())
return headers | 7a7291a4a440dfed678e3060f10c9083c27775ca | 674,108 |
def get_terms_and_score_predictions_render(terms_and_score_predictions):
"""
From the full collection of terms and scores, select a number of terms and score predictions to render.
:param terms_and_score_predictions: All terms and score predictions
:return: List of the terms and scores to render
""... | fe719b909f591ac98015c4129c54b6b9d8ddaabf | 674,109 |
import logging
from datetime import datetime
from pathlib import Path
import requests
def download_file(url, file_location=None, overwrite=False):
"""
Purpose:
Download file from specified URL and store in a specfied location.
If no location is provided, the file is downloaded in the current
... | e5e96485faa5b5577688d4dff4f3631b83ce05cd | 674,111 |
from datetime import datetime
def get_now_string():
"""
Returns the current time in roughly the ISO8601 format, but with : replaced
with - to avoid file sytem problems and returns it.
"""
now = datetime.now()
now = now.isoformat()
now = now.replace(':', '-')
now = now[0:now.rfind('.')]... | 19f8d232dde64108eae2c727cffc87f0be33bbd4 | 674,112 |
import re
def md(text):
"""Basic filter for escaping text in Markdown."""
return re.sub(r'([_*])', r'\\\1', text) | e4ab0c874cb0818778506fdf77d79b1a0c2515ed | 674,113 |
def block_to_smiles(block):
""" Convert the formula of a block to a SMILES string """
if block == 'CH2':
return 'C'
elif block == 'NH':
return 'N'
elif block == 'O':
return 'O'
elif block == 'C6H4':
return 'C1=CC=CC=C1'
elif block == 'C4H2S':
return 'C1=CS... | 763b68a42c2a407bd00a88a77a86677af333c227 | 674,114 |
def SVT2(prng, queries, epsilon, N, T):
"""
Alg. 2 from:
M. Lyu, D. Su, and N. Li. 2017.
Understanding the Sparse Vector Technique for Differential Privacy.
Proceedings of the VLDB Endowment.
Modification of implementation by Yuxing Wang
MIT License, Copyright (c) 2018-2019 ... | ad82688b1b22108a6fcae6326b94463975e8e7a4 | 674,115 |
def get_confirmation_block_from_results(*, block_identifier, results):
"""
Return the confirmation block from results list
"""
return next((i for i in results if i['message']['block_identifier'] == block_identifier), None) | 5e815f7c59a953c8b373d0d484ef70e528458424 | 674,116 |
def add(initial: int=0, number: int=0) -> int:
"""Return sum of *intial* and *number*.
:param initial: Initial value.
:type initial: int
:param number: Value to add to initial.
:type number: int
:return: Sum of initial and number.
:rtype: int
"""
return initial + number | 14b29b7ff49ac2961fe49ddbade7eddc3fd2a7a3 | 674,117 |
def sliding_window(array, k):
"""
A sequence of overlapping subsequences
Example:
>>> from m2py import functional as f
>>>
>>> x = ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9']
>>>
>>> print(f.sliding_window(x, 1))
[('x0',), ('x1',), ('x2',), ('x3',), ('x4',), ('x5',... | fd7c45a6d19023998b7b717dd23b356ff90bc081 | 674,118 |
from urllib.parse import urlencode
from typing import OrderedDict
def make_pr_link(url, project, slug, from_branch, to_branch):
"""Generates a URL that can be used to create a PR"""
if "github.com" in url:
result = "{url}/{organization}/{repo_name}/compare/{to_branch}...{from_branch}".format(
... | db5b43db58348789092d3170ccc8e84e32230255 | 674,119 |
def heuristics(values):
"""
Decorator for specifying how the values of certain meta-parameters may be computed.
This is useful for cases where auto-tuning is prohibitevely expensive, or just not applicable.
.. highlight:: python
.. code-block:: python
@triton.heuristics(values={'BLOCK_SIZE... | 40fa7e8e07f65bf111456e0738d2b6f82624ca71 | 674,121 |
from typing import List
from typing import Tuple
def generate_options_for_point(x: int, y: int, z: int) -> List[Tuple[int, int, int]]:
"""
generate 24 different orientations for point presented of (x, y, z)
"""
return [(x, y, z), (z, y, -x), (-x, y, -z), (-z, y, x),
(-y, x, z), (z, x, y), ... | 34530c959686692ac6d749653f8da3a99c0bc4bc | 674,122 |
def filter_bin(length, index_pairs):
"""
用于某些二进制标志位的场景
index_pairs: {index: value,}
返回 length 长度内第 index 位值为 value 的所有可能的 int 的 list, index 从 1 开始, e.g.
>>> filter_bin(3, {1: 1})
[1, 3, 5, 7]
>>> filter_bin(3, {1: 1, 2: 0})
[1, 5]
>>> filter_bin(3, {1: 0, 2: 1})
[2, 6]
"""
... | 692448a8ff75ca997e551ed193498498931ee6ed | 674,123 |
def _find_moved_imports(list_with_import_from_origin_branch, list_with_import_from_working_branch):
"""
Return a list with tuples where the first element is the origin and the second element is
the branch with the modifications
"""
list_with_modified_imports = {
(origin.module + "." + origin... | 629fd6cc2dd81a57b2942bfb648a46573acac204 | 674,124 |
def unwrap(f):
"""Unwrap a decorated function
Requires __wrapped_function and __wrapper_name to be set
"""
for _ in range(42):
try:
uf = getattr(f, '__wrapped_function')
print("Unwrapping %s from %s" % (f.func_name, f.__wrapper_name))
f = uf
except Att... | e96b95a5a22bfb15d20bf4962ab7a782e8de2a6a | 674,125 |
def enforce_order(form_class, fields_in_order):
""" Takes a list of fields used in a form_class and enforces the
order of those fields.
If not all fields in the form are given, the resulting order is undefined.
"""
# XXX to make sure the field order of the existing class remains
# unchanged, ... | ea7878619d953bbac1b03ac4fbc6118896e52109 | 674,126 |
def to_int_str(data):
"""converte para inteiro."""
return str(int(data)) | 3a02813b94690ae06afb79d1b9466e4be7493771 | 674,127 |
def config_empty():
"""Empty config."""
return {} | b87da7db3854374d3e03c7e9d0e70261278725ed | 674,128 |
async def get_hashtags(conn, limit: int):
"""Get top hashtags from users."""
sql = "select hashtags, count(hashtags) as count_hashtags " \
"from tweets t where hashtags != ''" \
" group by hashtags order by count_hashtags desc limit %s;"
return await conn.fetch(sql, (limit,)) | 6b6adcb595ca1b3ee096c2aa4ae07981b82ec64d | 674,129 |
def get_head_indices(model, data):
"""In data.y (the true value here), all feature variables for a mini-batch are concatenated together as a large list.
To calculate loss function, we need to know true value for each feature in every head.
This function is to get the feature/head index/location in the large... | a41241e1ae63f1b9e635842dc7271a6df86db863 | 674,131 |
def GetNECPClientBitFields(necp):
""" Return the bit fields in necp_client as string
returns: str - string representation of necp_client bit fields
"""
bitfields_string = ''
if necp.result_read != 0:
bitfields_string += 'r'
else:
bitfields_string += '-'
if necp.allow_mu... | a7399f4f38f7f57cecfef9a8a926a8dacfe2d1aa | 674,132 |
def switch_month(month: str):
"""
Translates an english month to a french one. For example: 'Jan' becomes '(01)Janvier'.
month : the month that will be translated
"""
return {
"Jan": "(01)Janvier",
"Feb": "(02)Fevrier",
"Mar": "(03)Mars",
"Apr": "(04)Avril",
... | 2a292c64333d9455ca6ce5b7f41b9e83eee2cb82 | 674,133 |
def pretty_printing(Lx,Ly,lattice):
"""
print the lattice for display in regular terminal
"""
for ky in range(Ly):
print(" "*(ky%2),*(lattice[i +ky*Lx] for i in range(Lx)))
return None | 65df07be6e8f0d6dce118b1cfa576a4a2b9fd55d | 674,134 |
def load_data(file_path):
""":param file_path : the file path
:returns : the parsed text
"""
with open(file_path) as f:
text = f.read()
return text | a7b81ce7675692b11f873e6666685728759a070c | 674,135 |
def memory(cmd, value):
"""memory(cmd, value) -> str or int
Get or set information about memory usage.
The value parameter is optional and is only used by some of the commands (see below).
The cmd parameter specifies what memory information to retrieve. It can be one of the following values:
- info [node-name] ... | d920b10cde9d248d65bf2655ea496a18a3e5145f | 674,137 |
def add_arg(*args, **kwargs):
"""
Add arguments for certain function.
"""
def decorator(function):
if not hasattr(function, 'arg'):
function.arg = []
function.arg.append((args, kwargs))
return function
return decorator | 7400cfd89bd9b096f2857181d8ef3c47eac3114c | 674,138 |
def right_node(nodes, x, y):
""" find the first right node
and returns its position """
try:
return str(nodes.index('0', x+1)) + " " + str(y) + " "
except(KeyError, ValueError):
return '-1 -1 ' | 487343b56d5fcec994eccecd253558c97251ccf8 | 674,140 |
import json
def createResourceUsingSession(url, session, resourceName, resourceJson):
"""
create a new resource based on the provided JSON
using a session that already has the auth (credentials)
returns rc=200 (valid) & other rc's from the put
resourceDef (json)
"""
# create a ne... | 5e6467f5dec75a0d7df19b993fd41a1f0adf27f7 | 674,141 |
def square(x):
"""for testing"""
return x * x | 51bdd68f08d049d4956c1439ea67f372de457576 | 674,143 |
def start():
"""Show a working notification on the root page."""
return '<h1>It works!</h1>\nThis is the main page for the scouting server. This page itself is useless. If you want to upload some data, submit it with a POST request to /api/data. If you want to fetch ALLL the data, submit a GET request. All this... | 221ae118cccbd541f529b2d14b85229032155873 | 674,144 |
import json
def extract_json(serie, k):
"""Extract a value by a key."""
return serie.map(lambda row: json.loads(row)[k]) | 1ac588712e832d5e282ca223f3205b2e59d3891a | 674,145 |
import os
def get_python_path() -> str:
""" Accurately get python executable """
python_bin = None
if os.name == 'nt':
python_root = os.path.abspath(
os.path.join(os.__file__, os.pardir, os.pardir))
python_bin = os.path.join(python_root, 'python.exe')
else:
python_r... | c9db725ad67b2c7a469a3a45ce1faf5d2567fe61 | 674,146 |
import subprocess
def run(cmd, logger=None):
"""
Calls subprocess.run with select options.
"""
if logger:
logger.info("Running %s", cmd)
return subprocess.run(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False
) | 60b1656c2334b4ebd5470df5b8ddc6453631f5da | 674,149 |
def escape_quotes(s: str) -> str:
"""Replaces double quotes in the input string with either ' or \\".
Description:
Given a string, returns that string with double quotes escaped in one of two ways.
If the string contains single quotes, then \\" will be used to escape the double quotes.... | 836ff53b7aa19f0a0aeba768b0b9ca181ecd5a4e | 674,150 |
def get_downloadconfig():
""" get configuration from .config_burn file, if it is not existed,
generate default configuration of chip_haas1000 """
configs = {}
configs['chip_haas1000'] = {}
configs['chip_haas1000']['serialport'] = ''
configs['chip_haas1000']['baudrate'] = ''
configs['chi... | bd3d306065196e3934c137b61ff929e1eeb22cb5 | 674,151 |
import os
def sample_data():
"""Loads sample source data from file."""
current_dir = os.path.dirname(__file__)
file_path = os.path.join(current_dir, "sample_data.csv")
with open(file_path) as event_file:
return event_file.read() | e95846b6e051be8e9234f2d754db7fdc0896d0eb | 674,152 |
import glob
def glob_all_files_from_path(wavfiles_path):
"""
#Define the path where the audiofiles(.wav format) are downloaded
"""
all_wav_files_path = glob.glob(wavfiles_path+"*.wav") + glob.glob(wavfiles_path+"*.WAV")
wav_files = []
for each_file in all_wav_files_path:
wav_files.appe... | 38701a7e2389a7eb306a1d6e692317af533049fa | 674,153 |
def process_icon_emoji(inIconEmoji: str) -> str:
"""Process an 'icon_emoji' string.
Args:
inIconEmoji:
Single icon emoji string.
Returns:
Properly formatted 'icon_emoji' string
"""
tmpStr = inIconEmoji.strip(": ")
return f":{tmpStr}:" if tmpStr else "" | 8c497c3c213d5c1ae6dd2991ec0ce1547ba0cf62 | 674,154 |
from typing import Dict
from typing import OrderedDict
import pkg_resources
import os
def _find_templates(template_type: str) -> Dict[str, str]:
"""Find all templates and return a map from short name to full name."""
lookup: Dict[str, str] = OrderedDict()
templates = pkg_resources.resource_listdir("etl", ... | 640d93959c1a1acff59bb007fb84244bf00d2313 | 674,155 |
def GetLabelsFromDict(metadata):
"""Converts a metadata dictionary to a string of labels.
Args:
metadata: a dictionary of string key value pairs.
Returns:
A string of labels in the format that Perfkit uses.
"""
return ','.join('|%s:%s|' % (k, v) for k, v in metadata.iteritems()) | 907611aa94551565d86eccf0f8b01740cd480484 | 674,156 |
import binascii
import hashlib
def hash_password(salt, password):
"""
https://nitratine.net/blog/post/how-to-hash-passwords-in-python/
Modified by: Andres Osorio
:param salt:
:param password:
:return:
"""
salt_bin = binascii.unhexlify(salt)
key = hashlib.pbkdf2_hmac(
'sha2... | 1214083408ef77757159b46cd5fc247b74b6d0eb | 674,157 |
def generate_md_code_str(code_snippet: str, description: str = 'Snippet') -> str:
"""The normal ``` syntax doesn't seem to get picked up by mdv. It relies on indentation based code blocks.
This one liner accommodates for this by just padding a code block with 4 additional spaces.
Hacky? Sure. Effective? Yu... | 4f6f1f61f211292c9f92975fb12659f283f566ef | 674,158 |
def subsample(data, every=5):
"""Subsample to the desired frequency. Use every `every`th sample."""
return data[::every] | 799516f13e75608fbaf22f9adcafff5247fc33d6 | 674,159 |
def check(equation: str) -> bool:
"""Check if the equation is correct"""
if '=' not in equation:
return False
equality = eval(equation.replace('=', '=='))
return equality | 906390241ee79cb02724412330f3ffe9b872143f | 674,160 |
def get_subclasses(klass):
"""Gets the list of direct/indirect subclasses of a class"""
subclasses = klass.__subclasses__()
for derived in list(subclasses):
subclasses.extend(get_subclasses(derived))
return subclasses | 22d9a8def2a1d6b795c05ee0e0fa1899ee839c8b | 674,161 |
import os
import sys
def readme():
"""
This helper function uses the `pandoc` command to convert the `README.md`
into a `README.rst` file, because we need the long_description in ReST
format. This function will only generate the `README.rst` if any of the
`setup dist...` commands are used, otherwise it will... | 84c6b2bbe31ab5e6e5037f635c9d7f283af11b0e | 674,163 |
import string
def words_to_marks(s):
"""This functio taks a string and gives you an int value for the string where a=1 b=2..."""
number = 0
values = dict()
for index, letter in enumerate(string.ascii_lowercase):
values[letter] = index + 1
for i in s:
number = number + values[i]
... | aba41f4c7a76d3502fa1742add9293957634bcbf | 674,164 |
def shift_all(links_json, x):
"""
Shift the full text to account for the link markers.
"""
new_json = {}
for start, end in links_json.keys():
new_start = start - x
new_end = end - x
new_json[tuple([new_start, new_end])] = links_json[(start, end)]
return new_json | 73069ea70afc7b2fee1834cf0f32e69113ff8684 | 674,165 |
def is_vulnerable(source):
"""A simple boolean function that determines whether a page
is SQL Injection vulnerable from its `response`"""
errors = {
# MySQL
"you have an error in your sql syntax;",
"warning: mysql",
# SQL Server
"unclosed quotation mark after the cha... | aafb015e794bccd100a8d63954d6fd43b2ddcf91 | 674,167 |
import os
def get_upload_path_images_payment(instance, filename):
"""
Function to get upload image payment proof dir path
"""
upload_dir = "%s" % instance.team_name
extension = os.path.splitext(filename)[1]
filename = "payment_" + instance.team_name + extension
return os.path.join(uplo... | e6e3234ff1f995cd281ca27cda3db8d71cb55296 | 674,168 |
def skip_material(mtl: int) -> int:
"""Computes the next material index with respect to default avatar skin indices.
Args:
mtl (int): The current material index.
Returns:
int: The next material index to be used.
"""
if mtl == 1 or mtl == 6:
return mtl + 2
return mtl + 1 | fc167912b06137244bbbcb7d9b4225334a5e564e | 674,169 |
import json
import requests
def getProcedures(host, service):
"""
Get all the procedures (stations) using the WA-REST API
"""
proc_url = f"http://{host}/istsos/wa/istsos/services/{service}/procedures/operations/getlist"
# Request and Get the procedures from the response
procedures = json.loa... | 442727d6b844855f52fd6f3f3b52b31aeab5a1bd | 674,171 |
def agg_moy_par_pret(dataframe, group_var, prefix):
"""Aggregates the numeric values in a dataframe. This can
be used to create features for each instance of the grouping variable.
Parameters
--------
dataframe (dataframe):
the dataframe to calculate the statistics on
g... | d046591d17249e21eb65c197aa26bce394a5abdf | 674,172 |
import unicodedata
def lowercase_and_remove_accent(text):
"""
Lowercase and strips accents from a piece of text based on
https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
"""
text = " ".join(text)
text = text.lower()
text = unicodedata.normalize("NFD"... | f05d6815c5dfec40ed51b50662e171c0e13809f6 | 674,173 |
import time
def get_time(t_start):
"""Returns the runtime since the input time."""
t_end = time.time()
t_running = t_end - t_start
time_string = 'Process executed after ' + str(round(t_running, 1)) \
+ ' seconds (i.e. ' + str(int(t_running/60)) + ':' \
+ str(int(rou... | 2f17a034059bda5b0368ecde18d75322cf4b95e0 | 674,175 |
import random
def blood_pressure_depending_on_age(age):
"""Randomly generate a blood pressure value depending upon the given age
value.
It is assumed that for a given age value the blood pressure is normally
distributed with an average blood pressure of 75 at birth (age 0) and of
90 at age 100,... | 77dfbe437a37659ae2326c8aa42c5d8cd5df429b | 674,176 |
import requests
import json
def get_ipify_ip():
"""
Returns your public IP address from ipify.
"""
response = requests.get('https://api.ipify.org?format=json')
ip = json.loads(response.content)['ip']
return ip | 70a477347382a2226bd59c1eb654f2aea5d53b03 | 674,177 |
def write_content(path, content):
"""Write string content to path name."""
print(f"- writing {path}")
with open(path, 'w') as file:
file.write(content)
return path | cba2dd75969435863078f032c01ca2b83745cc0a | 674,178 |
import requests
def grab_ONS_time_series_data(dataset_id, timeseries_id):
"""
This function grabs specified time series from the ONS API.
"""
api_endpoint = "https://api.ons.gov.uk/"
api_params = {"dataset": dataset_id, "timeseries": timeseries_id}
url = (
api_endpoint
+ "/".j... | 51a4b9644e36eb8a70dd8a20eda8465ae9a63045 | 674,179 |
def mountStandard(part, mountpoint):
"""
Mount all partitions that are not "special" aka partitions that are not root, swap etc
boot partitions are allowed here
"""
mount = mountpoint + "/" + part.mountpoint
if mountpoint[-1:] == "/" or part.mountpoint[0] == "/":
mount = mountpoint + par... | 491f781094e5fec62a56df3bfa45e7380fbd5082 | 674,180 |
import os
def replace_extension(full_filename, new_extension):
"""Replace extension of filename.
Args:
full_filename (str): Filename with extension.
new_extension (str): New extension.
Returns:
str: full_filename with replaced extension.
"""
filename, old_extension = os.... | 2665b876b028101e6e75bf61161a2dcb06aa4dff | 674,181 |
def merge_filters(filters1, filters2):
"""Merge two filter lists into one.
Duplicate filters are removed. Since filter order is important,
the order of the arguments to this function also matter. Duplicates
are always removed from the second filter set if they exist in the
first.
The result wi... | 043e8863ceaacb5ada246a5116ea1b2184af2b20 | 674,183 |
import hashlib
def sha1_hash(bytes):
"""
Compute the SHA-1 hash of a byte stream.
"""
sha = hashlib.sha1()
sha.update(bytes)
return sha.digest() | ba45c369407a77bc320b511bafcec7a7c503cf38 | 674,184 |
def founder_allocation() -> float:
"""How much tokens are allocated to founders, etc."""
return 0.2 | 90967e693d9c21c3f729bc9ffdea1472768f58b0 | 674,185 |
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
big_table: An open Bigtabl... | dd3f9dd7798bff45b232ae20ec5d4e7b701d2b48 | 674,186 |
import itertools
def compute_all_edges(data_pts):
"""Compute all edges."""
graph_connections = []
for current in range(0, len(data_pts)):
adjacent = [
data_pts.index(x)
for x in data_pts
if (abs(x[0] - data_pts[current][0]) < 2) and
(abs(x[1] - data_pts[current][1]) < 2) and... | b8d89ea71db5c313f584da50be8aa801c77c301b | 674,187 |
def new_results() -> dict:
"""Create the results dict"""
return {"Hostname": None, "IP": None, "DNS": None, "Results": []} | 11534865444c69a436d22cc36bb98ac40a298288 | 674,188 |
import torch
def generate_padding_masks(data, pad_value=0):
"""
Returns a mask based on the data. For values of the padding token=0, the mask will contain 1, indicating the
model cannot attend over these positions.
:param data: The data of shape (sequence_len, batch_size)
:param pad_value: The val... | f11baece2f4e087440b88562204a4cf187ded6cc | 674,189 |
def get_top_countries(docs, reg_var="coordinator_country", top_n=15):
"""Returns top countries in a cordis table"""
return docs[reg_var].value_counts().index[:15].tolist() | 3b8ccb56310336cb83ba4d22081c39d10c15b772 | 674,190 |
from typing import Dict
def _get_local_logging_config() -> Dict:
"""Create local logging config for running the dummy projects."""
return {
"version": 1,
"formatters": {
"simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"}
},
"root": {"level"... | ba9503e6f408533e360b64eef66d971b9ba4f51a | 674,191 |
import sys
def read_seismogram_file(filename):
"""
This function reads a seismogram and returns 4 lists with the
horizontal components (ns and ew), vertical, and the timestamps
"""
# Start empty
ts = []
ns = []
ew = []
ud = []
# Read file
seis_file = open(filename, 'r')
... | 91ac9366e9e0aa4084f69fc8dbc6700acd0c6dd4 | 674,192 |
def search_course_type(score_table, course_type):
"""
Search course types of courses.
'course_type' is a list, and we will match as much types as possible.
"""
return {v for v in score_table if v[1] in course_type} | f08abdc6ff83e00bedec6db0815a973a9f1f01b0 | 674,193 |
import warnings
def get_mol_3d_coordinates(mol):
"""Get 3D coordinates of the molecule.
This function requires that molecular conformation has been initialized.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule instance.
Returns
-------
numpy.ndarray of shape ... | 7174a29decb05398cae8c4859b323f86d67fb747 | 674,194 |
def attemptNameLookup(const,id):
""" Doesn't necessarily belong here but this avoids circular imports"""
return const.get(id, "UNDEF??[%0X]" % id) | 2301328ff675d2d4b1450586191177160162e9b4 | 674,195 |
def population_render_transparency(x, invert_colours=False, b=None):
"""Render image from patches with transparancy.
Renders patches with transparency using black as the transparent colour.
Args:
x: tensor of transformed RGB image patches of shape [S, B, 5, H, W].
invert_colours: Invert all RGB values.
... | de7e7a0e0fc79ed889fce4bb686d77eff6d1c078 | 674,196 |
import argparse
def check_int_or_float(value):
"""Check if a value is castable to float or rise ArgumentTypeError"""
try:
return float(value)
except:
raise argparse.ArgumentTypeError("%s is neither integer nor float" % value) | c64236e327948dde27757c79c38b3bf759c79ea2 | 674,197 |
import os
def absolute_path(*path):
"""
Turns the given path into an absolute path.
"""
if len(path) == 1 and os.path.isabs(path[0]):
return path[0]
return os.path.abspath(os.path.join(os.path.dirname(__file__), *path)) | 610c739b4794d95275c92ff65ef3e877511764dd | 674,198 |
def validate_listeria(seq_list, metadata_reports):
"""
Checks combined metadata for presence of IGS, inlJ, and hlyA in the GeneSeekr_Profile column
To be confirmed Listeria, the following criteria must be met:
IGS present + (inlJ present OR hlyA present) = True
:param seq_list:
:param metadata... | 346f45203763b18c0be9462e9f7fb2ffc602b505 | 674,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.