content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_outliers(points, column):
""" Remove outliers by using the statistical approach
as described in
https://www.itl.nist.gov/div898/handbook/prc/section1/prc16.htm
Keyword Arguments:
points {GeoDataFrame} -- A GeoDataFrame containing the track points
column {String} -- Columnn na... | 81008fb94a0302f4b5328bf1ad2985074d6b5c4b | 664,106 |
def separar_columnas(df):
"""Funcion que recibe DataFrame y separa la informacion de ClaimNumber en dos columnas (Code1_mc y Code2_mi).
Tambien separa Address en Direccion, Condado, Estado y Codigo postal"""
codigos= df['ClaimNumber'].str.split(expand=True) #Separar ClaimNumber
df['Code1_mc']=codigos[0... | 62b33d329082d0f82a71c039b3edd42156d2ceaf | 664,107 |
import time
def get_cur_timestamp():
""" 获取当前时间戳
"""
ts = int(time.time())
return ts | 4246105c2cae4205d2123438db131935fc0b83f4 | 664,108 |
from typing import Sequence
from typing import List
import random
def new_shuffle_list(seq: Sequence[str], seed: str) -> List[str]:
"""Deterministically shuffle"""
fixed_random = random.Random()
fixed_random.seed(seed, version=2)
seq = list(seq)
fixed_random.shuffle(seq)
return seq | 797f517e60a3f1d8861d44ff21ac6b1607fd20e5 | 664,109 |
def unwrap(func, stop=None):
"""Backport of Python 3.4's inspect.unwrap function.
Retrieves the object wrapped by func, following the chain of __wrapped__
attributes to reach the originally wrapped object.
Allows an optional stop callback which accepts the *current* function
as its only argument t... | d33027b36ac75493a1bf1ff09b88b683ffd60e14 | 664,111 |
def to_str(slug):
"""
converts slug to str
:param slug:
:return: str
"""
if not isinstance(slug, str):
raise ValueError("to_str expects arguments of type 'str'")
return ' '.join(slug.split('-')) | 1928d975e3315f809d6e0b39e1387f2d2de6da6d | 664,113 |
def _calc_detlam(xx, yy, zz, yx, zx, zy):
"""
Calculate determinant of symmetric 3x3 matrix
[[xx,yx,xz],
[yx,yy,zy],
[zx,zy,zz]]
"""
return zz * (yy*xx - yx**2) - \
zy * (zy*xx - zx*yx) + \
zx * (zy*yx - zx*yy) | 810c2e39f8c85dda255121394fbef5e0f21b8f24 | 664,114 |
import codecs
def from_json(json_object):
"""For py3 compat"""
if '__class__' in json_object:
if json_object['__class__'] == 'bytes':
return codecs.decode(json_object['__value__'].encode(), 'base64')
return json_object | a3841227e2e7b8f3ea367a63bad72209a1420845 | 664,115 |
def remove_useless_features(train, submission, pourc_of_db=0.30):
"""
Apply manual dimension reduction on features having more than 50% (default) equal to zero(0).
"""
mask = ((train == 0).sum() / train.shape[0]) > pourc_of_db
nb_useless = mask.sum()
print("Number of features having more th... | b6911ed935bf8556bd39be446f9a074e7846750d | 664,117 |
import hashlib
def get_sha512_sums(file_bytes):
""" Hashes bytes with the SHA-512 algorithm """
return hashlib.sha512(file_bytes).hexdigest() | 3f88cab516e0a8e2a209bef840cb112804cdac10 | 664,119 |
import re
def refinepath(s, reserve=''):
"""
:param reserve: 保留的字符,例如输入'*?',会保留这两个字符作为通配符
"""
if not s: return s
# 1 去掉路径中的不可见字符,注意这里第1个参数里有一个不可见字符!别乱动这里的代码!
s = s.replace(chr(8234), '')
chars = set(r'\/:*?"<>|') - set(reserve)
for ch in chars: # windows路径中不能包含的字符
s = s.replac... | dc23c286e9f9aa211bbfdfb3d7d9177602b390b0 | 664,120 |
import glob
def list_files(includes, excludes, reverse=False):
"""
:return: List of filenames matching the includes pattern minus excludes pattern
"""
paths = glob.glob(includes)
exclude_paths = []
if excludes:
exclude_paths = glob.glob(excludes)
paths = [path.replace('\\', '/') f... | 29a6e262803dec8fef446bf6e824e3a3e235e00a | 664,121 |
def _colorize(text, color):
"""Applies ANSI color codes around the given text."""
return "\033[1;{color}m{text}{reset}".format(
color = color,
reset = "\033[0m",
text = text,
) | 7bf5313677f8d065ed01977bad8ad06196377c62 | 664,122 |
def factory_name(obj):
""" Returns a string describing a DisCoPy object. """
return '{}.{}'.format(type(obj).__module__, type(obj).__name__) | 86fae35d0884b9de59535f771aae81436e5906fb | 664,123 |
def get_marker(func_item, mark):
""" Getting mark which works in various pytest versions """
pytetstmark = [m for m in (getattr(func_item, 'pytestmark', None) or []) if m.name == mark]
if pytetstmark:
return pytetstmark[0] | d526b4265c8d8e2420c87955d44b3268d195a571 | 664,124 |
def _approx_equal(a, b, tolerance):
"""Check if difference between two numbers is inside tolerance range."""
if abs(a - b) <= tolerance * a:
return True
else:
return False | 2f2c2a15b21e96f7d34e669d99acd1f06c333829 | 664,126 |
def _field_name(name, prefix=None):
"""
Util for quick prefixes
>>> _field_name(1)
'1'
>>> _field_name("henk")
'henk'
>>> _field_name("henk", 1)
'1henk'
"""
if prefix is None:
return str(name)
return "%s%s" % (prefix, name) | 03efaaca97ceffb1da958032f6d5ec65509c079f | 664,127 |
import numpy
def get_list_of_points(timeseries):
"""This function creates a list of angles based on the time series.
This list is used for convert the time series to a polygon.
:param timeseries: Your time series.
:type timeseries: numpy.ndarray
:return list_of_observations: Numpy array of lists... | e95ff203dcba8e50cb884f0c57882b3433027f48 | 664,128 |
def solveGomoku(size, grid, findAll=False):
"""Find the winning player from a gomoku game state.
If findAll is True, try to find all winning sets of 5 pawns."""
# Function to read the grid
def getPawn(row, col):
if (row < 0) or (row >= size) or (col < 0) or (col >= size):
return 0
... | 92f8a392409ba723a31092613240efcd8289c495 | 664,129 |
def call_function(name, instance=None, **params):
"""
Makes a call to a function or a method of an instance. The name of the
function/method to call must be provided, named parameters can also be provided.
The name of the function to call must contain the full path to its module:
call_function("... | bed1c271d5a47da2cda66bf52c97a68ac532c22c | 664,130 |
def _make_tuple(elem, repeats):
"""
expand 3 into (3, 3) for strides/paddings
"""
if isinstance(elem, int):
return [elem] * repeats
else:
assert len(elem) == repeats
return [int(x) for x in elem] | 48deb64e1161add46c177fac83e75ae75f406865 | 664,131 |
async def battle(ctx):
"""
- Battles a wild pokemon and earns you money based on it's rarity.
"""
return await battle(ctx) | 0373e0340986555f7cfea74be6157be449ea063b | 664,132 |
def need_args():
"""Check if arguments are given
Returns
-------
bool
"""
return print("No arguments was given") | 44c62b0b61054fe222434f1d4ae142269de29802 | 664,133 |
def filter_result(result):
"""Remove keys from shell/command output.
"""
stdout = result.pop('stdout', '')
stdout_lines = result.pop('stdout_lines', [])
if not stdout_lines and stdout:
stdout_lines = stdout.split('\n')
# for key in ('changed', 'cmd', 'invocation',
# 's... | 8087ed150d85fbc4185a24b5cf2b74fc9c6d2feb | 664,134 |
import re
def title(value):
"""Converts a string into titlecase."""
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) | 9d9ee0185ec94226272f508a0cb0bc13b58c7a2d | 664,136 |
from typing import OrderedDict
def sort_dictionary(dictionary):
"""
This function will turn a dictionary with sortable keys into an
OrderedDict with keys in the ordering of the keys.
This dictionary will have two levels of nesting as it will be a mapping of
the sort {State -> {State -> value}}
... | 0eb6d8ba5ec0257938d726ad19925033c9cf319c | 664,137 |
def parse_img_list(img_list):
"""
get the pure images id
"""
img_id = []
with open(img_list,'r') as f:
for temp in f.readlines():
temp = temp.split('/')[-1]
temp = temp.split('.')[0]
img_id.append(temp)
# print(img_id)
return img_id | 97ac401f5fac7b38458ce9fe2ed78c2ed37bf838 | 664,138 |
import math
def phi(n):
"""Calcula o totiente de Euler (função phi)
Args:
n: numero que terá o totiente de Euler calculado
Returns:
valor do totiente de Euler
"""
amount = 0
for k in range(1, n + 1):
if math.gcd(n, k) == 1:
amount += 1
return amount | 9c39b9190218b4e13b55e03432da99627bece558 | 664,139 |
def coin_list(self):
"""
https://www.cryptocompare.com/api/#-api-data-coinlist-
"""
return self._fetch_data(self.COIN_LIST_URL) | 5a60b01243a39987920f72061c89c65181a51f8a | 664,141 |
def square(n):
"""Square a Number."""
return n ** 2 | ea8c204d4cf33d6bba216be09ce224ff523346a5 | 664,143 |
def parse_json_data(data,sep='\t'):
""" Extract the data from json into a dictionary and a string """
# Set up the dictionary
keys = ['date','rower','meters','duration','split','spm',
'watts','calories','resistance','instructor','workout']
workout = {}
# Pointers to portions of the data... | 4c446c548ab10265d5ac911853ef7660197506c7 | 664,144 |
def merge(L1: list, L2: list) -> list:
"""Merge sorted lists L1 and L2 into a new list and return that new list.
>>> >>> merge([1, 3, 4, 6], [1, 2, 5, 7])
1, 1, 2, 3, 4, 5, 6, 7]
"""
newL = []
i1 = 0
i2 = 0
# For each pair of items L1[i1] and L2[i2], copy the smaller into newL.
whi... | 9b6423a2ed8ac900668cef3221ca3db7e581500f | 664,145 |
def filter_entity(org_name, app_name, collection_name, entity_data, source_client, target_client, attempts=0):
"""
This is an example handler function which can filter entities. Multiple handler functions can be used to
process a entity. The response is an entity which will get passed to the next handler i... | 301b989b19e4f62587ebc55546b6e84d8ca625a1 | 664,147 |
def _fix_old_syntax(tree):
"""Function for 'catching old glm format and translating it.'
This is intended to work recursively to catch nested objects.
"""
for key in list(tree.keys()):
if 'object' in list(tree[key].keys()):
# if no name is present and the object name is the old synta... | d7e1577d58bde9ec380e42d7cdd8606117a7b505 | 664,148 |
def get_host_id(session, hostname):
"""
Get host_id from the hostname.
"""
query = """
SELECT host_id FROM monitoring.hosts
WHERE hostname = :hostname
"""
result = session.execute(query, {"hostname": hostname})
try:
return result.fetchone()[0]
except Exception:
... | 7522eeebb9ebf8b0ff9c0f86bde7d6db59d43d87 | 664,150 |
def system(db):
"""An empty system."""
return db.system | 03a4f42af5e140ecd9ad65adfb4e39a9625eed81 | 664,151 |
def find_smallest_bin(b):
"""
Take boundary non-uniform vector and find smallest bin
assuming they are multiple of each other
Parameters
----------
b: array of floats
boundaries, in mm
returns: float
minimal bin size
"""
minb = 10000000.0
prev = b[0]
ll ... | bfeab80625eb939cc799946be49974c86a39cc0c | 664,152 |
def _func_star(args):
"""
A function and argument expanding helper function.
The first item in args is callable, and the remainder of the items are
used as expanded arguments. This is to make the function header for reduce
the same for the normal and parallel versions. Otherwise, the functions
... | 56901a69afdc403188e46f9b80942d7af3f38e46 | 664,153 |
import sys
def _tool():
"""Run the analysis from the tool
"""
testing = False
orig_fc = sys.argv[1]
dest_fc = sys.argv[2]
N = int(sys.argv[3])
out_fc = sys.argv[4]
# out_fc = r"C:\GIS\A_Tools_scripts\PointTools\Data\Near_testing.gdb\a2b"
args = ['closest_od.py', testing, orig_fc, de... | 02dde2aa2a92ca76cb8c2972e7b815ca30ac25d0 | 664,154 |
import pathlib
import os
def get_logpath(logdirpath):
"""
Args:
logdirpath ([str]): [path to a directory where to store logs]
Returns:
[bool]: [return True if an existing and writable path to directory is provided]
"""
if not pathlib.Path(logdirpath).exists():
try:
... | 1725dfd83ac77331ab4ca3926a4830204662047f | 664,155 |
def always_none(x):
"""Returns None"""
return None | fd19ec3bb5d0f76ebf79f1c4d600764d768243a1 | 664,156 |
def run_algo(op_list):
"""Execute all operations in a given list (multiply all matrices to each other)."""
ops = op_list[::-1] # reverse the list; after all, it's matrix mult.
result = ops[0]
for op in ops[1:]:
result = result * op
return result | d7954d938162885b704bf479f63dcc6741e8e65d | 664,157 |
def get_docomo_post_data(number, hidden_param):
"""Returns a mapping for POST data to Docomo's url to inquire for messages
for the given number.
Args:
number: a normalized mobile number.
Returns:
a mapping for the POST data.
"""
return {'es': 1,
'si': 1,
'... | ed46f080ac6cda8882bf826cad39f03512da334b | 664,158 |
def summarizeMaterial(mat, iDigits=5):
""""
summarizeMaterial(mat, iDigits)
A utility function to summarize a material
Parameters
----------
mat - a DTSA material
The material to list
iDigits - integer
decimal places to round
Returns
-------
A tuple: ( name, dictionary{Symbol : {mf : mass-fraction, af... | 85df8745e1cdfc469339e58ad179866cdeb56864 | 664,159 |
def AioNodeNameFromLightNickname(light):
"""Returns AIO node name for the specified light node."""
if light == 'BaseStation':
return 'kAioNodeGpsBaseStation'
else:
return 'kAioNodeLight' + light | d2724e7443c4b7332851bbaa450c72968d1fa112 | 664,160 |
from typing import List
def encode_message(message_string: str) -> List[int]:
"""Build a message to send in a sysex command."""
return [ord(char) for char in message_string] | 94e798677aa6fa389f48d54aa033e919bb93c724 | 664,161 |
def parse_performance_data(response):
"""Parse metrics response to a map
:param response: response from unispshere REST API
:returns: map with key as metric name and value as dictionary
containing {timestamp: value} for a the timestamps available
"""
metrics_map = {}
for metrics in respo... | 613f3029b4b8011b28dbbbdf35fad7be56906a71 | 664,162 |
import numpy
def rolling(t, A, f):
"""Return the instantaneous rolling angle.
Parameters
----------
t : float
Time.
A : float
Rolling amplitude.
f : float
Frequency.
Returns
-------
phi : float
Rolling angle (in radians).
"""
phi = -A * nu... | 936707504d6c494e520b868cf18da8572c335953 | 664,163 |
from typing import Iterable
def wrap_elementwise(value, wrapper):
"""Apply wrap if str (elementwise if iterable of str)
"""
if isinstance(value, Iterable) and not isinstance(value, str):
return [wrapper.fill(str(v)) for v in value]
else:
return wrapper.fill(str(value)) | 3d0fddcca7c864d3f2d4fee4b95e9574c3aa18d1 | 664,164 |
def catalog(default={}, **kwds):
"""
A {dict} of {list}s
"""
# build a dictionary that maps strings to lists
return dict(schema=list(**kwds), default=default) | 01f8c018c5e74ba7ee8e0568c32d5177f83820e3 | 664,166 |
import math
def sph_kern1(r,h):
"""SPH kernel for 0 < r < h/2"""
return 8/math.pi/h**3*(1-6*(r/h)**2+6*(r/h)**3) | a7155903692021200d09bafe8f9bc707b995d67d | 664,167 |
def flat_node_list(graph):
"""
returns list of all non-compund nodes in a graph, inculding
all the nodes that are inside compound nodes.
"""
node_ids = []
for node in graph:
node_data = graph.node[node]
#print(node_data)
if 'components' in node_data:
internal_... | b8997e9dfb7cc9dd569c609106142df586a56156 | 664,168 |
def calc_total_fuel_for_mass(mass:int) -> int:
"""Calculates the total amount of fuel needed for a given mass, including its needed fuel mass."""
fuel = (mass // 3) - 2
if fuel <= 0:
return 0
return fuel + calc_total_fuel_for_mass(fuel) | fa934c8829321f34416ab27196e953ccbe0de3f4 | 664,170 |
def _plugin_url(name, version):
"""
Given a name and an optional version, return the jenkins plugin url.
If there is no version, grab the latest version of the plugin.
>>> _plugin_url("git", None)
'https://updates.jenkins-ci.org/latest/git.hpi'
>>> _plugin_url("git", "2.3.5")
'https://updat... | 7993dd55234d8a8c07d4426d3c18e12052340b24 | 664,171 |
def transform_seq_to_Hmatrix(sequence):
"""
To transform a sequence to binary matrix of 4xX
:param sequence: sequence data
:return: 2-dimensional numerical array representing sequences
"""
m = []
a = [1 if x == 'A' else 0 for x in sequence]
c = [1 if x == 'C' else 0 for x in sequence]
... | 04c0c6167c9052cf42d7af738b4f34514b1cbfde | 664,172 |
import re
from sys import version
def task_mybinder():
"""Make the mybinder files up to date"""
def action(targets):
for filename in targets:
with open(filename) as f:
content = f.read()
content = re.sub('cytoscape(?P<cmp>[^0-9]*)([0-9\.].*)', rf'cytoscape\g<cm... | 4062808e9889a44b46bff41653187f7868d1f5a4 | 664,173 |
import functools
import builtins
import logging
def requires_ipython(fn):
"""Decorator for methods that can only be run in IPython."""
@functools.wraps(fn)
def run_if_ipython(*args, **kwargs):
"""Invokes `fn` if called from IPython, otherwise just emits a warning."""
if getattr(builtins, '__IPYTHON__',... | f826621ff8a89720c932f1f396b746ae6aef4e64 | 664,174 |
from typing import OrderedDict
def get_linking_log_headers() -> list:
"""
Get linking log headers for creating project master linking log
:return: list of headers for linking log
"""
linking_headers = OrderedDict()
linking_headers['SubjectID'] = 'subject_id'
linking_headers['MedicalRecordN... | c36de71da596b62f64cf4b1bef1684d1ee9ce38d | 664,177 |
import argparse
from typing import Optional
def parse_args() -> argparse.Namespace:
"""Parses the script's arguments."""
def delimited_list(delimiter: str, items: Optional[int] = None):
def _parser(arg: str):
args = arg.split(delimiter)
if items and len(args) != items:
... | 012ec9fd014f57ec5af07d1111a04029382c55ac | 664,178 |
def ErrorMessage(text):
"""Format an error output message
"""
return "\n\n" \
"********************************************************************\n" \
"{}\n" \
"********************************************************************" \
"\n\n".format(text) | de85fb28369b8efa0c33e5cc2c39f0a5f77b131f | 664,179 |
import os
def print_nifti_data( nifti, data_function ):
"""Perform any function on the data part of a NIfTI object (which is a Numpy array), print and return the output.
E.g. print_nifti_data( nifti, np.std ) # to print the standard deviation.
Works with loop_and_print(): E.g. loop_and_print(in... | 0561b87783b895fe9d8ff28ef9f3f0214d3b2558 | 664,180 |
def api_setup_view():
"""Returns function able to setup DRF's view.
Examples
========
`api_setup_view` should be used as normal pytest's fixture::
def test_profile_info_view(api_setup_view):
request = HttpRequest()
view = views.ProfileInfoView()
view = api_s... | 8aeb7a9e7b2d30c8bb5c3547f55fba9defa79aae | 664,181 |
import textwrap
def wrap_text(text, width=90, indent=''):
"""Wrap each line of text to width characters wide with indent.
Args:
text (str): The text to wrap.
width (str): width to wrap to.
indent (str): the indent to prepend to each line.
Returns:
str: A wrapped block of ... | 4cba6a5cfa41a8b21f5f9b4e9fcbbd4889a033eb | 664,182 |
import re
def expand_refs(comment_line):
"""Adds hrefs to markdown links that do not already have them; e.g.
expands [Foo] to [Foo](#Foo) but leaves [Foo](https://foo) alone.
"""
result = comment_line
result = re.sub(r"\[(\S+)\]([^(])", r"[\1](#\1)\2", result)
result = re.sub(r"\[(\S+)\]$", r"... | 3fc84773b12c27079aa96d2ced8bba9cfface969 | 664,183 |
def max_drawdown_value(daily_equity_value, num_to_show=5):
"""Show, by default, 5 worst loss dates and their losses"""
df = daily_equity_value.copy()
df = df.diff()
df = df.dropna()
return df.sort_values(ascending=True)[:num_to_show] | c3f71a00887a63305c043074cef5ce06425398fb | 664,184 |
import torch
def _get_torch_version():
"""Utility function to convert the torch version to a tuple of ints.
Returns:
tuple: The version - a tuple of ints.
"""
v = torch.__version__
v = v.split('+')[0]
v = v.split('.')
v = tuple([int(i) for i in v])
return v | d33fe57364c60e5e510bc92501004261002cd8bb | 664,186 |
def mkBinPacking(w,q):
"""mkBinPacking: convert a cutting stock instance into bin packing format"""
s = []
for j in range(len(w)):
for i in range(q[j]):
s.append(w[j])
return s | 95f25e359c5cdc1b5a0a9d5604fbb077b46309e8 | 664,187 |
import re
def clean_text(raw_text: str):
"""Clean raw text.
Args:
raw_text(str): text.
Returns:
cleaned_text(str): cleaned_text
"""
tokens = raw_text.split()
cleaned_text = '_'.join(tokens)
pattern = re.compile(r'(.+?)')
cleaned_text = pattern.sub('', cleaned_text)
... | 3a74d903a2effa9ab1b881740641119637969532 | 664,189 |
def append_group_info(record, groups):
""" Add new info fields """
record.INFO['IN_GROUP'] = groups
record.INFO['GROUP_ID'] = ''
return record | 50f56a08dbbd22c4862066b945a7b44d7d8a4b6e | 664,190 |
def get_control_variation(campaign):
"""Returns control variation from a given campaign
Args:
campaign (dict): Running campaign
Returns:
variation (dict): Control variation from the campaign, ie having id = 1
"""
for variation in campaign.get("variations"):
if int(variation... | aee9e6474bbb0ab2baa0e3e296ed5bf00c0d0c36 | 664,191 |
def to_lample(cd, features, labels):
"""
convert to Lample format
to run directly
"""
inv_f = {v:k for (k,v) in list(features.items())}
inv_l = {v:k for (k,v) in list(labels.items())}
res = [[['@', 'O']]]
wids = [0]
for sen, clabs in zip(cd.sentences, cd.crowdlabs):
#text_se... | 24c9aacd30ddc3c780f4b5390e953c6c66031f2e | 664,192 |
def get_all_ngrams(words):
"""
Get all n-grams of words
:param words: list of str
:return: ngrams, list of (list of str)
"""
ngrams = []
N = len(words)
for n in range(1, N + 1):
for i in range(0, N - n + 1):
ngrams.append([words[j] for j in range(i, i + n)])
retu... | 979aa2e1bffd50f0f4478b0058ea15a0863f2cec | 664,194 |
def total_hours(hours, days, weeks):
"""Total hours in w weeks + d days + h hours."""
return hours + 24 * (days + 7 * weeks) | 3149069da9bb63bac66901c1c203e7604d4839dc | 664,195 |
def generate_system_id_chain(system, c):
"""
Generates an id for the individuals of the genetic algorithm. Useful for detecting duplicates,
and creating readable ids for individuals.
:param chain: An ensemble
:return: String id
"""
id = ""
component = c
while component is not None:
... | d5c1f418fef1261e0fc4c70a0ceae91775095e18 | 664,196 |
def to_port_num(str_in):
"""
Tries to coerce provided argument `str_in` to a port number integer
value.
Args:
str_in (string): String to coerce to port number.
Returns:
(int) or (None): Integer port number if provided `str_in` is a valid
port number string,... | 7b922b8d809b87a45623ac398773180939ac0b0f | 664,197 |
import optparse
def parse_arguments():
""" Parses the command line arguments to create options object"""
usage = "Usage: %prog [--config <configuration.yaml>] "\
"[--params <params.yaml>] "
parser = optparse.OptionParser(usage=usage)
parser.add_option("-c", "--configuration",
... | 162eb4900f34c50b89a9db6cdea24f2057a9c741 | 664,198 |
def client_count(request):
""" Number of clients to test with """
return request.param | 8fad77ec479f89d9e39cab77d06945751625d96b | 664,199 |
import logging
def get_logger():
"""Configure logging and return a logger object.
Meant to be called once at module load time.
"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.getLogger("boto3").setLevel(logging.ERROR)
logging.getLogger("botocore").setLevel(logging.ER... | 67bcce32fca6a317c3cf278079cf3c83fd76520f | 664,200 |
import ast
def sub(*arguments):
"""
Subtract function.
"""
return ast.Sub(*arguments) | b58e9dedba0964e29e514fd9aa2ae9802b214eb0 | 664,201 |
def contains_ingredients(ing, check_ing):
"""
IMPORTANT: You should NOT use loops or list comprehensions for this question.
Instead, use lambda functions, map, and/or filter.
Take a 2D list of ingredients you have and a list of pancake ingredients.
Return a 2D list where each list only contains ing... | e46be3c1f0b1a91bd40d0764a668ebf07cd47290 | 664,202 |
import os
def get_folder_structure(path):
"""Returns the folder structure from the `path` variable.
The returned object is an iterable. To be compared to
the folder structure post-processing.
"""
return os.walk(path) | e03f61fed0a05837289c43f053c82549604a9777 | 664,203 |
import re
import os
def title_to_filename(path, title):
"""
We build a simple filename from the title - i.e. "These Cats" becomes "these_cats.md". We do
not check for existence, as we may be doing an overwrite deliberately.
"""
name = re.sub(r'[^a-z0-9]','_',title.lower())
return os.path.join... | d15ea6bc46aa5923e298a2a3fa35cead6ee0fa98 | 664,204 |
def convert_site_dm3_table_intensity(sites_df):
"""
Convert MagIC site headers to short/readable
headers for a figure (used by ipmag.sites_extract)
Intensity data only.
Parameters
----------
sites_df : pandas DataFrame
sites information
Returns
---------
int_df : pandas... | 8e130f16d00515e0c29141c66709846f44ccfff4 | 664,205 |
def read_binary(filename):
"""
Write binary data to a file on disk
"""
data = []
# Create file and write to it
f = open(filename, "rb")
byte = f.read(1)
while byte != b"":
data.append(ord(byte))
# Do stuff with byte.
byte = f.read(1)
f.close()
... | 4324a16994bed30f9d4f8ed39108d3ffe0814561 | 664,206 |
def match_emoji(emoji: str, text: str) -> bool:
"""
True if the emoji matches with `text` (case insensitive),
False otherwise.
"""
return emoji.lower().startswith(text.lower()) | b304614614ffb6fab26382ae607b212f917ff6ab | 664,207 |
import math
def _find_utm_crs(lat, lon):
"""Find the UTM CRS based on lat/lon coordinates.
Parameters
----------
lat : float
Decimal latitude.
lon : float
Decimal longitude.
Returns
-------
crs : dict
Corresponding UTM CRS.
"""
utm_zone = (math.floor((... | 7dff30cbfb277d21728c0feadeb0018b6e793462 | 664,208 |
def format_states(states):
"""
Format logging states to prettify logging information
Args:
states: logging states
Returns:
- formated logging states
"""
formated_states = {}
for key, val in states.items():
if isinstance(val, float):
if val < 1e-3:
... | 4612914f26813b9dd4cea527ec54f3d03ec5284f | 664,209 |
def has_two_tds(elem):
"""."""
tr = elem.name == "tr"
td = elem.find_all("td")
has_two = len(td) == 2
return tr and has_two | bab2f0c96e17f4039c2fb4976f022081a6ef9797 | 664,210 |
def insert_one_marriage(df,session):
"""
Given one row of data, insert one marriage to the graph.
"""
# do nothing if `spouse` data is missing
if df['spouse'] == "":
return None
with session.transaction().write() as transaction:
# write the graql query
graql_insert_query... | b56b46060463a272e2be09969da086554c4eeb6c | 664,211 |
def deep_map(f, root):
"""Sibling to |inverse_deep_map|. As :py:func:`map` maps over an iterable,
|deep_map| maps over a structure of nested ``dict``s and ``list``s. Every
object is passed through `f` recursively. That is, first `root` is mapped,
next any object contained in its result, and so on.
... | a4332b5d99bcd5e0771aaaeab9d483ff57ab4b46 | 664,212 |
def all_hkl(n_max=7):
"""Generate all possible hlk triplet"""
all_hkl = []
for l in range(1, n_max): # <-- indice max.
for k in range(l+1):
for h in range(k+1):
all_hkl.append(sorted([h, k, l], reverse=True))
all_hkl = sorted(all_hkl, key=lambda x: sum(i**2 for i i... | d27a9c37eb05c2c7fdbb10db72032aa9fa288ce4 | 664,213 |
def set_gte(left, right):
""":yaql:operator >=
Returns true if right set is subset of left set.
:signature: left >= right
:arg left: left set
:argType left: set
:arg right: right set
:argType right: set
:returnType: boolean
.. code::
yaql> set(0, 1) >= set(0, 1)
t... | 6928d48115906f0e8c56b4f9cbdbd24c52ad6d05 | 664,214 |
from typing import Dict
from typing import Any
import requests
def pinJSONToIPFS(
json_obj: Dict[str, Any], pinata_api_key: str, pinata_secret: str
) -> Dict[str, Any]:
"""
Purpose:
PIN a json obj to IPFS
Args:
json_obj - The json obj
pinata_api_key - pinata api key
pin... | 1219ea374f5e5dd6507d2b2c67e59938ef3cc4bf | 664,215 |
def std_ver_minor_uninst_valid_iativer_possible(request):
"""Return a string that is a correctly constructed IATIver minor version number."""
return request.param | 2ea3eacd0dac3c44d2290ee5620c5d019fa5ea39 | 664,216 |
import os
def check_env(envname, value=None):
"""See if an environment variable is set"""
try:
os.environ[envname]
except KeyError:
return False
if value is None:
return True
elif value in os.environ[envname]:
return True
else:
return False | dfc10caddc7428355cb6ccc52df8910bc7387cdc | 664,217 |
from bs4 import BeautifulSoup
def extract_data_by_class(raw_content, elem, class_name, is_all=False):
"""extract html tags by element and class name"""
parser = "html.parser"
soup = BeautifulSoup(str(raw_content), parser)
if is_all:
return soup.find_all(elem, class_=class_name)
else:
... | 5eac674f0ea6e48bac7d0c52e1c5d137377ecb0f | 664,218 |
def _to_x_constructor(fn):
""" Apply a function `fn` to all elements of lists and tuples, as well
as values in dicts, in a nested set of lists, tuples, and dicts """
def _to_x(args):
if isinstance(args, dict):
return {
key: _to_x(value)
for key, value in a... | 565fe22f648ee9808d8e78d0b96cf7141eb865a7 | 664,219 |
def str2bool(s):
"""
Turn a string s, holding some boolean value
('on', 'off', 'True', 'False', 'yes', 'no' - case insensitive)
into boolean variable. s can also be a boolean. Example:
>>> str2bool('OFF')
False
>>> str2bool('yes')
True
"""
if isinstance(s, str):
true_val... | a8c8dad6c468d5b983e6239b0e0d0e0096bf8ab0 | 664,220 |
def hangman(word, ans, attempt_left):
"""
:param word: str, the word randomly selected from our word bank.
:param ans: str, the result's of player's guess, before guessing
:param attempt_left: int, the guessing attempts left for players, before guessing
:return ans: str, the result's of player's gue... | 553832932a2edf561b327ffb01a0b994f0fe1399 | 664,221 |
import subprocess
import sys
def get_ctime_year(filepath: str) -> str:
"""
Get file creation time and return the year as a stringified integer.
Because git-clone overwrites ctime, we need to retrieve it
using git-log.
"""
# %aI: author date as an YYYY-MM-DDTHH:MM:SS-HH:MM string (git 2.21).
... | 2ff6b2be5995848985bf6f69143e56e5fb15c4d2 | 664,222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.