content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_square(positive_int):
"""
Quick function to find if a number is a perfect square root
Parameters
----------
positive_int : int
The number evaluated.
Returns
----------
bool : bool
If true, the number is a perfect square root.
"""
x = positive_int // 2
... | 22c876fad33a02096b5e5ed9f77cb3f21eaa773b | 605,661 |
from typing import List
def get_black_guess_list(
word_list: List[str],
black_list: List[str]) -> List[str]:
"""Hitしなかった文字に対応する推測を返却する
Args:
word_list (List[str]): 単語候補リスト
black_list (List[str]): Hitしなかった文字のリスト
Returns:
List[str]: 抽出した候補リスト
"""
for black i... | f5c6fd050156d69a30815d6f82612736d958febf | 605,665 |
def required_props(props):
"""
Pull names of required props from the props object
Parameters
----------
props: dict
Returns
-------
list
List of prop names (str) that are required for the Component
"""
return [prop_name for prop_name, prop in list(props.items())
... | c2d771d0304e8847d07a7dd8d6f3890d70350738 | 605,669 |
def pact_dir(tmpdir_factory):
"""Temporary directory that will store pacts for the session."""
return tmpdir_factory.mktemp("pacts") | abc4959ceb3e2b29abc5656cc3d56a2dff5bb632 | 605,672 |
def mean(l):
"""Calculate the mean of a list of values."""
l = iter(l)
s0 = 1
try:
s1 = next(l)
except StopIteration:
raise RuntimeError('cannot compute the mean of an empty iterable')
for x in l:
s1 += x
s0 += 1
return s1 / s0 | 686f54dc6617491ef95357f543c54e3b45e7ba36 | 605,673 |
def get_voltage_extremes(voltages):
""" Finds and returns the minimum and maximum voltages measured in the
ECG signal.
:param voltages: List of voltage measurements
:return: Tuple containing min and max voltages (floats)
"""
return min(voltages), max(voltages) | 72766b00c158402a3fcd68d7485532866109a9bc | 605,677 |
def hist(sx):
"""Histogram from list of samples."""
d = dict()
for s in sx:
d[s] = d.get(s,0) + 1
return map(lambda z: float(z)/len(sx), d.values()) | 555b64c3351a3a909c6bb0ea2c9b7ab0e8757710 | 605,678 |
def is_attribute(method, name=None):
"""
Decorator for methods that are attributes.
"""
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method | e737f7b356b22bea07ca20fbe56d92bedcaef8d8 | 605,682 |
import json
def getmeta_ocred(fname, cfg):
""" Get metadata info of fname.
Args:
fname (str): filename from which to get metadata.
cfg (Config): configuration data.
Return:
dict: metadata info corresponding to fname.
Raise:
ValueError: metadata for fname not found.
... | e2ac3b34515e219bf26564572e943e06de852b23 | 605,685 |
def askQuestionBool(prompt):
"""Ask a question, return a boolean corresponding to the answer."""
answer = input("%s [y/N] " % prompt)
return (answer.lower() in ['y', 'yes']) | ff85b21fb626ddf830d34504e579ea2f292ba4a2 | 605,687 |
from datetime import datetime
def timestamp_in_interval(tstamp: datetime, start: datetime, end: datetime) -> bool:
"""
Returns true if tstamp is in the interval [`start`, `end`)
"""
return tstamp >= start and tstamp < end | 8ca8014f91ffb97f80dda7c715d01cbeaa851470 | 605,688 |
def _Backward3a_v_Ps(P, s):
"""Backward equation for region 3a, v=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
v : float
Specific volume [m³/kg]
References
----------
IAPWS, Revised Supple... | ca7eb178ba0293bec3c933e6c1f053a1aca1f014 | 605,692 |
def is_ignored_but_command_mode(view):
"""
Returns `True` if the view wants to be ignored by Vintageous.
Useful for external plugins that don't want Vintageous to be active for
specific views.
.is_ignored_but_command_mode() differs from .is_ignored() in that here
we declare that only keys shou... | 64d18d81e09fbf6633fed4a7e40451a0ee3b325e | 605,693 |
def gen_oo_textgrid_str(begin_t, end_t, duration, transcript, speaker_name)->str:
"""Creates a TextGrid file in oo-format with only one entry as the transcript
with begins and ends at begin_t and end_t, respectively.
Args:
begin_t (float): beginning time
end_t (float): end time
tran... | 2a97b031bda4035671c5129f33c746b9e2f1049d | 605,695 |
def _get_sm_endpoint(client, **kwargs):
"""Get an endpoint for smapi using the provided keystone client."""
return client.auth_ref.service_catalog.url_for(
service_type=kwargs.get('service_name') or 'smapi',
endpoint_type=kwargs.get('endpoint_type') or 'public',
region_name=kwargs.get('o... | 2517ed263dc5db5332e969c5b9e5052989687fe2 | 605,696 |
def normalise_between_2_values(arraylike, min_value, max_value, invert=False):
"""Normalises an array of data between two desired values.
Any values below min_value will be converted to 0.
Any values above max_value will be converted to 1.
Optionally, the normalised array can be inverted, so that the o... | fd0477fd3d34213e13f0f5ec1184543bb1055814 | 605,697 |
def single_ped_posteriors_strs(num_variables=4, val_set=("0", "1")):
"""
@Params
num_variables = number of ped locations
@Returns
list of strings. Strings have the format: 'o_{i}={val}', where val is in val_set
"""
res = []
for i in range(num_variables):
for flag in val_set:... | 1583781c6d8ae759bb8f745690f544d000a6296f | 605,698 |
def mangle_sheet_name(s: str) -> str:
"""Return a string suitable for a sheet name in Excel/Libre Office.
:param s: sheet name
:return: string which should be suitable for sheet names
"""
replacements = {
':': '',
'[': '(',
']': ')',
'*': '',
'?': '',
... | 742728e243c0bb9e9ed0d2af1c5224c20a544f25 | 605,700 |
def dragon(n):
"""Returns a list of 0s and 1s representing the order n dragon curve."""
if n <= 1:
return [1]
prev = dragon(n-1)
prev_s = prev[:]
mid = len(prev_s) // 2
prev_s[mid] = 1-prev_s[mid]
return prev + [1] + prev_s | ff23d1cc825e2298f32a7b6a8634a7ea1df76bb6 | 605,705 |
from typing import Tuple
import ast
def _h5attr2tuple(attr: str) -> Tuple[str, ...]:
"""Convert an HDF5 attribute to a list of strings"""
if not attr or attr == "tuple()":
return tuple()
return ast.literal_eval(attr) | 99685fa982d8c32087ffe04d365a87cd5111e864 | 605,706 |
def getNorm(name, p=None):
"""Get an instance of a fuzzy norm with given name.
Normally looks into the fuzzy.norm package for a suitable class.
"""
m = __import__("fuzzy.norm."+name, fromlist=[name])
c = m.__dict__[name]
if p is None:
return c()
else:
return c(p) | eee640d29792f950ac959676241be8f7bf134bd0 | 605,708 |
def seed_cost(x0, u0, Q, R, Q_N, param):
""" Compute cost
Input: trajectories x0 and u0, penalty matrices Q, R, Q_N, parameter structure param
Output: cost J
"""
J = 0
N = len(u0)
for k in range(N):
J = J + (x0[:, k]-param.h_r).T @ Q @ (x0[:, k]-param.h_r)\
+ (u0[:, k]- p... | b66cf954be54c73cc94c469f13ca31ad7b420456 | 605,710 |
from typing import Dict
import re
def get_dependencies_default(r_content, schema_name) -> Dict[str, str]:
"""Return a dictionary (script_name -> table_name) for tables under the given schema_name that are used in r_content.
By default, the tables used in the R script must be referred to in the <schema>.<table... | 1cfd9836dd781e3f7ac3c5213e2f2e2788723c97 | 605,713 |
def beta_type(strings: str) -> tuple:
"""An argparse type function that takes a string and returns
a two part tuple for a low and high beta for an optimizer
Args:
strings (str): a comma separated string of numbers
Returns:
tuple: a tuple of floats
"""
mapped_beta = map(float, s... | 52b5396ec093c38988bc93d170dce09aa22c82f9 | 605,715 |
from typing import List
import pathlib
def all_files_exist(files: List[str]) -> bool:
"""Confirms files in list exist"""
return all([pathlib.Path(file).exists() for file in files]) if files else False | 199028de312056707d81d1a055521557f4671b64 | 605,716 |
def str_is_int(s, signed=True):
""" Check if a given string represents a (signed) integer.
Args:
s: str
Input string.
signed: bool
Check if string represents a signed integer (default) or unsigned.
Returns:
res: bool
... | cc929fac59e2cff28cb095235f765ed3d173f9c5 | 605,717 |
import socket
def get_src(dest):
"""
Attempts to learn the source IP from the outbound interface used to reach the provided
destination
:param dest: destination address/ip
:return: local ip
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.connect((dest, 1)... | 2dcf711a3bc14a5d99490c85da94d09a8b099588 | 605,718 |
def get_uninvoiced_hours(entries, billable=None):
"""Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
"""
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
... | 50d03c61d6897a8033c7e78163210102a1f901f0 | 605,719 |
def get_lw_grism_tso_intermeidate_aperture(aperture):
"""Grism time series observations use an intermediate aperture in
order to place the undispersed target at the correct location such
that, once the grism is in the beam, the trace lands at row 34 on
the detector. In the APT pointing file, the request... | a5b3cd25488c12082f62c0788b0bf88cb0e35ef2 | 605,721 |
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity [ms]."""
return 0.5 * mass * velocity ** 2 | 3aa2fe5a2153367f1e3f41c746b4d52f0f44e8c6 | 605,725 |
import math
def getTriangleVertices(latitude, longitude, heading, rangeAngle):
"""Return list of vertices of the isocelees triangle given lat/long as one vertex
and heading/rangeAngle specifying the angle to the other vertices.
Args:
latitude (float): latitude of central vertex
longitu... | dfb3814e72aafc2c5c6db893c7963cf165846022 | 605,726 |
def get_worksheet_name(worksheet):
"""
Get the name of a worksheet
args:
worksheet (): Worksheet
returns:
name (str): Name of the worksheet
"""
return worksheet.name | 8fca1a2f0f01b8e8e1d8a1e73cf106fa083253d3 | 605,729 |
import math
def get_age_decay(age):
"""
Calc Gauss decay factor - based on elastic search decay function
:param age: age in hours
:return: decay factor
"""
SCALE = 7 # The distance from origin at which the computed factor will equal decay parameter
DECAY = 0.5 # Defines the score at scale compared to ... | d3bfa6d7498d57c0c6f640c2cd0203f19b375da4 | 605,733 |
def not_a_long_word(word, wordlist):
"""Returns True if word is not part of wordlist or less than 4 letters.
Returns False if word is part of wordlist and longer than 3 letters."""
if word in wordlist and len(word) > 3:
return False
else:
return True | d3c00857326d0588eaa2503dfa85f1b4ffbf963c | 605,735 |
def dict_to_list(entries, nrows, ncols):
"""
Given a dictionary of coordinate tuples, return the list given by
reading off the nrows\*ncols matrix in row order.
EXAMPLES::
sage: from sage.matrix.matrix_space import dict_to_list
sage: d = {}
sage: d[(0,0)] = 1
sage: d[(1... | 0bcf770dbb5c18e86732dbfd87222f0784c2ce3b | 605,736 |
import yaml
import logging
def load_manifest_metadata(metadata_file, metadata_str):
"""
Loads the manifest metadata from a file and raw string; if multiple value
are provied for the same key, the raw string takes precedence
Parameters
----------
metadata_file: str
path to a YAML metad... | 9ad960caafe33231d60aaa63bdf7826c167d2703 | 605,737 |
def hash_combine_boost(seed, val):
"""Combine seed with hash value (after Boost library)
"""
return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2)) | a6945481f2fd32ad4a011a2f9168e3a5ca2d0ea0 | 605,740 |
def count_ranges(a):
"""
Assumes binary array of 1 and 0 as input. Calculate longest ranges of 1's.
:param a: array with binary values
:return: [end_pos, length] of ranges in array
"""
ranges = []
count = 0
for i, v in enumerate(a):
if v == 1: # same as previous value
... | 3a5a7fbcff488796510204e7ea0860c37fe0fe62 | 605,742 |
def build_env_list(obj, env):
"""Build env list for loaders to iterate.
Arguments:
obj {LazySettings} -- A Dynaconf settings instance
env {str} -- The current env to be loaded
Returns:
[str] -- A list of string names of the envs to load.
"""
# add the [default] env
env_... | 799dcc60050f1237f9b3505100813c6abfb11149 | 605,744 |
def wrap(data):
"""Wrap the data if an array if it is ont a list of tuple.
:param data: data to wrap
:returns: wrapped data
"""
return data if type(data) in [list, tuple] else [data] | 648cf51800df420f8a92e4e23c2ba4cae92669c7 | 605,747 |
def ReadFile(filename):
"""Read a file in one step.
Args:
filename: Filename to read.
Returns:
String containing complete file.
"""
fh = open(filename, 'rb')
data = fh.read()
fh.close()
return data | db53c3668e78e22336dd6c009c7056aba44453ba | 605,753 |
def ensemble_vote(int_img, classifiers, alpha):
"""
Strong classifier: classifies given integral image (numpy array) using given classifiers,
i.e. if the sum of all classifier votes is greater 0, image is classified
positively (1) else negatively (0). The threshold is 0, because votes can be
+1 or ... | 1bda42abf8332f9a37f89ea1a2dee72bdcb371a0 | 605,758 |
def force_log_rollover(logger):
"""
This will access the handler that is configured as a RotatingFileHandler and force a rollover.
:param logger: logger that you are using to write logs
:return boolean: True if successful else false
"""
rolled_over = False
for handle in logger.root.handler... | 928d32f11237a540c48d7ed6d7de2732279284b8 | 605,765 |
def width_and_height_of_pixel_map(pixel_map):
"""Returns the resolution of the pixel map as two integers being width, height."""
assert pixel_map.ndim == 3 and pixel_map.shape[2] == 2
height, width = pixel_map.shape[:2]
return width, height | fc786284884eca235d84928fa255aa7844ea336d | 605,767 |
from typing import Type
from typing import Any
from typing import Tuple
import warnings
import inspect
def get_methods(cls: Type[Any]) -> list[Tuple[str, Any]]:
"""Return a list of tuples of methods for the given class in alphabetical order.
Args:
cls: The class to retrieve the methods of.
Retur... | 02376ffe751ffe1b619f48165fd5bdb21a5566fa | 605,768 |
def mock_ingest_vcf(*args, **kwargs):
"""
Mock for StructuralVariantBuilder.ingest_vcf() for SV VCF ingestion.
"""
return [1, 0] | cd39bbce7b01ad7914713c421b396aaa823feb80 | 605,773 |
def set_recursive(d, names, v):
""" Recursively set dictionary keys so that final leaf is ``v``
The ``names`` argument should be a list of keys from top level to bottom.
Example::
>>> d = {}
>>> set_recursive(d, ['foo', 'bar', 'baz'], 12)
>>> d
{u'foo': {u'bar': {u'baz': 1... | 2392d035120e0c7ce2e62e3512965497fa30d328 | 605,774 |
def generate_edge_key(s: str, edge_label: str, o: str) -> str:
"""
Generates an edge key based on a given subject, edge_label and object.
Parameters
----------
s: str
Subject
edge_label: str
Edge label
o: str
Object
Returns
-------
str
Edge key a... | a1fb212a865b3b25e4d88957b67835a1ba54a35d | 605,775 |
def pad_dict(char_dict, n_pad):
"""
Pad list of dictionary with empty character of size n_pad
(Pad half before and half after the list)
"""
n_pad_2 = int((n_pad - 1)/2)
pad = [{'char': ' ', 'type': 'p', 'target': True}]
char_dict_pad = (pad * n_pad_2) + char_dict + (pad * n_pad_2)
return... | 9f8dfdcfdd4825f3d169cd7ac7b6fb014174c7f9 | 605,776 |
def getCisTrans(df):
"""Calcualtes percentage of cis and trans chromosomal reads"""
cis = (
df.loc[df[0] == "cis", 1].values[0]
/ df.loc[df[0] == "total_nodups", 1].values[0]
)
trans = (
df.loc[df[0] == "trans", 1].values[0]
/ df.loc[df[0] == "total_nodups", 1].values[0]
... | 031d45a63ff4e803344ab5cfafcf46bff9d8176a | 605,783 |
def convert_str_to_bool(item):
"""Converts a boolean string to a boolean value"""
if isinstance(item, str):
return item.lower() == "true"
return False | 9382451d2751d059339298a4e2c9026c3359037b | 605,785 |
def get_alt_genotype(ref, alt1, alt2=None):
"""For a given reference allele, and two alternates, return the appropriate
ALT and GT (genotype) fields for to be written to the VCF
Args:
ref (str): reference allele
alt1 (str): first alternate allele
alt2 (str): second alternate allele
... | 29de04ecf21d2c27dd93a7290751ba5955fb6d4c | 605,788 |
def _any_function(value):
"""Does a value or nested value starts with 'function'?"""
if isinstance(value, str) and value.lstrip().startswith("function"):
return True
elif isinstance(value, list):
for nested_value in value:
if _any_function(nested_value):
return Tr... | de1d6d6c15fb401174bb915454f2d52889bf8f93 | 605,789 |
def pe6(n=100):
"""
s1 = n*(n+1)/2
s2 = n*(n+1)*(2*n+1)/6
s1*s1 - s2
= n*(n+1)*(n*(n+1)/4 - (2*n+1)/6)
= n*(n+1)*(3*n*(n+1) - 2*(2*n+1))/12
= n*(n+1)*(3*n*n - n - 2)/12
= n*(n+1)*(n-1)*(3*n+2)/12
>>> pe6()
25164150
"""
return(n * (n + 1) * (n - 1) * (3 * ... | ef4f61670e48cebe04f5120506c1b7b96ba6fac4 | 605,793 |
def has_string_in_path(path, has):
"""
Checks if the path has the given string.
Parameters
----------
path: str
Forward slash separated string.
has: str
String to check in path.
Returns
-------
bool: bool
True or False.
"""
return bool(set(has.split(... | b85dfc3118ab553dc35f38c35d01e1020c794530 | 605,795 |
def rst_section(input: str):
"""Pretty simple reST section string
"""
return '=' * len(input) * 2 | a389d029c0a3796a3bdda56d74c4586021c60bc5 | 605,799 |
def MakePosterior(high, dataset, constructor):
"""Makes and updates a Suite.
high: upper bound on the range of hypotheses
dataset: observed data to use for the update
constructor: function that makes a new suite
Returns: posterior Suite
"""
hypos = range(1, high+1)
suite = constructor(... | 370271c05d3d422a7b28dd478a5c7806873fe429 | 605,807 |
import math
def calculate_crop_for_angle(image, angle):
"""
Calculates the pixels in vertical and horizontal direction which become invalid, i.e.,
not completely filled with image.
:param image: input image
:param angle: rotation angle
:type image: numpy.ndarray
:type angle: float
:re... | 39bbc1200daddfda0a77c5b0d989f5fff9157435 | 605,812 |
import json
def error_handle(status,
developer_message, user_message,
error_code=-1, more_info=""):
"""Return error handler json
:param status: HTTP status code
:type status: int
:param developer_message: message for developer
:type developer_message: str
:par... | 8306ab7b8c73c1adb20ce4049f0af4870915bf25 | 605,813 |
def num_chars(word):
"""
Return the length of the provided word
"""
return len(word) | d44ace022bbe612bc11437fecae83df222fc5078 | 605,814 |
def convert_single_value_to_tuple(value):
"""This function converts a single value of nearly any type into a tuple.
.. versionchanged:: 3.2.0
The function has been aesthetically updated to be more PEP8 compliant.
.. versionadded:: 2.3.0
:param value: The value to convert into a tuple
"""
... | e3ee113aedf30cd049a49b9aaf726e5b3c975867 | 605,815 |
def rgb2hex(r, g, b, a=None):
"""
Transform RGB color into hexadecimal format
Parameters
----------
r : float
Red component (0-1)
g : float
Green component (0-1)
b : float
Blue component (0-1)
a : float, optional (default: None)
Alpha channel, will be ign... | 806f919c76845612101059ef98a5dc4a905abd52 | 605,821 |
import math
def ceil(theNumber):
"""Returns math.ceil(theNumber)."""
return math.ceil(theNumber) | c90bf9c0b29e7d21cd1f9d9f3d7b751aade3a597 | 605,825 |
def _ExtractPatternsFromFiletypeTriggerDict( triggerDict ):
"""Returns a copy of the dictionary with the _sre.SRE_Pattern instances in
each set value replaced with the pattern strings. Needed for equality test of
two filetype trigger dictionaries."""
copy = triggerDict.copy()
for key, values in triggerDict.it... | 788b37902b5b96b295aa0cc38953a361c5804e0f | 605,828 |
def truncate_string_from_end(string: str, max_len: int) -> str:
"""If the string len is below the max_len, the function returns the same string.
If the string is above the max len, the function returns only the last max_len characters plus '...' at the beginning."""
if len(string) <= max_len:
return string
return... | e7b8193ee9881eb8c00d48205dd8c8a88790d3ee | 605,832 |
def slices_full_ids_from_patients(patients):
""" Extract full ids of cine-MRI slices that belong to specified list of patients
"""
slices_full_ids = []
for patient in patients:
slices_full_ids.extend([slice.full_id for slice in patient.cinemri_slices])
return slices_full_ids | 7c433e89ad01b117730af0f70436dfb1c41830fe | 605,835 |
def load_env(context):
"""Get the current environment for the running Lambda function.
Parses the invoked_function_arn from the given context object to get
the name of the currently running alias (either production or staging)
and the name of the function.
Example:
arn:aws:lambda:aws-regio... | 394fc46324018ddd0816a06d18c4f98f9ce35b5a | 605,836 |
import asyncio
async def _gather_with_concurrency(n, *tasks):
"""Limits open files to avoid 'too many open files' error
Parameters
------
n (int): number of files to open at once
Returns
------
awaitable: gathered coroutines that need to awaited
Notes
------
http... | e547f4ade2ff4d7256aa5e7d02a58c8cd4b17f3c | 605,840 |
def stencil_converter(stencil: list, ndims: int) -> list:
"""
Takes in the flattend stencil list and returns it
in forms of tuples
:param stencil: flattend list of rel. coord. Ex: [0, 1, 0, 2], ndims = 2
:return: list with tuples. Ex: [(0, 1), (0, 2)]
"""
converted_stencil = []
for i in ... | 54885e5b8a2b2939b3881b8482059e395eb230f5 | 605,841 |
from operator import sub
def get_aspect(ax):
"""Compute the aspect-ratio of matplotlib Axis `ax`."""
figW, figH = ax.get_figure().get_size_inches() # Total figure size
_, _, w, h = ax.get_position().bounds # Axis size on figure
disp_ratio = (figH * h) / (figW * w) # Ratio of display units
data_ratio = sub(*ax... | 4de58dc47ddc66675a6dd99023223939b1b6b5f7 | 605,842 |
def get_p7_seq(x):
"""
Return the sequence of P7: TruSeq, Nextera, smallRNA
"""
p7 = {
'truseq': ['AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC', 6, 'ATCTCGTATGCCGTCTTCTGCTTG'],
'nextera': ['CTGTCTCTTATACACATCTCCGAGCCCACGAGAC', 8, 'ATCTCGTATGCCGTCTTCTGCTTG'],
'smallrna': [],
}
retu... | 700cad512b0019f37a66cb33665a8d994ebd63e9 | 605,843 |
def local_landmarkness_track(traversed_nodes, nodes_gdf, buildings_gdf):
"""
It computes the accumulated local landmarkness of a route (a sequence of traversed nodes). This is designed for computing the local landmarkness of a GPS trajectory.
This function should be executed per row by means of the df.apply... | 9d58c0c3d8b394d69ceac0c43760e6d18db0d9d7 | 605,844 |
def _is_x_first_dim(dim_order):
"""Determine whether x is the first dimension based on the value of dim_order."""
if dim_order is None:
dim_order = 'yx'
return dim_order == 'xy' | 0e02f783b973246cca47db81a204a26682d9d7b2 | 605,846 |
def direction_string_cleaner(record):
"""
Pandas Helper Function to clean a record in the "direction" column.
Args:
record (str): Strings in "direction" column.
Returns:
str: Cleaned string.
"""
if "eastbound" in str(record):
return "eastbound"
elif "northbound" in ... | ea2b6a15eecafb429ce8174520a9b2b0ad2edaaa | 605,850 |
def greenshieldFlow(speed, capacity, free_flow_speed):
"""
Returns the flow of a link following the Fundamental Diagram (Greenshield's Model).
Parameters
----------
speed: miles/hr or km/hr
capacity: link's capacity in veh/hr
free_flow_speed: link's free flow speed in miles/hr or km/hr
... | 2d753d367f7c37d3751327b5fcbb8a79aa54354d | 605,857 |
def mathEsc(val):
"""Escape $ signs to `<span>$</span>`.
To prevent them from being interpreted as math in a Jupyter notebook
in cases where you need them literally.
"""
return "" if val is None else (str(val).replace("$", "<span>$</span>")) | 748125bd733ae586abd8e196ad3444201d7e2b58 | 605,858 |
from typing import List
def calc_share(total: int, no: int, yes: int, maybe: int, bad: int) -> List[float]:
"""Calculate the share of each category on the total count."""
no_share = no / total
yes_share = yes / total
maybe_share = maybe / total
bad_share = bad / total
return [no_share, yes_sh... | b9b18124f9c82fede43032a1776e57bc16a403fb | 605,862 |
def dict_depth(dictionary):
"""Get depth of nested dict
"""
if isinstance(dictionary, dict):
return 1 + (max(map(dict_depth, dictionary.values())) if dictionary else 0)
return 0 | 2e40aab755ee174c8e840db6c7a5623034a6746b | 605,863 |
import re
def has_added(message):
"""
Function to check if a message contains any word that indicates an addition of lines of code.
"""
if (re.search(
r"add(?:ed)*|implement(?:ed)*|introduce(?:d)*|improve(?:ment|ments)*",
message.lower())):
return True
return False | 279ca80deafd153e6209c78b0607b8c4f02f546b | 605,864 |
from typing import Any
def indent(lines: Any, spaces: int=2) -> str:
"""Reformat input lines with spaces indent before each line
Args:
lines: lines to be added indents before. If not str, lines = str(lines)
spaces: spaces in each indent. Default 2.
Returns:
Lines with indent
... | e061c205b26c84b84f4f784b82f738849b025f35 | 605,869 |
def replace_list_batch_string(string, list_string, new):
"""
Batch replace value in string.
Args:
string: The original string。
e.g.'md5:%{md5("123")}; timestamp:%{timestamp()}'
list_string: ["%{md5("123")}", '"%{md5(\"123\")}"', '%{md5("123")}']
new: 202cb962ac59075b964b... | d51d8ec886cec92175e3c89ea79831f0587109fe | 605,870 |
def normalize(ys, amp=1.0):
"""Normalizes a wave array so the maximum amplitude is +amp or -amp.
ys: wave array
amp: max amplitude (pos or neg) in result
returns: wave array
"""
high, low = abs(max(ys)), abs(min(ys))
return amp * ys / max(high, low) | c247cf22438e32b98cc883a17932aecd5ddeaca1 | 605,872 |
import six
def py_version_data(py2, py3):
"""
Return the related data for the given python version.
This is mostly used for comparing randomly generated
values as random produces inconsistent results
between python 2 and 3.
"""
if six.PY2:
return py2
return py3 | 161f5d5a787d2b879774f3e852c31d2ab29c83ea | 605,876 |
def line_segment_intersection(a, b, c, d):
"""Checks if two lines intersect.
Args:
a (list): Point 1 of Line 1
b (list): Point 2 of Line 1
c (list): Point 1 of Line 2
d (list): Point 2 of Line 2
Returns:
(bool) True if there is an intersection, otherwise False.
... | b09b64a8cee9fe81f06dcadf52a8c4d80e488093 | 605,878 |
def add_classes(value, arg="form-control"):
"""
Add provided classes to form field
:param value: form field
:param arg: string of classes seperated by ' '
:return: edited field
"""
css_classes = value.field.widget.attrs.get('class', '')
# check if class is set or empty and split its cont... | e8b5b5abb702c3a6c7817e174103faab87f5caab | 605,881 |
def nodes_with_m_nbrs(G, m):
"""
Returns all nodes in graph G that have m neighbors.
"""
nodes = set()
# Iterate over all nodes in G
for n in G.nodes():
# Check if the number of neighbors of n matches m
if len(G.neighbors(n)) == m:
# Add the node n ... | 494ddae10a743c516d303f0c186b4fecf19f5ba0 | 605,882 |
def __api_authorized_error(error):
"""Return error api authorization."""
return {'message': str(error)}, getattr(error, 'code', 401) | 499e293b8f47bb5396ff287dd15fa353a19e3d7b | 605,883 |
import math
def distance(position1, position2):
"""finds the distance between two atoms"""
return math.sqrt(math.pow(position1[0] - position2[0], 2) +
math.pow(position1[1] - position2[1], 2) +
math.pow(position1[2] - position2[2], 2)) | a3a4c69edddaa3e949c41fbcf26a278a568f4d79 | 605,885 |
def get_places(filenames):
"""
Gets places of tif imagery from filenames in list. Assumes names are of form
<country>_<img type>_<place name>.tif|_<date info>.tif
"""
places = []
for f in filenames:
place = f.split('_')[2]
if place.find('tif') != -1: place = place[:-1]
pl... | 1e80386c92e5830522196cde43ccf8f71c4f96ea | 605,886 |
def line_to_long(line, line_index):
"""Check if line is not to long."""
length = len(line)
if length >= 110:
return {'range': {'start': {'line': line_index,
'character': 0},
'end': {'line': line_index,
'c... | 857ae101db1d5438495657800a1331ecee9987d9 | 605,888 |
def get_users(passwd: str) -> dict:
"""Split password output by newline,
extract user and name (1st and 5th columns),
strip trailing commas from name,
replace multiple commas in name with a single space
return dict of keys = user, values = name.
"""
splitlines = passwd.splitlines(Fal... | f2b6fbf2dc6c23981f0dc8bdd45e3463878ae8f0 | 605,889 |
def get_nth_bit_from_right(binary, n):
"""
:param binary: value to extract a bit from
:param n: nth bit to extract (0 indexed)
:return: nth bit from right
"""
return (binary & (1 << n)) >> n | c4c6047eecff58a0ae452fdf79ff6756273f02b2 | 605,890 |
def VerifyLineLength(filename, lines, max_length):
"""Checks to make sure the file has no lines with lines exceeding the length
limit.
Args:
filename: the file under consideration as string
lines: contents of the file as string array
max_length: maximum acceptable line length as number
Returns:
... | 914046f7c9bfb3d11c0c3736c00f7049cdeb9e56 | 605,893 |
def melt_bond_length(p, coeffs):
"""
Return the bond length (in m) given
a polynomial expansion in pressure.
"""
r = 0.0000000001 * (coeffs[0] + p * coeffs[1] + p**2 * coeffs[2])
return r | 716752ecb6bba5262ac4a1bf3f996b5054b900ab | 605,896 |
from typing import List
from typing import Tuple
def list_window(sent: List, center: int, window: Tuple[int, int], oob_item=None) -> List:
"""Get a window of tokens within a sentence.
Parameters
----------
sent : List
A list of tokens.
center : int
The index acting as center of th... | 2a3d735a0c6289c73e3b531b57493f8b9bd4fb5f | 605,901 |
def tags(s):
"""Split '<foo><bar><baz>' into ['foo', 'bar', 'baz']."""
return ' '.join(s[1:-1].split('><')) | 7620995064b0b82829b2151118bed927de90cbb9 | 605,903 |
def generate_TFIDF(corpus, corpus_dict, tf_dict, idf_dict):
"""
Function to generate TF-IDF for all the words.
:param corpus: Corpus of words in the queries.
:param corpus_dict: Mapping of query number and its corpus.
:param tf_dict: Term Frequency Mapping.
:param idf_dict: Inverse Document Freq... | 7e0221feeeb2b44a27f9ba5022df7de9078498f8 | 605,907 |
def dup_valuate(p, val):
"""
evaluate the polynomial ``p`` in the point ``val``
"""
r = 0
for c in p:
r = r*val + c
return r | defed8f5916661fc894b20a74427767c88c9f7b9 | 605,913 |
def get_team_cost(team):
"""
Gets the team"s cost.
"""
cost = 0
for player in team:
cost += player["seasons"][0]["now_cost"]
return round(cost, 2) | eb95561ab19c03495ffceeaa1e28ed24795312bf | 605,916 |
def make_field(name: str, value: str) -> str:
"""
Return an ADIF field/value, like "<adif_ver:5>value"
"""
return f"<{name}:{len(value)}>{value}" | cb8461e43c61c792f7b3b57bf1fd1c4f3156ee1b | 605,917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.