content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def create_virtual_cdrom_spec(client_factory,
datastore,
controller_key,
file_path,
cdrom_unit_number):
"""Builds spec for the creation of a new Virtual CDROM to the VM."""
config_spec = clien... | 8f62c70c432c368f0f94b3c1dc48f38d75093b07 | 7,270 |
def plot_mean_and_CI(axes, mean, lb, ub, label, freqs, linestyle='-'):
""" Plot mean and confidence boundaries.
Args:
axes: plt.axes
mean: np.ndarray
lb: np.ndarray
ub: np.ndarray
label: string
freqs: list
linestyle: string
Returns: plt.axes
... | 77b7ecaa6dddae474495c0a65efafbf08717584c | 7,273 |
def locked(acquire, release):
"""Decorator taking two methods to acquire/release a lock as argument,
returning a decorator function which will call the inner method after
having called acquire(self) et will call release(self) afterwards.
"""
def decorator(f):
def wrapper(self, *args, **kwarg... | 92f8ae3b36375d14962997436bc1d210510b4cdb | 7,274 |
def check_next_in_request(request):
"""
Проверяет наличие слова 'next' в объекте запроса request методе POST
:param request:
:return:
"""
return True if 'next' in request.POST else False | b70ba54fa32234798b842ffcb24834fdcd95c827 | 7,276 |
def overlap_slices(large_array_shape, small_array_shape, position):
"""
Modified version of `~astropy.nddata.utils.overlap_slices`.
Get slices for the overlapping part of a small and a large array.
Given a certain position of the center of the small array, with
respect to the large array, tuples o... | ef86928b3ef619f209247bb72e2e391d14d541c4 | 7,277 |
import numpy
def rotmat(x, origin=(0, 0, 0), upvector=(0, 0, 1)):
"""
Given a position vector x, find the rotation matrix to r,h,v coordinates.
"""
x = numpy.asarray(x) - numpy.asarray(origin)
nr = x / numpy.sqrt((x * x).sum())
nh = numpy.cross(upvector, nr)
if all(nh == 0.0):
nh =... | 519d7aaa15dd48bb31aed0059c01f365f4e8118b | 7,278 |
def product(data):
"""
Generate the product for the entries specified by the data.
"""
return "tRNA-{aa} ({anticodon})".format(
aa=data["metadata"]["isotype"],
anticodon=data["metadata"]["anticodon"],
) | 5f347cfa1fd7d7030fb1b1a5d2e88eb664c831ae | 7,280 |
def get_zygosity(call):
"""Check if a variant position qualifies as a variant
0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT"""
zygdict = dict([(0, "nocall"), (1, "het"), (2, "nocall"), (3, "hom")])
return zygdict[call] | aff88ed481beeb6406261822eca482430494b6f6 | 7,281 |
import torch
def create_batch(sentences, params, dico):
""" Convert a list of tokenized sentences into a Pytorch batch
args:
sentences: list of sentences
params: attribute params of the loaded model
dico: dictionary
returns:
word_ids: indices of the tokens
lengths... | c08430651ea20f633169187f62f7b22e09bbd17e | 7,283 |
from typing import List
def make_pos_array_and_diff(trials: List[dict]) -> List[dict]:
"""
Parameters
----------
trials : Non-filtered refinement trials
Returns
-------
A list of dictionaries with updated position and difference of neighbours
"""
_trials = trials[:]
for i, c... | ebdb0a63d9399985d11b06ec28d4032a54b22f89 | 7,284 |
def coords_json_to_api_pan(ang_clockwise):
"""converts from robot coordinates to API coordinates."""
return ang_clockwise | 6511b7cf196a171095b184d48281f25f97fc6792 | 7,285 |
def dict_other_json(imagePath, imageData, shapes, fillColor=None, lineColor=None):
"""
:param lineColor: list
:param fillColor: list
:param imageData: str
:param imagePath: str
:return: dict""
"""
# return {"shapes": shapes, "lineColor": lineColor, "fillColor": fillColor, "imageData": im... | 3742664276d70ce5f037ba99994c8c2e61114107 | 7,286 |
def get_ast_field_name(ast):
"""Return the normalized field name for the given AST node."""
replacements = {
# We always rewrite the following field names into their proper underlying counterparts.
'__typename': '@class'
}
base_field_name = ast.name.value
normalized_name = replacemen... | c5cf0acbca963e7dc0d853064a2599b732d6b0d1 | 7,287 |
def olivine(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... | 387ea9413acdf551abe108ba5ba7dda51e162c51 | 7,288 |
from typing import Tuple
import re
import typing
def hex_to_rgb(hex: str, hsl: bool = False) -> Tuple[int, int, int]:
"""Converts a HEX code into RGB or HSL.
Taken from https://stackoverflow.com/a/62083599/7853533
Args:
hex (str): Takes both short as well as long HEX codes.
hsl (bool): C... | 2c912dacfcf6c52c21c94c5d7bb9b9763279245d | 7,290 |
def get_mode_C_array(mode_C):
"""冷房の運転モードを取得する
Args:
mode_C(str): 冷房方式
Returns:
tuple: 冷房の運転モード
"""
# 運転モード(冷房)
if mode_C == '住戸全体を連続的に冷房する方式':
return tuple(["全館連続"] * 12)
else:
return ('居室間歇', '居室間歇', '居室間歇', '居室間歇', '居室間歇', None, None, None, None, None, None,... | 6b9bce2eccab7698ec78ef3b843b17f3c3c9200d | 7,291 |
from datetime import datetime
def get_date():
""" gets current date """
return datetime.now() | dccf420bc6eb216bf76ee153504696ec1c390b5d | 7,292 |
def singular(plural):
"""
Take a plural English word and turn it into singular
Obviously, this doesn't work in general. It know just enough words to
generate XML tag names for list items. For example, if we have an element
called 'tracks' in the response, it will be serialized as a list without
... | 92ab7e074387d943d5593d759a10b3fafa67deca | 7,293 |
def crop_and_revenue_to_df(financial_annual_overview, waste_adjusted_yields, total_sales, vadded_sales, education_rev, tourism_rev, hospitality_rev, grants_rev):
"""Adding yields and sales information to financial overview
Notes:
Adds waste-adjusted yields for crops 1, 2, 3 and 4 with t... | 6be32e6f4ff3ae0ed6434313b8bcc2f44192231b | 7,294 |
def filter_rows_via_column_matching(data, column, index=0):
"""
Filter data, by keeping rows whose particular field index matches the
column criteria
It takes parameters:
data (data in the form of a list of lists)
column (used as the match criteria for a particular field of the data)
and op... | fcd5548677290a34d94c2eb8d5fefcb2bb50f0b4 | 7,295 |
import re
def _normalize_name(name: str) -> str:
"""
Normalizes the given name.
"""
return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name) | b38a90c05b0a6ec5a26db6d0da85bed2ae802cea | 7,296 |
def filter_claims_by_date(claims_data, from_date, to_date):
"""Return claims falling in the specified date range."""
return [
claim for claim in claims_data
if (from_date <= claim.clm_from_dt <= to_date)
] | d1568d0fd52382bdb3f1f02414f591d5f4da3596 | 7,297 |
def unicode2str(content):
"""Convert the unicode element of the content to str recursively."""
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
r... | 30618f0305d28646af36bcff488af971643fd142 | 7,298 |
import sys
def validate_min_python_version(major, minor, error_msg=None, exit_on_fail=True):
"""If python version does not match AT LEAST requested values, will throw non 0 exit code."""
version = sys.version_info
result = False
if version.major > major:
return True
if major == version.maj... | 49f078af83d956b3e099d792b5a364c359991df0 | 7,299 |
import os
import argparse
def get_arg_parser():
"""Allows arguments to be passed into this program through the terminal.
Returns:
argparse.Namespace: Object containing selected options
"""
def dir_path(string):
if os.path.isfile(string):
return string
else:
... | 035bb8df1743aca4ba78c17d60836b9f485e769d | 7,300 |
import os
def current_umask() -> int:
"""Get the current umask which involves having to set it temporarily."""
mask = os.umask(0)
os.umask(mask)
return mask | 8d24ace1eba3746cb4f38f91c127075c0bce6aaf | 7,301 |
import json
def encode_json(struct):
"""Encode a structure as JSON bytes."""
return bytes(json.dumps(struct), "utf-8") | 6724c0a687a98230a32fef81b3a4447c12d164fc | 7,302 |
def categories_to_errors_dict():
"""Categories to error dictionary function maps common error substrings to categories.
The categories are keys in the dictionary and the values are arrays of strings
or arrays of list.
Some error categories, such as User Errors, has many subcategories. Thus,
... | 4b59fc9775d3d5d808ecedee7756dad5d302848a | 7,303 |
import re
def rhyme_analyser(str, rhyme_db):
"""
Rhyme Analyzer - Print out the rhyme scheme of a poem.
Given: A string - like
If you want to smell a rose
You must put it to your nose.
If you want to eat some bread
You must not eat it in bed
Or I will eat your toes.
Output: Rhyme s... | 0fb166c92b2e60d1739638b23a3de5dae18ce26b | 7,305 |
def is_chosen(bbox, area_threshold=None) -> bool:
"""
Calculate area of bounding boxes and return True if area >= threshold
Args:
bbox: (x1, y1, width, heigh)
area_threshold:
Returns:
True/False
"""
are = bbox[2] * bbox[3]
if area_threshold is not None:
if ... | 091fda7a389a74e92703c6eeca05aec413bc65a5 | 7,306 |
def _float(value):
"""Return env var cast as float."""
return float(value) | 254b1e3a542c5a74153cd58d3f43e86dab964028 | 7,308 |
def isjsonclass(class_: type) -> bool:
"""Check if a class is jsonclass.
Args:
class_ (type): The class to check.
Returns:
bool: True if it's a jsonclass, otherwise False.
"""
return hasattr(class_, '__is_jsonclass__') | 3234cf62beb03aa968888dd8ec3b65f4c5f4cab3 | 7,312 |
import math
def mu_from_pdiv(pdiv, nobj=3):
"""
Get population count based on divisions per objective for NSGA-III
"""
h = int(math.factorial(nobj + pdiv - 1) / (math.factorial(pdiv) * math.factorial(nobj - 1)))
mu = int(h + (4 - h % 4))
return mu | b4087bcab34a0fe03c6a1d5c9e2d9fb1f47d79f0 | 7,313 |
def locals_in_putty():
"""Hard-coded information regarding local variables
"""
locals_d = {
# k: index
# v: dict of local properties
0x14007DA84: {
6: {'name': 'v6', 'size': 8, 'type_name': '__int64'},
7: {'name': 'v7', 'size': 8, 'type_name': '__int64'},
... | 52398e84aa324f8f751e2ca50bee9ad33be6eeb5 | 7,315 |
def dvi( redchan, nirchan ):
"""
DVI: Difference Vegetation Index
dvi( redchan, nirchan )
"""
redchan = 1.0*redchan
nirchan = 1.0*nirchan
result = ( nirchan - redchan )
return result | afa5ffffccc3053598cd3597de1efd3dcfc4cd8f | 7,316 |
def needs_min_max_values(mode, buckets):
"""
Returns True, if an encoding mode needs minimum and maximum column values, otherwise False
"""
return not buckets and mode in ['one-hot',
'one-hot-gaussian',
'one-hot-gaussian-fluent',
... | 50ae2b899e5957347061dd59905290506c460093 | 7,317 |
def listed_list(list_list):
"""Return presentable string from given list
"""
return '{} and {}'.format(', '.join(list_list[:-1]), list_list[-1]) if (
len(list_list) > 1) else list_list[0] | da35296196fff56816fe7b0427985ee278238dab | 7,318 |
import re
def remove_plus_signs(_s: str) -> str:
"""Removes plus signs from string"""
return re.sub(pattern=r'\+', repl=r'', string=_s) | 53cf3117221ce82578a20d75e7eb807c2d41b8fc | 7,319 |
def Intersection(S1x, S1y, D1x, D1y, S2x, S2y, D2x, D2y):
"""
Find intersection of 2 line segments
:param S1x: x coordinate of segment 1's start point
:param S1y: y coordinate of segment 1's start point
:param D1x: x coordinate of segment 1's end point
:param D1y: y coordinate of segment 1's end... | 2dba8839ebf24b55fe3c1b7797e53c7e0c3ed72a | 7,321 |
import os
def write_jobfile(cmd, jobname, sbatchpath='./sbatch/',
nodes=1, ppn=1, gpus=0, mem=16, nhours=3):
"""
Create a job file.
Args:
cmd : str, Command to execute.
jobname : str, Name of the job.
sbatchpath : str, Directory to store SBATCH file in.
s... | 0493f480fa42eb5dc8d108c59999d8a9430e4669 | 7,323 |
def collect_nodes(points, highlighted_nodes=[], color='#79FF06', highlighted_color='blue', width=200, highlighted_width=400):
"""
Собирает необходимые нам вершины в нужный формат
Parameters
----------
points : [str, str, ...]
Вершины графа.
highlighted_nodes : [str, str, ...], optional
... | a3a218b5f8c8c25a0f13a4154f12779a84726f9d | 7,324 |
def feature_names_from_extractor_list(feature_extractors):
"""
get a list of feature names from a list of feature extractors
:param feature_extractors: a list of feature extractors
:return: a list of the feature names for each extractor (think first row of .csv file)
"""
feature_names = [feature... | 2f23aa860137e70270e9c7d564df5dacfa1d22a2 | 7,325 |
import io
def read_txt(filename, encoding='utf-8'):
"""Text file reader."""
with io.open(filename, 'r', encoding=encoding) as f:
return f.read() | 2ca0d80bddc49b793e8cbc63c513410154b4d460 | 7,326 |
def get_job_type(name):
"""Returns job type based on its name."""
if 'phase1' in name:
return 'phase1'
elif 'phase2' in name:
return 'phase2'
elif 'dfg' in name:
return 'dfg'
else:
return 'other' | 50db4a7833028b0a0944a4b915d82a8cabf91595 | 7,327 |
def is_resnet(name):
"""
Simply checks if name represents a resnet, by convention, all resnet names start with 'resnet'
:param name:
:return:
"""
name = name.lower()
return name.startswith('resnet') | 6310d849b76a1006c7c2e97405aa9f0ebc53a78b | 7,328 |
import os
import re
import logging
def convert_output_record(data):
"""Covert data record into a list for output csv
"""
output_record = []
# Participant ID
output_record.append(os.path.basename(data['filename']).replace('.eaf', ''))
# Speaker
output_record.append(data['speaker'])
#... | 046fe65ae63e5559e4bccde5817a4c4f238b0467 | 7,329 |
def handle_pmid_25502872(filename):
"""Bergseng, ..., Sollid. Immunogenetics 2015 [PMID 25502872]"""
return None | 25a11d19293c59e4ae636b0b26389dbfd6b74955 | 7,330 |
from typing import Dict
def invert_dictionary(mapping: Dict) -> Dict:
"""Invert the keys and values of a dictionary."""
remap = {v: k for k, v in mapping.items()}
if len(remap) != len(mapping):
raise ValueError("Dictionary cannot be inverted; some values were not unique")
return remap | 911aee48eff3bf0d980e5ad054c77c8a3081e232 | 7,331 |
def store_file(file):
"""Stores the file to specified destination"""
destination = "/".join(["api/test_docs", file.name])
file.save(destination)
return destination | 1118415a1c1b7c2a33ecc539df7bf27dfd783d16 | 7,332 |
def mpl_dict(params):
""""Convert _ to . for easier mpl rcparams grid definition"""
return {k.replace('_', '.'): v for k, v in params.items()} | a8c4ae683205a1412a73f00e6965cb345ec63a3e | 7,333 |
def test_df_keys():
"""List of keys to be used for populating a bucket with DataFrames"""
return {
'avro': ['df.avro'],
'csv': ['df.csv'],
'csv.gz': ['df.csv.gz'],
'csv.zip': ['df.csv.zip'],
'csv.bz2': ['df.csv.bz2'],
'csv.xz': ['df.csv.xz'],
'psv': ['df.p... | 3b008664744fb6abf8960caebe658ecc2f6525af | 7,335 |
def first_existing(d, keys):
"""Returns the value of the first key in keys which exists in d."""
for key in keys:
if key in d:
return d[key]
return None | eb9f34f1f5adb0a8e44127fe777e35ca8d36dc04 | 7,336 |
import os
def resolve_usr_filename(filename):
"""Resolve the filename to an absolute path.
:param filename: The input file name.
"""
full_filename = filename
if os.path.isabs(full_filename) == False:
full_filename = os.path.join(os.path.expanduser("~"),
full_filename)
retu... | e239c80c9e11f79c786557d4de3e1fc51a4f791d | 7,337 |
def get_requirements():
"""Return a list of package requirements from the requirements.txt file."""
with open('requirements.txt') as f:
return f.read().split() | 85efbe71d02ced7c5987f08a56a1a966bff2e1ef | 7,338 |
def integer_to_real_mapper(integers):
"""Define Integer Mapping Function Here(If Needed.)"""
real_numbers = []
range_of_integers = 32767 # each value goes from 0-32767(2 ^ length_of_chromosome)
integer_to_real_number_mapper = 1 / range_of_integers # will produce number between 0-1 when multiplied by ... | 18cc9dc1efe2dd8122d4953a4256cedd5fe234c9 | 7,339 |
import os
def get_feature_normalizer_filename(fold, path, extension='cpickle'):
"""Get normalizer filename
Parameters
----------
fold : int >= 0
evaluation fold number
path : str
normalizer path
extension : str
file extension
(Default value='cpickle')
R... | c2956766f891b6285dfb8b1d5a0a7f36c160351f | 7,340 |
def filter_files(file_path, selected=('bacteria', 'virus')):
"""filter files based on filepath"""
base = file_path.stem
for s in selected:
if s in base:
return True
return False | e666d091eb41a128d39238181b9fef0396432cf8 | 7,341 |
def VerboseCompleter(unused_self, event_object):
"""Completer function that suggests simple verbose settings."""
if '-v' in event_object.line:
return []
else:
return ['-v'] | e536e221f8f3465f72071d969b11b6623359cf58 | 7,342 |
def load_input_into_list():
"""
Takes our input and returns it into a comprehensive list with split terms
:return: The list of lists for our input
:rtype: list
"""
return [line.replace('-', ' ').replace(':', '').split(' ') for line in open("inputs/day2_01.txt", "r").read().splitlines()] | 9d8f1a313712f11249f4612d38ed9831d666287b | 7,343 |
def computeTF(doc_info,freqDict_list):
"""
tf =(frequency of the term in the doc/total number of terms in the doc
:param doc_info:
:param freqDict_list:
:return:
"""
TF_scores =[]
for tempDict in freqDict_list:
id = tempDict['doc_id']
for k in tempDict['freq_dict']:
... | 8a8567a98227226bc54de6c41010c9103d10be47 | 7,344 |
import pathlib
def get_file(file_path):
"""
获取给定目录下的所有文件的绝对路径
:param file_path: 文件目录
:param pattern: 默认返回所有文件,也可以自定义返回文件类型,例如:pattern="*.py"
:return: 文件路径列表
"""
all_file = []
files = pathlib.Path(file_path)
f = files.rglob('*.md')
for file in f:
pure_path = pathlib.Pure... | b3819e7f8d307d5ad8dcc62442817b99b3d134fc | 7,346 |
def gauss_to_tesla(gauss):
"""Converts gauss to tesla"""
return gauss*1e-4 | 4f0239432a3436fd5c6cad4ae9747c8849289f34 | 7,347 |
def createKey(problemData):
"""
Creates the key for a given 'problemData' list of number
of item types.
"""
key = ''
for itData in problemData:
key += str(itData) + ','
# Remove the last comma
return key[:-1] | 420a4e96dc6442ba2ae18f4bca3d8a10f8a19284 | 7,348 |
def lfsr_next_one_seed(seed_iter, min_value_shift):
"""High-quality seeding for LFSR generators.
The LFSR generator components discard a certain number of their lower bits
when generating each output. The significant bits of their state must not
all be zero. We must ensure that when seeding the gen... | 9cc82109ff3f491e6f880bdba2f598344556f92c | 7,351 |
def function_to_dump(hallo,welt,with_default=1):
"""
non class function to be dumped and restored through
create_pickled_dataset and load_pickled_data
"""
return hallo,welt,with_default | 09bd551300d6672c685f3eeedd2e37fe528dfe14 | 7,352 |
def get_hashtag_spans(tokens):
"""
Finds the spans (start, end) of subtokes in a list of tokens
Args:
tokens: list[str]
Returns:
spans: list[tuple[int]]
"""
is_part = ["##" in t for t in tokens]
spans = []
pos_end = -1
for pos_start, t in enumerate(is_part):
if pos_start <= pos_end:
continue
if ... | 2e70466370e1171a2d29636d13c908c2e8b8e30e | 7,353 |
def roundToNearest(number, nearest):
""" Rounds a decimal number to the closest value, nearest, given
Arguments:
number: [float] the number to be rounded
nearest: [float] the number to be rouned to
Returns:
rounded: [float] the rounded number
"""
A = 1/nearest
rounde... | 5f3974611b529e93ae8157182ff8b7dbc100a234 | 7,354 |
import os
def is_directory(filename):
"""Tells if the file is a directory"""
return os.path.isdir(filename) | 0e6d6c8aa9b666ec7d25d1a353e692bcb5220b06 | 7,355 |
def compare_dict_keys(d1, d2):
"""
Returns [things in d1 not in d2, things in d2 not in d1]
"""
return [k for k in d1 if not k in d2], [k for k in d2 if not k in d1] | 4b68c06d1598e325c5baa5ad8eefaa7af1e82d27 | 7,356 |
import os
def icon_path(name):
""" Load an icon from the res/icons folder using the name
without the .png
"""
path = os.path.dirname(os.path.dirname(__file__))
return os.path.join(path, 'res', 'icons', '%s.png' % name) | dd8254d4aae3b930623ec46dc6e262b37f8170ca | 7,358 |
def project_name(settings_dict):
"""Transform the base module name into a nicer project name
>>> project_name({'DF_MODULE_NAME': 'my_project'})
'My Project'
:param settings_dict:
:return:
"""
return " ".join(
[
x.capitalize()
for x in settings_dict["DF_MODU... | 07411942978ad769d25234f8c7286aaddc365470 | 7,359 |
def parse_config_vars(config_vars):
"""Convert string descriptions of config variable assignment into
something that CrossEnvBuilder understands.
:param config_vars: An iterable of strings in the form 'FOO=BAR'
:returns: A dictionary of name:value pairs.
"""
result = {}
for val... | 1bc1b96b6a2b0bf8e42fca0bb4ee9601c883b124 | 7,360 |
def is_power_of_two(x):
# type: (int) -> bool
"""Check if `x` is a power of two:
>>> is_power_of_two(0)
False
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(3)
False
"""
return x > 0 and x & (x-1) == 0 | c657fc5c74dacd2acd7855d99bd277933423b1eb | 7,361 |
def add_malicious_key(entity, verdict):
"""Return the entity with the additional 'Malicious' key if determined as such by ANYRUN
Parameters
----------
entity : dict
File or URL object.
verdict : dict
Task analysis verdict for a detonated file or url.
Returns
-------
dic... | a20ba12ae04d09047f228a26ef6f39e334225cb3 | 7,362 |
def remove(property_name):
"""
Removes the given property.
:param property: The property (or property identifier) to remove
:type property: Host Specific
:return: True if the property was removed
"""
return None | 6f0fd282164d91cf2772ac4155a842a4cb3ccfd2 | 7,363 |
from typing import Counter
def count_terms(terms: list) -> dict:
"""
Count the number of terms
:param terms: term list
:return dict_term: The dictionary containing terms and their numbers
"""
entity_dict = dict(Counter(terms))
print('There are %s entities in total.\n' % entity_dict.__len__... | 77e362894fbbae3d0cec99daea845734d30e8a2d | 7,364 |
def pretty_duration(seconds):
"""Return a pretty duration string
Parameters
----------
seconds : float
Duration in seconds
Examples
--------
>>> pretty_duration(2.1e-6)
'0.00ms'
>>> pretty_duration(2.1e-5)
'0.02ms'
>>> pretty_duration(2.1e-4)
'0.21ms'
>>> pr... | ceec602cb07ab5c27831c4ed9e1cd552c5b9dde8 | 7,365 |
import numpy
def get_buffered_points(points, centroid=None, factor=2.0):
"""
Add buffer to points in a plane. For example, to expand a convex hull
param points: Points we want to buffer
param centroid: Centroid of the points
param factor: Defines scalar product for point vectors
return numpy a... | 08fdc70a867fddda82bc9b1207587db66852d7fb | 7,366 |
def roman(num):
"""
Examples
--------
>>> roman(4)
'IV'
>>> roman(17)
'XVII'
"""
tokens = 'M CM D CD C XC L XL X IX V IV I'.split()
values = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
result = ''
for t, v in zip(tokens, values):
cnt = num//v
res... | e0f51cefd16a098336cd28fb3e35249063c9761c | 7,367 |
def create_url(url, data):
"""
Method which creates new url from base url
:param url: base url
:param data: data to append to base url
:return: new url
"""
return url + "/" + str(data) | b08fdc2c9e7ecef589ac5208905de8934f667f2b | 7,368 |
import ast
def is_side_effecting(node):
"""
This determines whether node is a statement with possibly arbitrary side-effects
"""
node = node.value
return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) | 137eabb0cbb1b92b48ef05e2800c10e8e598ed1b | 7,369 |
def read_wordlist_file(file_name):
"""
Reads a one-word-per-line list of words to accumulate (w,c) counts for. Duplicates
are collapsed via a dictionary.
"""
word_list = {}
f = open(file_name,'r')
lines = f.readlines()
for l in lines:
word = l.strip()
if len(word) > 0:
... | aa304c23431c6c4a462fac21fbf96377dcdcafcf | 7,370 |
import re
def add_locations(string, args):
""" Adds location links to a snippet string """
string = string.replace(' ', ' ')
locs = args[0]
text = args[1]
for loc in locs:
pattern = re.compile(r'(?<!=)\b{0}[a-zA-Z-]*\b'.format(loc['location']), flags=re.I)
for (match) in re.findal... | 0dca0118e1bc3fae7c6ad5a7c7317f11b2bedb68 | 7,371 |
def extract_results(results, mode, limit=50):
"""extract result from json style list returned by download_results:
parameters:
results: json style - list with results
mode: str- "ppa" for questions, "organic" for link of answers
limit: int - max number of items per keyword
Returns list of list... | 64a9a159f5499295c3cb52239b0cdc49c0cd6ecd | 7,372 |
import os
def get_last_version():
"""Get the last version number in guids file if exists.
Returns:
version number.
"""
version_cmake_path = os.path.join(os.getcwd(), "cmake", "firebase_unity_version.cmake")
with open(version_cmake_path, "r") as f:
datafile = f.readlines()
for line in datafil... | 18afd90dcc9e5f473e88ff3e391d0d32e85a1415 | 7,374 |
def getsize(datadescriptor):
"""Get the size of a data descriptor tuple."""
if datadescriptor[0] == 'reg':
size = datadescriptor[1][2]
elif datadescriptor[0] == 'mem':
size = datadescriptor[1][1]
elif datadescriptor[0] == 'heap':
size = datadescriptor[1][2]
elif datadescriptor[0] == 'perp':
size = datade... | feaaa9d0698b58649a55c53ba399a46ba81520b6 | 7,375 |
import random
def crossover(parent1, parent2, d):
"""One point crossover
Args:
parent1 (int, (int, int)[])[]): chromosome of parent1
parent2 (int, (int, int)[])[]): chromosome of parent2
d (int): Total duration, in durks, of song
Returns:
((int, int)[],(int, int)[... | bea05705b758e8e37dc637bec09566fda8978c6b | 7,376 |
def get_j2k_parameters(codestream):
"""Return some of the JPEG 2000 component sample's parameters in `stream`.
.. deprecated:: 1.2
Use :func:`~pydicom.pixel_data_handlers.utils.get_j2k_parameters`
instead
Parameters
----------
codestream : bytes
The JPEG 2000 (ISO/IEC 1544... | 722a84eadb6f381a531d09d3b6279b7775bca1d3 | 7,378 |
def to_lowercase(word_list):
"""Convert all characters to lowercase from list of tokenized word_list
Keyword arguments:
word_list: list of words
"""
lowercase_word_list = [word.lower() for word in word_list]
return lowercase_word_list | 025e3edaa79723f8656d10a8d52fe16a402644ae | 7,379 |
def convert_to_score(label_name, label_dict):
"""Converts the classification into a [0-1] score.
A value of 0 meaning non-toxic and 1 meaning toxic.
"""
if label_name=='non-toxic':
return 1-label_dict[label_name]
else:
return label_dict[label_name] | 608caf76f62a70d09e1592367daeb2ad3ebae248 | 7,380 |
import pandas as pd
import six
def csv2df(csv_string):
"""http://stackoverflow.com/a/22605281"""
return pd.read_csv(six.StringIO(csv_string),index_col=False) | 2aeda7db7f36dac8fcec20e1f09a9299d362dfa6 | 7,382 |
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'):
"""
Helper function to generate a CSV header line depending on
the combination of arguments provided.
"""
if isinstance(header, str): # user-provided header line
header_line = header + newl... | b9a7f32404a432d2662c43f4fe6444241698bf37 | 7,383 |
def filter_labeled_genes(genes):
"""Filter genes which already have a label and return number of labels.
Args:
genes(dict): dictionary of genes {g_name: gene object}
Returns:
dict: dictionary of genes without label {g_name: gene object}
int: number of distinct labels in the set of labele... | 4d50580a07ad6825b4c28e7c91780f1964568056 | 7,384 |
def get_floss_params(str_floss_options, filename):
"""Helper routine to build the list of commandline parameters to pass to Floss."""
# First parameter is the name of the Floss "main" routine.
list_floss_params = ['main']
# Add the options from app.config
list_options = str_floss_options.split(",")... | e637c25d299c8217fef31b85a2610ec46e53d1f3 | 7,385 |
def is_leap_year(year: int) -> bool:
"""Whether or not a given year is a leap year.
If year is divisible by:
+------+-----------------+------+
| 4 | 100 but not 400 | 400 |
+======+=================+======+
| True | False | True |
+------+-----------------+------+
Args:
... | e4cca9a2b9f0475aadc763fed679eee8b5dddc4a | 7,387 |
def borders(district, unit):
"""Check if a unit borders a district."""
if district == []:
return True
neighbour_coords = [(unit.x+i, unit.y+j) for i in [1, 0, -1]
for j in [1, 0, -1] if bool(i) ^ bool(j)]
district_coords = [(d_unit.x, d_unit.y) for d_unit in district]
... | d95bf55b54f0df63980236def80610dcdc6cbfeb | 7,389 |
def get_step_g(step_f, norm_L2, N=1, M=1):
"""Get step_g compatible with step_f (and L) for ADMM, SDMM, GLMM.
"""
# Nominally: minimum step size is step_f * norm_L2
# see Parikh 2013, sect. 4.4.2
#
# BUT: For multiple constraints, need to multiply by M.
# AND: For multiple variables, need to... | 4adec493ff82450ff0546088af86bac2372b862f | 7,390 |
def MakeCircleRange(circle_size, slice_side):
"""factory function that pre computes all circular slices
slices are assumed to be 2*slice_side+1 in length
"""
assert (circle_size - 1) % 2 == 0
slice_collection = {}
full_indices = list(range(0, circle_size))
for centre_index in range(circle_s... | f952b7b110233780164916afcef102364c3b7399 | 7,391 |
def ramp_geometric(phi, A):
""" Weighted geometric mean according to phi. """
return A[0]**(0.5*(1.+phi))*A[1]**(0.5*(1.-phi)) | 0f79e345336f4038e03947b10446031bd9f3e404 | 7,392 |
def rot13(encoded: str) -> str:
"""
>>> rot13("har crefbaar abeznyr crafr dh’ha xvyb-bpgrg rfg étny à 1000 bpgrgf, ha vasbezngvpvra rfg pbainvaph dh’haxvybzèger rfg étny à 1024 zègerf.")
'une personne normale pense qu’un kilo-octet est égal à 1000 octets, un informaticien est convaincu qu’unkilomètre est ég... | 790d260a1cc517c49d3ea6e4c481fba32dca0831 | 7,395 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.