content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import math
def correct_bits_length(bits_expected, number):
"""
Checks if the number has sufficient bits
Keyword arguments:
bits_expected -- Number of bits expected.
number -- Decimal number
Returns:
True if equal False otherwise
"""
length_expected = int(math.log10(2 ** bits_expected))
actual_len... | 129cbfd25052fa1f0227573c6a7ffd0a7b150bfe | 229,060 |
import re
def remove_zero_padded_dates(date_string):
"""Mimic %-d on unsupported platforms by trimming zero-padding
For example:
January 01 2018
Becomes:
January 1 2018
The regex finds a space or a hyphen followed by a zero-padded
digit, and replaces with the symbol (space or hyp... | 100b06eee8c756f289be7e457be67d2334160a6c | 612,353 |
from datetime import datetime
def parse_date_parts(month, year):
"""
Given a month string and a year string from publisher data, parse apart the month, day and year and create
a standard date string that can be used as input to VIVO
:param month: string from publisher data. May be text such as 'JUN' ... | 29b5a162b851b51d1bd9c63c9996c5d3577263f2 | 411,266 |
def score_1(game, player): # 82.14%
"""
Heuristics computing score using #player moves - k * #opponent moves
:param game: game
:param player: player
:return: score
"""
if game.is_winner(player) or game.is_loser(player):
return game.utility(player)
opponent = game.get_opponent(p... | 3995237f5d5474660c752c308e1077aad1743d06 | 700,898 |
from typing import List
def whozit_loop(n: int) -> List[int]:
"""This function takes an integer, loop from 0 through to the integer, and returns a list of the numbers containing 3 using for-loop."""
result = []
for i in range(n):
if '3' in str(i):
result.append(i)
return result | 985dc074f6aac5379b3626877d20a4b996347965 | 453,976 |
import re
def is_canonical(version):
"""Return True if `version` is a PEP440 conformant version."""
match = re.match(
r'^([1-9]\d*!)?(0|[1-9]\d*)'
r'(\.(0|[1-9]\d*))'
r'*((a|b|rc)(0|[1-9]\d*))'
r'?(\.post(0|[1-9]\d*))'
r'?(\.dev(0|[1-9]\d*))?$', version)
return mat... | df3f693aed625c9e1edbf76085571f8f022330d7 | 351,759 |
def validateInputs(dict):
"""
Checks that all necessary inputs to post request are present
----------
Parameters
----------
dict: dictionary received from post request
Returns
-------
1 if there are missing keys
0 if all keys are present
"""
dict_keys = ['username... | 91d50c7a55132a60861da9ecaba0f0e3da4a8efd | 360,592 |
def _mangle_name(internal_name, class_name):
"""Transform *name* (which is assumed to be an "__internal" name)
into a "_ClassName__internal" name.
:param str internal_name: the assumed-to-be-"__internal" member name
:param str class_name: the name of the class where *name* is defined
:return: the t... | 6a97a729437e08f510f2eefc8210c8063d1648a5 | 398,238 |
import torch
def sample_noises(size):
"""
Sample noise vectors (z).
"""
return torch.randn(size) | edce1ff6d618c4e569d725fff4dce81eb9c643d5 | 617,561 |
def pairs_generator(rng):
"""
Creates Generator of ordered pairs
:param rng : Range of the interval, e.g. 3 means pairs (0,1),(0,2),(1,2)
:return:
"""
return ((i, j) for i in range(rng) for j in range(rng) if i < j) | 1d3eb5f1a0a06aeae6df32c222c5321539620da4 | 606,876 |
def run_wsgi(app, environ):
"""Execute a wsgi application, returning (body, status, headers)."""
output = {}
def start_response(status, headers, exc_info=None):
output['status'] = status
output['headers'] = headers
body = app(environ, start_response)
return body, output['status'],... | 4f4e2797ebd8f869797458a79df4239096144ff3 | 232,582 |
import pytz
from datetime import datetime
def get_utctimestamp(thedate=None, fmt='%Y-%b-%d %H:%M:%S'):
"""
Returns a UTC timestamp for a given ``datetime.datetime`` in the
specified string format - the default format is::
YYYY-MMM-DD HH:MM:SS
"""
d = thedate.astimezone(pytz.utc) if thedate... | 5cc3650a466a00b542762e8521a984609cfa1b1a | 328,775 |
def get_security_group_id(event):
"""
Pulls the security group ID from the event object passed to the lambda from EventBridge.
Args:
event: Event object passed to the lambda from EventBridge
Returns:
string: Security group ID
"""
return event.get("detail").get("requestParameter... | 8f19704efb2c2b2f2dd99d0c07c95c88948a47a2 | 189,441 |
import tempfile
def downloadDataFromBucket(bucket, fileName):
""" Download a single NEXRAD radar datum.
Args:
bucket: A NOAA NEXRAD level 2 radar data bucket.
fileName: A filename formatted as follows :
'YYYY/MM/DD/KLMN/KLMNYYYYMMDD_HHMMSS_V06.gz' or
'YYYY/MM/DD/KLMN/K... | 6cc214615f896af7bec2833796dc2671dd6b61c7 | 498,438 |
def mergeHeight(feet, inches):
"""
Takes two integer values, feet and inches, and calculates
the total height in inches.
"""
return (feet * 12) + inches | f35c850454b8a458d3c9e33038003aff2dc8ec7d | 422,704 |
def basename(path):
"""Return the file name portion of a file path."""
return path.split("/")[-1] | 15bc5f9471478300dc946621bc525077216230fa | 610,234 |
def unpack(value, number=2, default=None):
"""Unpack given `value` (item/tuple/list) to `number` of elements.
Elements from `value` goes first, then the rest is set to `default`."""
if not isinstance(value, list):
if isinstance(value, tuple):
value = list(value)
else:
... | 9f5ec4f64bd81d1a656cdaf8b3e9cfe5ce4f8f6e | 569,767 |
def normalize_column_to_length(col, desired_count):
"""Given the value(s) for a column, normalize to a desired length.
If `col` is a scalar, it's duplicated in a list the desired number of
times. If `col` is a list, it must have 0, 1, or the desired number of
elements, in which cases `None` or the sin... | befb5bffb7f9bdc5c8bb0a69978184eee3f2dff2 | 239,222 |
def format_bids_name(*args):
"""
write BIDS format name (may change this later)
:param args: items to join
:return: name
"""
return ("_").join(args) | 1f8e2ecbf3609093668ad153e75663fe6e3f3f76 | 513,146 |
import torch
def bluebert_load_model(bluebert_model_path: str):
"""
Load fine-tuned Bluebert model.
:param bluebert_model_path: directory with saved model
:return: fine-tuned Bluebert Transformer model
:return device: CPU vs GPU definition for torch
"""
if torch.cuda.is_available():
... | 2f783a4ade34e67f68bf7a175736c2d7a600fb9c | 153,884 |
def _get_az_function_def(full_command, command_verb, arguments, command_doc):
"""Given a function name, arguments, and doc,returns a formatted string function def."""
if command_doc:
function_def = f"""
def {command_verb}({arguments}):
'''
{command_doc}
'''
return _call_az("az {full_comm... | b7ff28aa3336c62f2a87fa0a7d9207c739d15817 | 597,360 |
def check_is_right(name):
"""
Checks if the name belongs to a 'right' sequence (/2). Returns True or
False.
Handles both Casava formats: seq/2 and 'seq::... 2::...'
"""
if ' ' in name: # handle '@name 2:rst'
name, rest = name.split(' ', 1)
if rest.startsw... | 1dd9a8edd79fbb3e83038ec15fdb0f02d547acb1 | 383,083 |
def add_one(series, config):
""" Add a count of 1 to every count in the series """
return [ ct+1 for ct in series ] | 3f764718af04b93cd2d5b50ce6a78207bea9e387 | 563,276 |
import re
def remove_tag_and_contents(s, tag=None, tags=None):
"""
>>> remove_tag_and_contents('hi there')
'hi there'
>>> remove_tag_and_contents('<p>hi</p> <style>p {font-weight: 400;}</style><p>there</p>', tag='style')
'<p>hi</p> <p>there</p>'
>>> remove_tag_and_contents('<span class="foo"... | 9c6506b39ff6f926cf9b03f691bd1b4ecbed6c4a | 39,805 |
def parse_suppress_errors(params):
"""Returns a list with suppressed error codes."""
val = params.get('suppressErrors', None)
if not val:
return []
return val.split('|') | 10161322d820f009b2b62e8164d22671fcea665f | 283,331 |
import json
def uglify(data):
""" return a string of compressed json text """
return json.dumps(data, separators=(',', ':')) | b704ddc7ce82da15453ab54e3dd58e68649da0f6 | 131,458 |
def armstrong(some_int: int) -> bool:
"""
Accepts an int
Returns whether or not int is an armstrong number
:param some_int:
:return:
"""
string_rep = str(some_int)
sum_val = 0
for digit in string_rep:
sum_val += int(digit) ** 3
return some_int == sum_val | dd0c2b3533e77c29330d750826b328c2b33b2460 | 44,153 |
def add_id_to_dict(doc):
""" Adds the document's id to the document's fields dictionary.
"""
full_dict = doc.to_dict()
full_dict['id'] = doc.id
return full_dict | 3626ee822817fde648e46fcd6862dc689cc20c5a | 679,346 |
def calculate_sum_dice(die1_value, die2_value):
"""
Add up the num of the first two dice
die1_value: The first random value
die2_value: The second random value
Returns: The number of sum in value (int)
"""
sum_dice = int(die1_value) + int(die2_value)
return sum_dice | 77589800f74744dc4119e5d32d9c9a9e7aa4e2f3 | 227,848 |
import logging
def validate_config(config):
"""
Validates given *OpenColorIO* config.
Parameters
----------
config : Config
*OpenColorIO* config to validate.
Returns
-------
bool
Whether the *OpenColorIO* config is valid.
"""
try:
config.validate()
... | 8248d3e94ead22672533908bb7e91a78decaef41 | 287,575 |
import random
def make_id(stringLength=10):
"""Create an id with given length."""
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
return "".join(random.choice(letters) for i in range(stringLength)) | f2b75e9bedd706b8a7901ffb8c8bae5e4f2cbdbb | 414,605 |
def make_nofdel(name):
"""Make a deleter for `property()`'s `fdel` param that raises
`AttributeError`
Args:
name (str): property name
Raises:
AttributeError: always raises exception
Returns:
function: A deleter function
"""
def fdel(self):
raise AttributeEr... | 2e44f43f48a6a22211bc7e268fafa7ff84cc3d66 | 77,375 |
def read_sheet(spreadsheet_id, google, row=0):
"""
Returns the content of the entire sheet. If a row number above 0 is
specified, only returns the contents of that row.
"""
if row > 0:
return google.values().get(
spreadsheetId=spreadsheet_id,
range="Synced-Act... | a293db85f3b2ccefa5ee211b363867edac353b8e | 266,312 |
import requests
def ct_get_links(link, platforms='facebook', count=100, start_date= None,
end_date=None, include_history=None, include_summary='false',
offset = 0, sortBy = 'date', api_token=None):
""" Retrieve a set of posts matching a certain link.
Args:
link (str):... | ad718c9768617eb2f81731aeb0cd0fa8ebf7e9da | 502,727 |
def extract_some_key_val(dct, keys):
"""
Gets a sub-set of a :py:obj:`dict`.
:param dct: Source dictionary.
:type dct: :py:obj:`dict`
:param keys: List of subset keys, which to extract from ``dct``.
:type keys: :py:obj:`list` or any iterable.
:rtype: :py:obj:`dict`
"""
edct = {}
... | 80dff136ada8cfd754e1a02423e7eef364223a48 | 28,013 |
def bdev_compress_delete(client, name):
"""Delete compress virtual block device.
Args:
name: name of compress vbdev to delete
"""
params = {'name': name}
return client.call('bdev_compress_delete', params) | 0ccf183c0f6d97b8e6fdcfa37b7f3c3692967a8a | 596,526 |
def rectangle_dot_count(vertices):
""" Count rectangle dot count include edge """
assert len(vertices) == 2
width = abs(vertices[0][0] - vertices[1][0])
height = abs(vertices[0][1] - vertices[1][1])
dot_count = (width + 1) * (height + 1)
return dot_count | 2e330a5137482e7bf1eb2396936c61a0497bbe62 | 640,267 |
import math
def categorize(distance: float) -> int:
"""Distance binning method to be referenced across data analysis files and classifiers.
Args:
distance (float): The premeasured distance, in meters.
Returns:
The floor of the given distance amount.
"""
return math.floor(distance... | 0014f2096131f03e6c0619e7d8a3ad9526d44fd1 | 42,606 |
import torch
def dot(A, B, dim=-1):
"""
Computes the dot product of the input tensors along the specified dimension
Parameters
----------
A : Tensor
first input tensor
B : Tensor
second input tensor
dim : int (optional)
dimension along the dot product is computed (... | b8859730dec5987cf566f6292b66d5087b230e97 | 681,186 |
import socket
def is_connectable(port):
"""Trys to connect to the server to see if it is running."""
try:
socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_.settimeout(1)
socket_.connect(("localhost", port))
socket_.close()
r... | b5d9e6bd1287a4af497d1124681e6be9533993a5 | 329,604 |
def _setup_residual_graph(G, weight):
"""Setup residual graph as a copy of G with unique edges weights.
The node set of the residual graph corresponds to the set V' from
the Baswana-Sen paper and the edge set corresponds to the set E'
from the paper.
This function associates distinct weights to th... | 49c68ad977beb9edc695993cc1fe7fc235f1d69b | 464,774 |
def named_crs(epsg):
"""Construct a named CRS dict given an EPSG code
according to the GeoJSON spec.
"""
return {
'type': 'name',
'properties': {
'name': 'urn:ogc:def:crs:EPSG::{}'.format(epsg)
}
} | 552147bb7a5646f91913deb2bc33181c82d579d4 | 413,681 |
def object_from_args(args):
"""
Turns argparser's namespace into something manageable by an external library.
Args:
args: The result from parse.parse_args
Returns:
A tuple of a dict representing the kwargs and a list of the positional arguments.
"""
return dict(args._get_kwargs... | e48c0a8a49e4fe106d30d37f03c11a07e479cfc3 | 630,876 |
def read_maze(maze_file):
""" (file open for reading) -> list of list of str
Return the contents of maze_file in a list of list of str,
where each character is a separate entry in the list.
"""
res = []
for line in maze_file:
maze_row = [ch for ch in line.strip()]
res.append(ma... | 2084ac891012932774d46d507f550e8070e3cc47 | 42,814 |
def combinedJunctionDist(dist_0, dist_1):
"""Computes the combined genomic distance of two splice junction ends
from the closest annotated junctions. In essence, it is finding the
size indel that could have created the discrepancy between the
reference and transcript junctions.
Examples ('|' ... | af2a0b0d880f29afb097215a55dfef8426c57556 | 81,005 |
def _create_youtube_video_asset(
client, customer_id, youtube_video_id, youtube_video_name
):
"""Creates a asset with the given YouTube video ID and name.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID str.
youtube_video_id: a str of a YouTu... | 459555ea8e67a5a9c8a568e108ec14411ed80692 | 594,061 |
def list_resources(client, resource_group_name=None):
"""
List all Azure Cognitive Services accounts.
"""
if resource_group_name:
return client.list_by_resource_group(resource_group_name)
return client.list() | cf013768ed6ed613ef5010b3d7ad8229168cd774 | 462,526 |
def valid_gain(gain):
"""
Use this parse an argument as if it were a float and get back a valid gain as a float.
Raises ValueError if passed an un-parse-able value.
"""
try:
my_gain = round(float(gain), 1)
except TypeError:
raise ValueError("Could not parse value as into a valid ... | 2dd48252812a408e8cc55cd0cbfc768096ca6d81 | 617,067 |
def verify_filetype(filename: str, valid_filetypes=["jpeg", "png", "jpg"]) -> bool:
"""
Helper function which determines the filetype of
a file based on it's filename
valid filetypes = ["jpeg", "png", "jpg"]
Parameters:
filename (str)
Returns:
True if filetype is valid
"""... | 115b5b1c77a5cf5a116fa86aa53c9ac147a56e42 | 547,806 |
import requests
import logging
def post_peripheral(api_url: str, body: dict) -> dict:
""" Posts a new peripheral into Nuvla, via the Agent API
:param body: content of the peripheral
:param api_url: URL of the Agent API for peripherals
:return: Nuvla resource
"""
try:
r = requests.pos... | 7da79de1a59973c5325a93ce2e316a6a45239c00 | 253,517 |
from typing import Any
from typing import Union
def check_is_union(data_type: Any) -> bool:
"""Check if `data_type` is based on a `typing.Union`."""
return hasattr(data_type, '__origin__') and \
data_type.__origin__ is Union | ea6da23d864cde40a3862bc12fd0ab20a7ae3ea0 | 219,611 |
def arrival_to_str(arrival):
"""
:param arrival: list (minutes, seconds, stops)
:return: arrival string
example : '4m(3)' for 4 minutes and 3 stops left
"""
arrival_str = "----"
if arrival is not None:
# omit seconds
arrival_str = '{}m({})'.format(arrival[0], arri... | c897b74d0646e8987ae55758f5a2d77de29972c4 | 278,495 |
import re
def cleanYear(media):
"""
Takes a Show/Movie object and returns the title of it with the year
properly appended. Prevents media with the year already in the title
from having duplicate years. (e.g., avoids situations like
"The Flash (2014) (2014)").
Arguments:
media -- a Show/Mo... | 75bb401f8e09f3ae37473131fc761ea7d56b8f9d | 567,906 |
def versiontuple(v, version_index=-1):
""" convert a version string to a tuple of integers
argument <v> is the version string, <version_index> refers o how many '.' splitted shall be returned
example:
versiontuple("1.7.0") -> tuple([1,7,0])
versiontuple("1.7.0", 2) -> tuple([1,7])
versiontuple(... | e85d18e9005b0ffa9adb3e7dbb5c01c4fdb4a333 | 88,416 |
from datetime import datetime
from dateutil import tz
def max_time() -> datetime:
"""Returns max time datetime object
Returns
-------
datetime
max time datetime object
"""
return datetime.max.replace(tzinfo=tz.tzutc()) | 7bedef28756a5d4454ae82fda8e250ec74caf303 | 437,302 |
def from_camel_case(name):
"""Convert camel case to snake case.
Function and variable names are usually written in camel case in C++ and
in snake case in Python.
"""
new_name = str(name)
i = 0
while i < len(new_name):
if new_name[i].isupper() and i > 0:
new_name = new_na... | c6e7184598252a6db1bcaee5d5375969c5c9bd39 | 698,053 |
import requests
def query_url(url):
""" - Performs HTTP GET to the URL passed in params, then:
* Returns response container if HTTP 200 or 404
* Raise exception for other HTTP response codes. i.e >500 """
server_response = requests.get(url)
if server_response.status_code == 200:
... | 07ffd112251cf92834de6dbbd65bc0b4ec9bf3ea | 534,579 |
def drop_rows(rows):
"""Drop rows in a DataFrame and reset the index."""
def dropper(data):
return data.drop(rows).reset_index(drop=True)
return dropper | 9edb8eab028c15355f9883fcab31e47018e4da57 | 574,142 |
def extr_hotdays_calc(data, thr_p95):
"""
Calculate number of extreme hotdays.
Return days with mean temperature above the 95th percentile
of climatology.
Parameters
----------
data: array
1D-array of temperature input timeseries
thr_p95: float
95th percentile daily mea... | 3a082ffc5ef62089f8de25747272f3c32ad2409a | 117,352 |
def generate_bounds_for_fragments(x_size, y_size, move_size, image_dimension):
"""
Generate bounds for fragments, for an image of arbitrary size
Inputs:
x_size - width of the image
y_size - height of the image
move_size - pixels to move (horizontally and vertically) between each ste... | 622bfdfb676dc1ded33e5449c8b591a10d8ee2d1 | 252,678 |
def elapsed(sec):
"""
Formatting elapsed time display
"""
mins, rem = int(sec / 60), sec % 60
text = "%.1f" %(rem)
ending = "s"
if mins > 0:
text = "%d:" %(mins) + text
ending = "m"
return text+ending | 3cb61df21df5343473dadfbce80989407b3cdab4 | 80,661 |
def gen_binding(role, members=None, condition=None):
"""Generate the "bindings" portion of an IAM Policy dictionary.
Generates list of dicts which each represent a
storage_v1_messages.Policy.BindingsValueListEntry object. The list will
contain a single dict which has attributes corresponding to arguments passe... | 54de43c06a5d0886f1b71bd3a3777c5c843e9838 | 241,178 |
import copy
def copy_exc_info(exc_info):
"""Make copy of exception info tuple, as deep as possible."""
if exc_info is None:
return None
exc_type, exc_value, tb = exc_info
# NOTE(imelnikov): there is no need to copy type, and
# we can't copy traceback.
return (exc_type, copy.deepcopy(ex... | 645259c64714053d8c5c9abfe3742352b54b6c68 | 255,389 |
def convert_to_jiant_ep_format(input_path: str):
"""
Converts the TREC-10 Question Classification file into samples for the Question Type Probing task in Jiant format
:return: A list of samples in jiant edge probing format.
"""
DOC_ID = "trec-qt"
samples = []
sample_id = 0
with... | 3a46cbbc4963175a27acf54f4c6e38f165c9f5b9 | 482,613 |
import logging
def get_recording_delay(distance=1.6, sample_rate=48828, play_from=None, rec_from=None):
"""
Calculate the delay it takes for played sound to be recorded. Depends
on the distance of the microphone from the speaker and on the processors
digital-to-analog and analog-to-digital... | 7716794d36bc34856866c0ac6b6c811b3713b515 | 192,940 |
def filter_keras_submodules(kwargs):
"""Selects only arguments that define keras_application submodules. """
submodule_keys = kwargs.keys() & {'backend', 'layers', 'models', 'utils'}
return {key: kwargs[key] for key in submodule_keys} | 4f1ed71131b27dfe9e6c424d2dbbebd1a372d920 | 86,933 |
import time
def mongod_wait_for_primary(mongo, timeout=60, sleep_interval=3):
"""Return True if mongod primary is available in replica set, within the specified timeout."""
start = time.time()
while not mongo.admin.command("isMaster")["ismaster"]:
time.sleep(sleep_interval)
if time.time()... | 926a40611b0202573f1a9dfe07a515f17245eaf7 | 267,105 |
import json
def pretty_print_dictionary(dictionary):
"""Convert an input dictionary to a pretty-printed string
Parameters
----------
dictionary: dict
Input dictionary
Returns
-------
pp: str
The dictionary pretty-printed as a string
"""
dict_as_str = {key: str(va... | 4a30f069f6ae87d968f5865de6df15acb6520c18 | 376,282 |
def train_test_split(tokenized):
"""Returns a train, test tuple of dataframes"""
train = tokenized.query("category != 'title'")
test = tokenized.query("category == 'title'")
return train, test | 749d4c57087422fb2b610bf74ba2909229ef4e12 | 638,079 |
def get_hashtags(tokens):
"""Extract hashtags from a set of tokens"""
hashtags = [x for x in tokens if x.startswith("#")]
return hashtags | ae75465950411e447515a919ed73e303519ed9a6 | 531,876 |
import torch
def reverse_bound_from_rel_bound(batch, rel, order=2):
"""From a relative eps bound, reconstruct the absolute bound for the given batch"""
wavs, wav_lens = batch.sig
wav_lens = [int(wavs.size(1) * r) for r in wav_lens]
epss = []
for i in range(len(wavs)):
eps = torch.norm(wavs... | a8b87a73f4a862b037960baf32ad9565e70cfe84 | 263,425 |
def obb_text2listxy(text):
"""
Purpose: parse x, y coordinates from text of obb(rotbox) annotation in xml
Args:
text: text of obb(rotbox) annotation in xml, "[[x0,y0], [x1,y1], [x2,y2], [x3,y3]]"
Returns: lists of storing x y coordinates,
x: [x0, x1, x2, x3]
y: [y0, y1, y2, y3... | 916a9be1265ee3e1e922703e8ecb1d6c20188bc7 | 435,263 |
def displayhtml (public_key):
"""Gets the HTML to display for reCAPTCHA
public_key -- The public api key"""
return """<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="%(PublicKey)s"></div>""" % {
'PublicKey' : public_key
} | 84e4bf8c5ef36c1c4213e9eefa35882638578fc4 | 671,671 |
from typing import OrderedDict
def filter_resource_dict_sort(d):
"""
Used to sort a dictionary of resources, tuple-of-strings key and int value,
sorted reverse by value and alphabetically by key within each value set.
"""
items = list(d.items())
keyfunc = lambda x: tuple([-x[1]] + list(x[0]))
... | 2f0fcf9692fb8be460b972bced8440788033cce7 | 350,338 |
def IsInstanceV2(instance):
"""Returns a boolean indicating if the database instance is second gen."""
return instance.backendType == 'SECOND_GEN' | ca922402314fa4725d7eb03c713e819a08e4d0b9 | 156,741 |
def complement_residues(ligand_list_full, ligand_list_selected):
"""
Given a list of ligands and a list of ligands selected from the previous list, return the ligands included in
the first but not the second list.
Args:
ligand_list_full: A list of ``List[AnalysisActorClass]`` containing the ful... | 3ab914516421cb3d8e44cf7cb66a31a763aaa3e4 | 417,806 |
def match(first_list, second_list, attribute_name):
"""Compares two lists and returns true if in both there is at least one element which
has the same value for the attribute 'attribute_name' """
for i in first_list:
for j in second_list:
if i[attribute_name] == j[attribute_name]:
... | 2b7c38ef3132c5cb9e693be2995691600ac76ec7 | 14,302 |
import unicodedata
def asciify(string):
"""Convert unicode string to ascii, normalizing with NFKD
Strips away all non-ascii symbols"""
string = unicodedata.normalize('NFKD', string)
return string.encode('ascii', 'ignore').decode('ascii') | e6f61d09e865b3f240a17b66158de68c2dbfc378 | 594,572 |
def get_lomb_lambda(lomb_model):
"""Get the regularization parameter of a fitted Lomb-Scargle model."""
return lomb_model['freq_fits'][0]['lambda'] | 8e4188bf7b4099148a9b10096dc608aa14e3e1af | 126,055 |
def trp(doc,n,pad=['@PAD@']):
"""
Truncates and pads input doc
Arguments:
doc: interable object containing text.
pad: pad sequence e.g. @PAD@
Returns:
truncated and padded document
"""
l=[token for token in doc if token.has_vector]
pad_trunc=list(l[:n])+list(pa... | f5595ab06828aca44d14fb7793fc9b3707c5b7a9 | 362,936 |
def get_locale_and_nickname(account, message):
"""Returns a locale and nickname for the given account and email message."""
if account:
locale = account.locale or 'en'
nickname = account.nickname or account.email
else:
locale = 'en'
nickname = message.sender
return (local... | 2e71ed528a58f483937688559a5da487d288d4d3 | 602,638 |
def int32_to_octets(value):
""" Given an int or long, return a 4-byte array of 8-bit ints."""
return [int(value >> 24 & 0xFF), int(value >> 16 & 0xFF),
int(value >> 8 & 0xFF), int(value & 0xFF)] | 06ea4d1c47b4a99ef9a8ff530b4e5b2d00abd54d | 61,822 |
def ensure_all_alternatives_are_chosen(alt_id_col, choice_col, dataframe):
"""
Ensures that all of the available alternatives in the dataset are chosen at
least once (for model identification). Raises a ValueError otherwise.
Parameters
----------
alt_id_col : str.
Should denote the colu... | 52ad5254951a1ac09a8dc20136494587338063cb | 112,245 |
def _generate_end_sequence(leds: int) -> bytes:
"""
Generate a byte sequence, that, when sent to the APA102 leds, ends a
led update message.
:param leds: number of chained LEDs.
:return: terminating byte sequence.
"""
edges_required = ((leds - 1) if leds else 0)
bytes_required = 0
o... | e5054bfb928a281c660ecdd14450ce189e3b520d | 123,701 |
def sort_feature_value_pairs_list(feature_value_pairs_list):
""" Sorts feature value pairs list.
Args:
feature_value_pairs_list: List of feature value pairs (list in itself)
Returns:
A Feature value pairs list sorted by score descending.
"""
sorted_list = [
sorted(x, key=la... | b11f27c27ba7cd1195adcde0f6c2cdc1cf4a35dd | 367,719 |
def get_total_negative(fp, tn):
"""
This functions returns the number of total negatives.
:param fp: Number of false positives
:type fp: int
:param tn: Number of true negatives
:type tn: int
:return: Number of total negative
:rtype: int
"""
return fp + tn | 296613c0c6c8a8d8a00b9b38abcb9c005a25d702 | 390,165 |
def ly_to_m(ly):
"""
Converts the input distance (or velocity) of the input from light years to meters.
"""
return ly * 9.4607 * 10**15 | 1f2a4e53c9936601901c03ceaab0b258a0059200 | 209,669 |
def valid_index(index, list_dim):
"""
Returns if a given index is valid
considering a list of dimensions list_dim.
"""
for i, ind in enumerate(index):
if not (0<= ind < list_dim[i]):
return False
return True | d54f01fc5e51d618ba8f15c2c9b93b9182b95fce | 354,059 |
def relative_url(value, field_name, url_encode=None):
"""
This snippet comes from the website simpleifbetterthancomplex.com and was made by Vitor Freitas, as part of his
article “Dealing with querystring parameters” (published on 22th 08/2016, read the 12/05/2016)
:param value: the parameter to add to ... | 81eb2212afbea3e95b9e9e63ac324ec421673f25 | 196,931 |
def snake_to_camel(field_name: str) -> str:
"""Convert snake_case to camelCase"""
words = field_name.split('_')
if len(words) < 2:
return field_name
first_word = words[0]
other_words = words[1:]
return first_word + ''.join(word.capitalize() for word in other_words) | 0adf78aa4a10d15c17038eb4a2f58eead2d28020 | 176,670 |
import math
def num_tiles_not_in_position(state):
"""
Calculates and returns the number of tiles which are not in their
final positions.
"""
n = len(state)
total = 0
for row in state:
for tile in row:
try:
y = int(math.floor(float(tile)/n - (float(1)/n))... | 102d2eb616f8b459fc31e68788f355440bac97e0 | 9,912 |
def normalize_images(fixed_image, moving_image):
"""
Noramlize image intensities by extracting joint minimum and dividing by joint maximum
Note: the function is inplace
fixed_image (Image): fixed image
moving_image (Image): moving image
return (Image, Image): normalized images
"""
fixe... | 48bf06a138bb21dacb1708b92819ce415ad0ab3d | 302,576 |
def extract_appendix_from_fname(fname):
"""
Isolate only the appendix, starting from a full fname
:param fname:
:return:
"""
idx_start_pattern = fname.find('q_')
idx_end_pattern = fname.find('.csv')
appendix = fname[idx_start_pattern:idx_end_pattern]
return appendix | 0299c9ce22f089a85f82d1ed2633e08f0d159d9b | 511,893 |
def getInterestedRange(message_context):
"""Return a (start, end) pair of character index for the match in a MessageContext."""
if not message_context.match:
# whole line
return (0, len(message_context.line))
return (message_context.match.start(), message_context.match.end()) | f173a09a7281bb79f20e7658932d1c7f4e5ddd43 | 50,232 |
def peak_list_blank_annotate(dataframe):
"""Blank annotation function for peak_list_annotate"""
if dataframe.iloc[0]["analyte_blank_match"]:
return True
else:
return False | 48499e3e26113fe6c996f65aa0ee5d5a28bc5311 | 510,842 |
def p_correct_given_pos(sens, fpr, b):
"""Returns a simple Bayesian probability for the probability
that a prediction is correct, given that the prediction
was positive, for the prevailing sensitivity (sens),
false positive rate (fpr) and base rate of positive
examples.
"""
assert 0 <= sens... | d4402ddb431dc3fe118468eda37576e730465406 | 517,013 |
import hmac
import hashlib
def validate_signature(key, body, signature):
""" Validate the received signature against the secret key
:param str key: secret key
:param str body: message body
:param str signature: received signature
:return:
:rtype: bool
"""
signature_parts = signature.s... | f3522abb59c4ab07bfbeea51cffb68d2b786e714 | 597,837 |
def is_layer_inside_image(image, layer):
"""
Return True if the layer is inside the image canvas (partially or completely).
Return False if the layer is completely outside the image canvas.
"""
return ((-image.width < layer.offsets[0] < image.width) and
(-image.height < layer.offsets[1] < image.h... | 87987e2e8baf4b2e374fc6cbecc2e2196eb3d0f5 | 155,213 |
def feature_types(df):
"""
Get feature types
Args:
df: pd.DataFrame, input data
Returns:
f_types: feature type
"""
ftypes = {}
ftypes['num_cols'] = [str(x) for x in df.select_dtypes(include=['int32', 'int64', 'float32', 'float64']).columns]
ftypes['cat_cols'] = [str(x) f... | 72f6dfebd159a274e9a8eed5c7ccb6da25c6d8c6 | 576,003 |
def create_yaml_workflow_schema_with_workspace(create_yaml_workflow_schema: str) -> str:
"""Return dummy YAML workflow schema with `/var/reana` workspace."""
reana_yaml_schema = f"""
{create_yaml_workflow_schema}
workspace:
root_path: /var/reana
"""
return reana_yaml_schema | e54c9254d489dc694e33a0dd5b6fbe3255c3e660 | 173,832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.