content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def soft_equals(a, b):
"""Implements the '==' operator, which does type JS-style coertion."""
if isinstance(a, str) or isinstance(b, str):
return str(a) == str(b)
if isinstance(a, bool) or isinstance(b, bool):
return bool(a) is bool(b)
return a == b | 2813936f29090c2ba7d61f1f7f337773effb2160 | 109,172 |
def resource_to_type_name(resource):
"""Creates a type/name format from a resource dbo.
Args:
resource (object): the resource to get the the type_name
Returns:
str: type_name of the resource
"""
return resource.type_name | a837aac94a493a2201f470670862eb7b22e70941 | 109,173 |
def addColorbar(ax, mappable, norm, cbarLabel=None):
"""
Quick utility to add a colorbar to an axes object
Parameters
----------
mappable: iterable
Collection of meshes, patches, or values that are used to construct
the colorbar.
norm: None or :class:`matplotlib.colors.Normalize... | b53905f7e213e254442250ab8288810ad2d70fac | 109,174 |
def getDataType(p_type, p_size):
"""Given the input type and size, returns the corresponding
Python character for that data type"""
# How many bits in a single value?
if p_type == 'float':
if p_size == 32:
return 'f'
elif p_size == 64:
return 'd'
else: #... | 3fad77e48c7a40ff908b5066cd353a83649425b6 | 109,176 |
import hashlib
def hashDictionary(dictionary):
"""
Hash a dictionary. Sort the dictionary according
to the keys beforehand.
"""
chain = ""
for key,value in sorted(dictionary.items()):
chain += key+","+value+";"
return hashlib.md5(chain.encode()).hexdigest() | 20c078737e836a4a1002f8948f344ddadc6cdb4b | 109,188 |
def index_to_sq(ix):
"""Convert an index to a column and rank"""
return (ix % 8, ix // 8) | 65e9a7859dc8f5e4b96b400b396e3bb3d4fa3495 | 109,197 |
def xcp_created (db):
"""Return number of XCP created thus far."""
cursor = db.cursor()
cursor.execute('''SELECT SUM(earned) AS total FROM burns \
WHERE (status = ?)''', ('valid',))
total = list(cursor)[0]['total'] or 0
cursor.close()
return total | 2f298fca557e6df89b5a84880516302497518fc5 | 109,199 |
def get_required(question):
"""
Returns True if metaschema question is required.
"""
required = question.get('required', False)
if not required:
properties = question.get('properties', False)
if properties and isinstance(properties, list):
for item, property in enumerate(... | f116f616dd07bfcfef6fec554da897342ab2b493 | 109,201 |
def _run_dict(session, run_dict, feed_dict=None):
"""Convenience function to run a session on each item in a dict of tensors.
Args:
session: The session to evaluate.
run_dict: A dict of tensors to be run in the session.
feed_dict: Feed dict to be used in running the session.
Returns:
A dict conta... | c0f2edc8ded0932ab5aae2fbacb2ef79071f65e9 | 109,203 |
import inspect
def _get_plugin_methods(plugin_klass):
"""
Return a list of names of all the methods in the provided class.
Note: Abstract methods which are not implemented are excluded from the
list.
:rtype: ``list`` of ``str``
"""
methods = inspect.getmembers(plugin_klass, inspect.ismet... | 154c3d081bdf6c7129414affa4d85325308c61ff | 109,212 |
from typing import Dict
def DictOf(name, *fields):
"""
This function creates a dict type with the specified name and fields.
>>> from pyws.functions.args import DictOf, Field
>>> dct = DictOf(
... 'HelloWorldDict', Field('hello', str), Field('hello', int))
>>> issubclass(dct, Dict)
Tr... | a97e63a0d5c6a0c6abcab260a372a267210fdb42 | 109,214 |
from datetime import datetime
def datetime_string_to_naive(datetime_string):
"""
This function converts ISO 8601 time string without timezone info to a naive datetime object.
Main usage is for date of birth and other places where timezon is not required.
"""
try:
dt = datetime.strptime(dat... | d3b61f2bfc28e0eebaeda607fc3dd4b2f7d288ff | 109,217 |
def get_hook_environment_value(application):
"""From an Application that has been mangled with the "complete" hook, get the value
of the token and the URL that were added to it.
Args:
application (Application): the Application augmented with the elements of the
"complete" hook.
Ret... | 46a6e8314e776d5ff4f494b919d106b768b47e04 | 109,218 |
def delogify_mass(logmass=0.0, **extras):
"""Simple function that takes an argument list including a `logmass`
parameter and returns the corresponding linear mass.
Parameters
----------
logmass : float
The log10(mass)
Returns
-------
mass : float
The mass in linear unit... | ac525e951106074f6aaf2276dc0fa8a3967e37b5 | 109,220 |
import itertools
def xnat_children(obj):
"""
Returns the XNAT objects contained in the given parent object.
:param obj: the XNAT parent object
:return: the child objects
:rtype: list
"""
# pyxnat children() is oddly the child collection attributes
# rather than objects.
child_... | ffd225fe0c2ca869c60e1cc88a675fa6d8241b9d | 109,225 |
from typing import Union
from typing import Callable
def format_fully_qualified_type_name(
type_object: Union[Callable, type]) -> str:
"""Formats a fully qualified name of any type."""
module: str = type_object.__module__
type_name: str = type_object.__qualname__
if module is None or module ==... | 339f56f649f35aac293dbd42ffb856cdafc80ddc | 109,226 |
def only_sig(row):
"""Returns only significant events"""
if row[-1] == 'yes':
return row | 12ff2d7b5cea4a01f3ecbba81dc1f4f982f7bd5a | 109,229 |
def build_geometry(self):
"""Compute the curve (Line) needed to plot the Slot.
The ending point of a curve is the starting point of the next curve in
the list
Parameters
----------
self : SlotCirc
A SlotCirc object
Returns
-------
curve_list: list
A list of one Arc
... | 5368f8eb53ff3cf5fe37df0e44cb7aba6c4169f9 | 109,236 |
def get_path(data, question_name, path_list):
"""
A recursive function that returns the xpath of a media file
:param json data: JSON representation of xform
:param string question_name: Name of media file being searched for
:param list path_list: Contains the names that make up the xpath
:return... | d7b31854aa741e8bc088439b01cc36e6c3417868 | 109,238 |
import base64
def encode(message):
"""
Encodes the message in base64
Args:
message (str/list): message to encode
Returns:
str: encoded message in base64
"""
message_bytes = message.encode("ascii")
encoded_base64_bytes = base64.b64encode(message_bytes)
encoded_message... | 2de0557421d030c548d84909756817c3c2df2646 | 109,239 |
from typing import Dict
from typing import Set
def filter_least_used_disks(disk_to_copy_processes_count: Dict[str, int]) -> Set[str]:
"""Filters for the least used disk
Parameters
----------
disk_to_lockfile_count : Dict[str, int]
Dictionary of disks with lockfile count
Returns
-----... | c52e55837cd0cbd8216441e0b2d9e14e7d0862b8 | 109,245 |
def load_image_set(imageSets_file):
"""
Get image identifiers from ImageSets dir's file for train or test. like ['set00_V000_I00000','set00_V000_I00001'...]
"""
with open(imageSets_file, 'r') as f:
lines = f.readlines()
image_identifiers = [x.strip() for x in lines]
return image_identifi... | 5d0ac0f37f3debe1ec2aef81424055dc7df60758 | 109,246 |
import itertools
def findsubsets(S, m):
"""
Find all subsets of S containing m elements.
Parameters
----------
S: list
List of objects.
m: int
Number of elements per subset.
Returns
-------
subset_list: list
List of subsets.
"""
subset = list(iter... | 096b00d378a2b631736934fb250faf417d89b6d2 | 109,252 |
import six
def get_macros(macro_maker, build_xml, build_system):
"""Generate build system ("Macros" file) output from config_compilers XML.
Arguments:
macro_maker - The underlying Build object.
build_xml - A string containing the XML to operate on.
build_system - Either "Makefile" or "CMake", dep... | 0cf10822e133d13603b2100e3dd994760aafcc7e | 109,263 |
def leading_spaces(line: str) -> int:
"""
Calculates the number of leading spaces in a string.
Parameters
----------
line
Returns
-------
int
"""
return len(line) - len(line.lstrip()) | ab973694fa45b8dded10a046329638d9f65e0d02 | 109,268 |
def complement(chromosome, point1, point2):
"""
Flip chromosome bits between point1 and point2.
"""
new_chromosome = ""
for i in range(len(chromosome)):
if i >= point1 and i <= point2:
if chromosome[i] == '0':
new_chromosome += '1'
else:
... | ebe0a0c35873592f031e94f67cbf31589dd25cf3 | 109,269 |
def terminate_execution() -> dict:
"""Terminate current or next JavaScript execution.
Will cancel the termination when the outer-most script execution ends.
**Experimental**
"""
return {"method": "Runtime.terminateExecution", "params": {}} | 63a4b776b68498cdaa938a0591456f30a64f122e | 109,271 |
def read_converged(content):
"""Check if program terminated normally"""
return True | aa5158fb32e16f98ceb0b64b568f7f2c0f8847a1 | 109,273 |
def output_list(str_num):
"""
Outputs a list from a string of numbers that is meant to represent a sudoku game
board. For example, the following...
530070000600195000098000060800060003400803001700020006060000280000419005000080079
will turn into...
[[5 3 0 0 7 0 0 0 0]
[6 0 0 1 9 5 0 0 0]
... | 745adf06f9af5966bb7bd9046d6f039264698e52 | 109,278 |
import re
def normalize_mac(mac):
"""
Given a Mac, strip periods, colons, or dashes form string and return result in lower case
This works but for a more production ready script look at the netaddr module
:param mac:
:return: lowercase mac without any special characters
"""
return re.sub(r... | f2d7a99984fb1690c0eebd5246fe1288f6648910 | 109,279 |
def testsuites_dict(class_testplan):
""" Pytest fixture to call add_testcase function of
Testsuite class and return the dictionary of testsuites"""
class_testplan.SAMPLE_FILENAME = 'test_sample_app.yaml'
class_testplan.TESTSUITE_FILENAME = 'test_data.yaml'
class_testplan.add_testsuites()
return cla... | bdd7c875b2af9b8e61f9dab0326554f7d7f068f3 | 109,280 |
def convert_string_to_float(s):
"""
Attempt to convert a string to a float.
Parameters
---------
s : str
The string to convert
Returns
-------
: float / str
If successful, the converted value, else the argument is passed back
out.
"""
try:
retur... | aa5f2423e50addd39626bc37d086733fd1fa5032 | 109,283 |
def cal_msg(tick:dict) -> str:
"""
根据tick信息计算成交性质
:param tick: 当前tick
:return: string 成交性质
"""
msg = ''
if tick['oi_diff'] > 0 and tick['oi_diff'] == tick['vol_diff']:
msg = '双开'
elif tick['oi_diff'] < 0 and tick['oi_diff'] + tick['vol_diff'] == 0:
msg = '双平'
else:
... | 89fc7167be63e95bedde5031c4ecb96b9a2296bc | 109,289 |
def time_left_str(since_time):
"""Return a string with how much time is left until
the 1 hour cooldown is over."""
until_available = (60 * 60) - since_time
minute, second = divmod(until_available, 60)
hour, minute = divmod(minute, 60)
return "{:d}:{:02d}:{:02d}".format(hour, minute, second) | 071be855a35daf5b64623784b8015ffe2893e875 | 109,292 |
def split_path(path):
"""
Get the parent path and basename.
>>> split_path('/')
['', '']
>>> split_path('')
['', '']
>>> split_path('foo')
['', 'foo']
>>> split_path('/foo')
['', 'foo']
>>> split_path('/foo/bar')
['/foo', 'bar']
>>> split... | 44ca28d0877e1f24d62ed5cf246ea007e71aa27e | 109,295 |
def read_spectrum(spectrum, index):
"""Read a single spectrum
Parameters
----------
spectrum : mzML spectrum
The mzML spectrum to parse.
Returns
-------
out : list of tuples
List of values associated with each peak in the spectrum.
"""
polarity = 'MS:1000130' in spe... | b3d05c4af829377bcea0e077cd92ceffaca375e5 | 109,299 |
def get_broken_limbs(life):
"""Returns list of broken limbs."""
_broken = []
for limb in life['body']:
if life['body'][limb]['broken']:
_broken.append(limb)
return _broken | 5de9d33885d90ba27a7be90c201d7b61598ec328 | 109,305 |
import re
def strip_prefix(string, strip):
"""
Strips a prefix from a string, if the string starts with the prefix.
:param string: String that should have its prefix removed
:param strip: Prefix to be removed
:return: string with the prefix removed if it has the prefix, or else it
just re... | aff70bfc19206ad7f7123b2be4fdb40c6d9c3828 | 109,308 |
import importlib
def get_module_class(d, c):
"""Load module m in directory d with the class name c."""
m = importlib.import_module('.'.join([d, c]))
return getattr(m, c) | ada580a602a23781923e8fe38b081de5299aa51b | 109,310 |
def set_axes_vis(p, xlabel, ylabel):
""" Set the visibility of axes"""
if not xlabel: p.xaxis.visible = False
if not ylabel: p.yaxis.visible = False
return p | 2a2632b1c041b4957bf08280eeffea9bbc2977f0 | 109,317 |
def get_res_str4WOA18(input):
"""
Convert WOA folder resolution str into filename's resolution str.
"""
d = {
'0.25': '04',
'1.00': '01',
'5deg': '5d',
}
return d[input] | fac2b1471205d876584338f99fb8908ef1139cd6 | 109,319 |
def binary_search_recursive(array, item, left=None, right=None):
"""Return index of item in sorted array or none if item not found."""
# BASE CASE: left and right point to same index
if left == right and left is not None:
# not in array
if left == len(array):
return None
... | 39fa4f85e789333d35dfcfcf817f4887ea4df9d0 | 109,320 |
import time
def time_solve(sokoban):
""" Time how long it takes to solve a Sokoban game """
t0 = time.time()
result = sokoban.solve()
return (time.time() - t0, result) | d3f2366e2a6d550152dfb3439ac81c36acdf0096 | 109,322 |
def getLnrm(arg, pattern):
"""Normalizes the given arg by stripping it of diacritics, lowercasing, and
removing all non-alphanumeric characters.
"""
arg = pattern.sub('', arg)
arg = arg.lower()
return arg | 4e85bcc315f5f7f14b943cb5f48763e68e826253 | 109,324 |
from pathlib import Path
def fixture_snp_path(fixtures_path: Path) -> Path:
"""Return the path to a file with snp definitions"""
return fixtures_path / "snps.grch37.txt" | 44cb3bfb7d197485668b9cfe84074e61bba1d6aa | 109,325 |
def get_energy(output_parameters):
"""
Given the output parameters of the pw calculation,
return the energy (eV).
"""
E = output_parameters.dict.energy
return (E) | 38a03577ef8b937de2ceae1ac1a943c224095e94 | 109,332 |
import re
def was_replied(df):
"""Looks to see if something like Re or RE: is in the subject. Uses regular expressions
"""
return df['subject'].str.contains('re?\:?\s', flags=re.IGNORECASE).values | 6a4ef72bef1049e8e4c6c707f6c6f7978e1663a2 | 109,335 |
def read_sh(path: str):
"""
read a sh file. skip comment, shebang and qsub params.
Args:
path (str): path to the sh file
Returns:
list: list of lines of the sh file without comment, shebang and qsub params.
"""
lines = []
with open(path) as f:
for line in f:
... | 1ab6f3841cf0870afbbbb8b6349897149bb3697a | 109,337 |
def encrypt(plaintext, rails):
"""
Rail fence cipher. Encrypts plaintext by given number of rails.
:param plaintext: plaintext to encrypt.
:param rails: number of rails to use to encrypt.
:returns: encrypted plaintext (ciphertext).
See https://en.wikipedia.org/wiki/Rail_fence_cipher
Exampl... | 57b4cf3b71d8ef33f041326d90032beda4da48a9 | 109,339 |
def _sorted_by_type(fields):
"""Sorts params so that strings are placed before files.
That makes a request more readable, as generally files are bigger.
It also provides deterministic order of fields what is easier for testing.
"""
def key(p):
key, val = p
if isinstance(val, (bytes,... | 8f08d89a55eeeb3a7b32e4a232134a467905231f | 109,341 |
def owner_id_to_string_array(owner_id):
"""
Converts a snowflake owner id to an array of strings.
Parameters
----------
owner_id : `int`
Snowflake value.
Returns
-------
owner_id_array : `list` of `str`
"""
return [str(owner_id)] | 2083eecc50090ef94631199755f61043f66bd664 | 109,347 |
import json
def read_jobs_statuses(filename):
"""Deserialize statuses for all jobs from the JSON file."""
with open(filename) as fin:
return json.load(fin)["jobs"] | dc05789f342d333e8ee0179ac359b1637a624763 | 109,349 |
def play_episode(env, policy, render_option, min_steps):
"""
Play an episode with the given policy.
:param min_steps: the minimum steps the game should be played
:param env: the OpenAI gym environment
:param policy: the policy that should be used to generate actions
:param render_option: how th... | 4644d80df0dcbfc1ca6172ec949235ea9b2b1f0e | 109,355 |
def read_string(puzzle_string: str):
"""
Read string describing puzzle,
converting it into a form the solver can understand.
puzzle_string: string specifying puzzle
return: array of numbers and operations for each row and column
"""
puzzle = [
part.split(' ')
for part
... | 1e6e25b6a58aa16b7a9d23bcc632fc0622b2800a | 109,368 |
def inverse(a, n):
"""Find the multiplicative inverse of one number over a given range.
Adapted from Wikipedia: Extended Euclidian Algorithm -
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
Returns the multiplicative inverse of a over the finite range n. The result
is a number which... | d1c8d624c912e51d01f9da2e63bea50794b0f48f | 109,370 |
def fib_from_pascal(m):
"""Return the mth fibonacci number using Pascal's triangle."""
def fib_pascal(n, fib_pos):
if n == 1:
line = [1]
fib_sum = 1 if fib_pos == 0 else 0
else:
line = [1]
prev, fib_sum = fib_pascal(n - 1, fib_pos + 1)
... | 658ed4ef2142b6e13805a9e57687190167e788b4 | 109,374 |
def file_extension(filename):
"""
Return the extension of a file (if any)
"""
parts = filename.split(".")
if len(parts) >= 2:
return parts[-1]
else:
return "" | fa230dce3b05ca16c27470140ad6a32e8f497068 | 109,376 |
def stopw_removal(inp, stop):
"""
Stopwords removal in line of text.
Input:
- inp: str,
string of the text input
- stop: list,
list of stop-words to be removed
"""
# Final string to be returned
final = ''
for w in inp.lower().split():
if w not in stop... | ec7f386cc66b8673ee00f18d9f6a3e62eb06731e | 109,378 |
def _select_points(a, list_like):
"""
returns one above a, one below a, and the third
closest point to a sorted in ascending order
for quadratic interpolation. Assumes that points
above and below a exist.
"""
foo = [x for x in list(list_like) if x-a <= 0]
z = [min(foo, key=lambda x : abs... | 4487336f10a2d08561bf38ee095be9f21f05d078 | 109,380 |
def mid_point(start_x, start_y, end_x, end_y):
"""
returns the mid point of two points
"""
mid_x = (start_x + end_x) / 2
mid_y = (start_y + end_y) / 2
return mid_x, mid_y | f445dcea7827bb57d4f96690ef2eae9578278660 | 109,383 |
def _field_path_to_elasticsearch_field_name(field_path):
"""Take a field_path tuple - for example: ("va", "info", "AC"), and converts it to an
elasicsearch field name.
"""
# drop the 'v', 'va' root from elastic search field names
return "_".join(field_path[1:] if field_path and field_path[0] in ("v... | d215378cb40d2d4bd8c6a99c1c655c5a2e5aa905 | 109,384 |
from typing import Callable
def locate_resource(name: str) -> Callable:
""" Locate a resource (module, func, etc) within the module's namespace """
resource = globals()[name]
return resource | 392d6b4daac711cb9a33907e3ce8f439a0022a61 | 109,385 |
def pattern_from_multiline(multiline, pattern):
"""Return only lines that contain the pattern
Parameters
----------
multiline - multiline str
pattern - str
Returns
-------
multiline str containing pattern
"""
return "\n".join([line for line in multiline.splitlines() if... | d8be4e97fa53fccb3869a59a0725fbc88f2f2ba9 | 109,386 |
def get_sourced_from(entry):
"""Get a list of values from the source_from attribute"""
sourced_from = 'http://worldmodelers.com/DataProvenance#sourced_from'
if sourced_from in entry:
values = entry[sourced_from]
values = [i['@id'] for i in values]
return values | a4b7751eae4c5c49938cee0765b80828d14f2854 | 109,387 |
def fast_mean_variance_update(new_sample, old_mean, old_variance, k):
"""
Return the new mean and variance if one new sample is added.
"""
new_mean = (k * old_mean + new_sample)/(k+1)
new_variance = (k-1) * old_variance / k + (new_sample - old_mean)**2/(k+1)
return new_mean, new_variance | 12097acde4eecdf5df222c1af8f83d27f2f6b46f | 109,388 |
def to_code(cells):
"""
Turns the cells into Python code.
:param cells: the cells to iterate
:type cells: list
:return: the generated code
:rtype: list
"""
result = []
for cell in cells:
if ("cell_type" in cell):
if (cell["cell_type"] == "code") and ("source" i... | 38c21ba513fd27ea41fd226607bdc230f26c7bb8 | 109,391 |
def get_hostname_to_data_dict(fio_data):
"""Create dictionary mapping hostname to its fio data.
Returns:
Dict[str, List[dict]] - hostname to its fio data
"""
hostname_data_dict = {}
for jb in fio_data['client_stats']:
if jb['jobname'] == 'All clients':
continue
h... | 15c3b2b2159332634648a62f7ca31bc4d660e498 | 109,392 |
def vect3_subtract(v1, v2):
"""
Subtracts one 3d vector from another.
v1, v2 (3-tuple): 3d vectors
return (3-tuple): 3d vector
"""
return (v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]) | b5710e04d80340f731db55b472e690fdfcba9f7a | 109,397 |
def add_base_class_to_instance(instance, base_class=None, new_name=None):
"""
Generic utility for adding a base class to an instance.
This function returns a copy of the given instance which
will then include the new base_class in its ``__mro__``.
The way that is done internally is it creates a br... | 4c4f07922d5b79cf72d5ab10e7634e96688199b3 | 109,399 |
def calc_completeness(req_tags, tags):
"""Takes in a list of required tags and
tags found. Returns a string status of
completion depending if all required tags
were found."""
status = "Incomplete"
result = all(k in tags for k in req_tags)
if result:
status = "Complete"
return sta... | ca2213ef144e4a59621fd48eb48553399b67a8b6 | 109,401 |
def heuristic(node, goal)->int:
"""
Heuristic function that estimates the cost of the cheapest path from node to the goal.
In our case it is simple manhatan distance.
:param node:
:param goal:
:return: Manhatan distance of nodes
"""
# expand nodes
x1, y1 = node.get_pos()
x2, y2 =... | b625872a0eef65e860a41f768975f724b9f8cbb6 | 109,402 |
def max_divisible(a, b):
"""
Keep dividing(a/b) till it's divisible(a % b == 0)
e.g.
Input: a = 300; b = 2
Output: 75
:param a:
:param b:
:return:
"""
while a % b == 0:
a = a / b
return a | 66c4df2e935db614c40a509569ceaa46a7141f3b | 109,403 |
def textwrap(text, width=80, indent=0):
"""Wrap a string with 80 characters
:param text: input text
:param width: (defaults to 80 characters)
:param indent: possible indentation (0 by default)
"""
if indent == 0:
indent = ""
else:
indent = " " * indent
data = [indent + ... | e963d0a0f72205816fa5f4b74471873189521392 | 109,412 |
def calc_check_digit(number):
"""Calculate the check digit.
The number passed should not have the check digit included.
"""
primary_weights = (3, 2, 7, 6, 5, 4, 3, 2)
secondary_weights = (7, 4, 3, 2, 5, 2, 7, 6)
# pad with leading zeros
number = (8 - len(number)) * '0' + number
s = -sum... | 253159db05c0796f744acc027fca0687d69efc61 | 109,413 |
def env_str_to_bool(varname, val):
"""Convert the boolean environment value string `val` to a Python bool
on behalf of environment variable `varname`.
"""
if val in ["False", "false", "FALSE", "F", "f", "0", False, 0]:
rval = False
elif val in ["True", "true", "TRUE", "T", "t", "1", True, 1]... | 6572a4368f492510b6287a49ef38be2ef614dca0 | 109,414 |
def wrapseq(seq, size=60):#{{{
"""
wrap the sequence in to a list of fixed length
"""
return [seq[i:i+size] for i in range(0, len(seq), size)] | 1932bd6caef677337de12a88495fb64917446518 | 109,415 |
import functools
def wrap(before=None, after=None, condition=lambda *args, **kwargs: True):
"""
A helper for creating decorators.
Runs a "before" function before the decorated function, and an "after"
function afterwards. The condition check is performed once before
the decorated function.
"... | ca9e6c4a41f93ca2902fe7e7c9fbbb2a96826064 | 109,418 |
from typing import Dict
from typing import Any
def default_style() -> Dict[str, Any]:
"""Define default values of the pulse stylesheet."""
return {
'formatter.general.fig_size': [8, 6],
'formatter.general.dpi': 150,
'formatter.color.fill_waveform_d': ['#648fff', '#002999'],
'fo... | a516ad47fa4f90cca3533c6c7bc643ce874329b5 | 109,421 |
import torch
def diff(x: torch.Tensor, dim: int) -> torch.Tensor:
"""Take the finite difference of a tensor along an axis.
Arguments:
x (torch.Tensor):
Input tensor of any dimension.
axis (int):
Axis on which to take the finite difference.
Returns:
d (torch.... | d705b586b7cec135474d616ce2edca748d1fa15f | 109,429 |
def has_spdx_licenses(resource):
"""
Return True if a Resource licenses are all known SPDX licenses.
"""
if resource.scan_errors:
return False
for detected_license in resource.licenses:
if not detected_license.get('spdx_license_key'):
return False
return True | 06048d6806c4d056ef8df581aa7b860e8469a88c | 109,430 |
def get_number_from_string(s, number_type, default):
"""Returns a numeric value of number_type created from the given string or default if the cast is not possible."""
try:
return number_type(s.replace(",", "."))
except ValueError:
return default | f4905debb35daefb1b9490142009f7827c345a1e | 109,432 |
def _get_factory_attr(factory, attr):
"""
Try getting a meta attribute 'attr' from a factory.
The attribute is looked up as '_attr' on the factory, then, if the factory
and its model class names match, as 'attr' on the model's meta. The
factory's own meta cannot define custom attributes and is skip... | 29f8a87fdf573b0fae3864f2fa00ba0ef263ffac | 109,435 |
def _get_spm_arch(swift_cpu):
"""Maps the Bazel architeture value to a suitable SPM architecture value.
Args:
bzl_arch: A `string` representing the Bazel architecture value.
Returns:
A `string` representing the SPM architecture value.
"""
# No mapping at this time.
return swif... | d44dc3bcccbe44dfd9203a3aea21920e8e907e74 | 109,442 |
import math
def truncate(x:float)->int:
"""
Float to int truncating for possitive and negative values.
x - float to be truncated.
return truncated int.
"""
return math.floor(x) if x<0 else math.ceil(x) | b163a11cc00d679d4f94886780672236cc12f8ef | 109,444 |
def cleanup_watch(watch):
"""Given a dictionary of a watch record, return a new dictionary for output
as JSON."""
watch_data = watch
watch_data["id"] = str(watch["_id"])
watch_data["author"] = str(watch["author"])
watch_data["watched"] = str(watch["watched"])
del watch_data["_id"]
... | e464764c2360486fc8ba3008b77f508ff950a882 | 109,448 |
import io
def export_sass(palette):
"""
Return a string of Sass variable for every colors.
Arguments:
palette (dict): Dictionnary of named colors (as dumped in JSON from
``colors`` command)
Returns:
string: Sass variables.
"""
# Sass color palette variable
sas... | c6c6f870d60fb9b5e71bb7697f2218a2ff2904fc | 109,449 |
def is_removable(queue_url) -> bool:
"""
Returns True if the queue url does not end with staging or production
:param str queue_url: The queue url
:return bool:
"""
if str(queue_url).endswith("staging") == True \
or str(queue_url).endswith("production") == True:
return False
... | 04e822f9571b9ee5c181e23e2c79b3a3d72610e9 | 109,450 |
from typing import Tuple
def _pad_strides(strides: int, axis: int) -> Tuple[int, int, int, int]:
"""Converts int to len 4 strides (`tf.nn.avg_pool` uses length 4)."""
if axis == 1:
return (1, 1, strides, strides)
else:
return (1, strides, strides, 1) | 8cd91ea7e04b2c032505d51d68a6d4ad088d5934 | 109,452 |
def nucl_count(sequence):
"""determine counts of each letter in a sequence,
return dictionary with counts"""
nucl = {'A': 0, 'C': 0, 'G': 0, 'T': 0, 'N': 0}
for letter in sequence:
if letter not in nucl:
print(f'unexpected nucleotide found: "{letter}"')
nucl[letter] = 0... | 4082ef833cb857dab64fdb897a4be3495d67c482 | 109,453 |
def bhp2watts(bhp):
"""convert brake horsepower (bhp) to watts"""
return bhp * 745.7 | 8a1ffdf59104431d0e78353b7ba9f52408c5ebc4 | 109,462 |
import inspect
def nargs(fun):
"""Get the number of arguments of a function"""
return len(inspect.signature(fun).parameters) | ccf278bda20f9e8c49bcf141f21e1654c30b599f | 109,465 |
def camelcased_to_uppercased_spaced(camelcased: str) -> str:
"""Util function to transform a camelCase string to a UPPERCASED SPACED string
e.g: dockerImageName -> DOCKER IMAGE NAME
Args:
camelcased (str): The camel cased string to convert.
Returns:
(str): The converted UPPERCASED SPACE... | e9a01ee1fdbc6ea626ed509d68ec3ae799c2a007 | 109,470 |
def ordinalStr(n) :
"""
Given the positive integer n, return the corresponding ordinal number string
"""
assert(n>0)
def getSuffix(n) :
def getOrdKey(n) :
if n < 14 : return n
else : return (n % 10)
i = getOrdKey(n)
if i == 1: return 'st'
... | 9736abc3cce2611fb3ce60a6903a7f77ed026998 | 109,472 |
def configure_proxy_settings(ip, port, username=None, password=None):
"""
Configuring proxies to pass to request
:param ip: The IP address of the proxy you want to connect to ie 127.0.0.1
:param port: The port number of the prxy server you are connecting to
:param username: The username if requred authentication, ... | 1e24d07f1039c8538033561a41c9cc01dc74b17f | 109,477 |
def _summary_name(node):
"""
Generate summary label for node based on its package, type, and name
"""
if node.name:
return "%s (%s/%s)"%(node.name, node.package, node.type)
else:
return "%s/%s"%(node.package, node.type) | b5633207dd78d0dedd68c96ef6e7e14bfb1760cd | 109,480 |
import requests
from bs4 import BeautifulSoup
import re
import itertools
def translate(word: str) -> list:
"""Translate word
Arguments:
word {str} -- the word to be translated
Returns:
[list] -- list of translations
"""
req = requests.get(f"https://www.diki.pl/slownik-angielskieg... | 37281a50c9c8d787cdc643eb6945de6d118f85b8 | 109,485 |
def min_max_denorm(data, min_, max_):
"""
Denormalize the data using that was normalized using min-max normalization
:param data: 1d array of power consumption
:param min: the min of the power consumption
:param max: the max of the power consumption
:return: denormalized power consumption
""... | e88346945aff245566bb21b1a50e828ff79115f8 | 109,492 |
def get_covid_ids(projs):
"""Returns covid-related ids in cordis data"""
d_ids = set(
projs.loc[
(projs["covid_level"] != "non_covid") | (projs["has_covid_term"] == True)
]["project_id"]
)
return d_ids | f57391338744d6357396dd81c6702d310801a820 | 109,493 |
def d2arcs(d):
"""Convert degrees into arcseconds."""
return d * 3600.0 | 87c897170dce450764fb6dbd2b12795969f7e64c | 109,495 |
import re
def _matching_ints(strings, regex):
"""Uses regular expression to select and then extract an integer from
strings.
Parameters
----------
strings : list of strings
regex : string
Regular Expression. Including one group. This group is used to
extract the integer from... | 0b13031c5ede9b5af04ed8bd9d40e9c0895e5ce5 | 109,500 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.