content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def entity_emiss_o(x, n_lbs, tp, exp_term=2):
"""
The function that calculates the emission prior of entity labels to the non-entity label 'O'
according to the diagonal values of the emission prior
Parameters
----------
x: diagonal values
n_lbs: number of entity labels (2e+1)
tp: turnin... | 34b9473e5799d7beddd20bea81a6fe926b8fde3f | 37,759 |
def mssql_sql_utcnow(element, compiler, **kw):
"""MS SQL provides a function for the UTC datetime."""
return 'GETUTCDATE()' | 5f3fed9f95de23069bd13b6a26cdf21f916a15b7 | 37,764 |
import re
def validate_fs_path(path):
"""Checks if the specified file system path is valid
Arguments:
path {string} -- the file system path to check
Returns:
True if the specified path matches the regex (is a valid path),
False if otherwise
"""
is_valid_path = re.search(r... | c34f451fd3e74167fc6aa1b72862378878da7b6e | 37,769 |
import copy
def get_added_dicts(a, b):
"""Add two dictionaries together, return new dictionary.
if key in B already exists in A, do not override. None destructive.
Args:
a (dict): dictionary you want to ADD to
b (dict): dict you want to add from, the new keys
Returns:
dict: c... | f2a015dddcd1442ec556a71cb13e9da6b2950805 | 37,772 |
def format_uuid(uuid: str):
"""
Returns UUID formatted according to https://tools.ietf.org/html/rfc4122#section-3 (8-4-4-4-12)
Parameters
----------
module_name : str
unformatted UUID
"""
return f'{uuid[0:8]:s}-{uuid[8:12]:s}-{uuid[12:16]:s}-{uuid[16:20]:s}-{uuid[20:32]:s}' | c3383cab2bbcafb9d67c4535c6369f3646faafea | 37,781 |
from typing import List
import re
def extract_cve_references(text: str) -> List[str]:
"""
Extract CVE identifiers
"""
return [result.group(0) for result in re.finditer(r"CVE-\d{4}-\d{4,8}", text)] | 8d32525bc04077a418e3f9fd334ab4e8dd905376 | 37,789 |
import math
def ordinal(n):
"""Output the ordinal representation ("1st", "2nd", "3rd", etc.) of any number."""
# https://stackoverflow.com/a/20007730/404321
suffix = "tsnrhtdd"[(math.floor(n / 10) % 10 != 1) * (n % 10 < 4) * n % 10::4]
return f'{n}{suffix}' | fa7f5cadd1c684e048a1bf1557014e37ad69c930 | 37,790 |
def parse_string(string, *, remove):
"""
Return a parsed string
Args:
:string: (str) string to parse
:remove: (list) characters to remove
Returns:
:parsed_string: (str) parsed string
"""
parsed_string = string
for char in remove:
parsed_string = parsed_str... | 641feb61ff5ad918fefe14b618863e4b5164ddbf | 37,791 |
def build_message(history_record, game):
"""Builds the endpoint message from the game and current history record"""
msg = ""
if history_record[0].result == 'Good guess':
msg += "Good guess! | "
else:
msg += "Wrong guess... | "
msg += game.current_game + " | "
msg += "Strike(s) l... | ff3c9dd193de67f1879a4ffe3e9f859993bdef6f | 37,794 |
def decompose_two(p):
"""Decomposes p into p - 1 = q * 2^s
Args:
p: an integer representing a prime number
Results:
p: an integer representing q above
k: an integer representing the exponent of 2
"""
k = 0
while p % 2 == 0:
k += 1
p //= 2
... | 19934989b53707c836c1fb6864365c1828800229 | 37,795 |
def create_node(id, shape, size, label):
"""Auxiliary function that creates a Node in Vis.js format
:return: Dict with Node attributes
"""
node = {
"id": id,
"shape": shape,
"size": size,
"label": label,
"color": {"background": "#FBD20B"},
}
return node | 007c3d1d42e981aa378664683903caecc898c7c6 | 37,801 |
from typing import Union
import torch
from typing import Tuple
from typing import Any
from typing import Optional
from typing import Dict
from typing import List
def split_non_tensors(
mixed: Union[torch.Tensor, Tuple[Any, ...]]
) -> Tuple[Tuple[torch.Tensor, ...], Optional[Dict[str, List[Any]]]]:
"""
Spl... | 9b63e940bccd4e0bfabe618d2986d11f3b16ef93 | 37,804 |
def split_url(url):
"""Splits the given URL into a tuple of (protocol, host, uri)"""
proto, rest = url.split(':', 1)
rest = rest[2:].split('/', 1)
host, uri = (rest[0], rest[1]) if len(rest) == 2 else (rest[0], "")
return (proto, host, uri) | 67b09e52d2e3e321d5f1d1effb7f2ac5163e3d29 | 37,808 |
def underscorify(name):
"""Replace ``-`` and ``/`` with ``_``."""
return name.replace("-", "_").replace("/", "_") | a5dcddb62119ea5863522cdffcbc44dc7381a0d6 | 37,809 |
import re
def is_date_index(index):
"""
Checks whether the index is of the agreed upon date format.
In this case YYYY.MM.DD. This is a very 'EU' centric date.
Would have preferred YYYY-MM-DD which is more ISO, however
there are dates which exist in the 'EU' format already (topbeat).
Note that... | b53bb6a58350d6ada8e5fce91c6191296bb93c15 | 37,811 |
from typing import TextIO
from typing import Dict
def parse_percepta_txt_output(
result_file: TextIO, offset: int = 0
) -> Dict[str, Dict[str, str]]:
"""
Parses text output file from perceptabat_cv.
Returns a nested dictionary {compound ID: {property name: value}}.
"""
parsed_output = {}
... | 030af92661e38c7f8e84164639c2bb82da71485c | 37,813 |
def mapValue(value, minValue, maxValue, minResultValue, maxResultValue):
"""
Maps value from a given source range, i.e., (minValue, maxValue),
to a new destination range, i.e., (minResultValue, maxResultValue).
The result will be converted to the result data type (int, or float).
"""
# check if value... | 339268c09e99db9294dc1c30871b6c03f9fca776 | 37,814 |
def opt_bool(opt):
""" Convert bool ini strings to actual boolean values
"""
return opt.lower() in ['yes', 'y', 'true', '1'] | 9f321363cb96b08a122c9437c028cbe142de5881 | 37,815 |
def read_length(data):
"""Read length from a list of bytes, starting at the first byte.
Returns the length, plus the number of bytes read from the list.
EMV 4.3 Book 3 Annex B2
"""
i = 0
length = data[i]
i += 1
if length & 0x80:
length_bytes_count = length & 0x7F
length ... | 79ebf734ff863a567727ef0469e37f74327ee6e0 | 37,825 |
def parse_range(s):
"""Parse a string "a-b" describing a range of integers a <= x <= b, returning the bounds a, b."""
return tuple(map(int, s.split("-"))) | b17314dc729bec8130384a71ee10cf32e60da9c1 | 37,828 |
def get_page_id(title, query_results):
"""
Extracts the title's pageid from the query results.
Assumes queries of the form query:pages:id,
and properly handle the normalized method.
Returns -1 if it cannot find the page id
"""
if 'normalized' in query_results['query'].keys():
for nor... | 8ddce8c95b4a312b7478dc53d5b3a7fb53bba39e | 37,830 |
def get_gt(variant_call):
"""Returns the genotypes of the VariantCall.
Args:
variant_call: VariantCall proto. The VariantCall for which to return GTs.
Returns:
A list of ints representing the genotype indices of this call.
"""
return variant_call.genotype | 865c1954d24c43ee5545dc0f477e66eba8c22a46 | 37,831 |
def find_video_attachments(document_attachments):
"""This function identifies any attached videos in a collection of document attachments.
:param document_attachments: Attachments associated with a document
:type document_attachments: list, dict
:returns: A list of dictionaries containing info on any v... | 471e0366279711784d0b628cbd38527e5f15c836 | 37,839 |
def getBytesSize(bytesIn=0, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
bytesValue = bytesIn
if bytesValue is None or 0:
return int(0)
elif (isinstance(bytesValue, int) or isinstance(bytesValue, float)) and (in... | 1e6e2ad83a13ddc0cd35f82925f7617c09e229dc | 37,841 |
def _CreateChartStats(loss_stats):
"""Creates the Chart object to interface with Google Charts drawChart method.
https://developers.google.com/chart/interactive/docs/reference#google.visualization.drawchart
Args:
loss_stats: A dictionary of years paired to square meters.
Returns:
A Python dictionary ... | 384623ad5cd3c3ee81cf25c00402bd8d65396f59 | 37,842 |
def extract_channel_platform(url):
"""Returns last two elements in URL: (channel/platform-arch)
"""
parts = [x for x in url.split('/')]
result = '/'.join(parts[-2:])
return result | 73c71ed879f07e8eedf2730db174e1cb81177276 | 37,844 |
def is_same_class(obj, a_class):
"""return true if obj is the exact class a_class, otherwise false"""
return (type(obj) == a_class) | 029b12b101b53cc960f72994ae082df5f0fd9d0e | 37,845 |
import hashlib
import six
import base64
def CalculateMd5Hash(file_path):
"""Calculate base64 encoded md5hash for a local file.
Args:
file_path: the local file path
Returns:
md5hash of the file.
"""
m = hashlib.md5()
with open(file_path, 'rb') as f:
m.update(f.read())
return six.ensure_text(... | 2a24ce3dd4f6e5f9d9a5d9be5632e6d481fd690b | 37,851 |
def read_connection_data_from_external_file(filepath, separator="="):
"""Reads SQL server connection information from an external file.
Keeping this information external is potentially important for security reasons.
The format of this file should be:
server = [server_name]
database = [database_name]
Arguments... | f12a659f302f7a8252f29673fa916b6ac997663f | 37,852 |
import json
def load_filename(loc: str) -> dict:
"""Open a filename, parse it as JSON."""
with open(loc) as fh:
return json.load(fh) | 9b8984926573dbcbff16a7fcee4b20e5e85fe6e0 | 37,853 |
def lin_poly_solve(L, M):
"""
Return the point defined as the intersection of two lines
(given as degree-one polynomials in some field).
"""
x0,x1,x2 = M.parent().gens()
a0 = L.coefficient(x0)
a1 = L.coefficient(x1)
a2 = L.coefficient(x2)
b0 = M.coefficient(x0)
b1 = M.coefficient... | 5ebacff94b80dd4b1b54ac7742d0c9a37db596c8 | 37,854 |
def toRGB(hex_color_str):
"""
transform hex color string to integer tuple.
e.g. r,g,b = toRGB('0xFFFFFF')
"""
return int(hex_color_str[2:4],16)/255., int(hex_color_str[4:6],16)/255., int(hex_color_str[6:8],16)/255. | 5821d5f0d42d1a53982eb81739fe81e47d75fa23 | 37,855 |
def lookup_object(spec):
"""
Looks up a module or object from a some.module:func_name specification.
To just look up a module, omit the colon and everything after it.
"""
parts, target = spec.split(':') if ':' in spec else (spec, None)
module = __import__(parts)
for part in parts.split('.')... | e09c30d1cf3f523b790208dec60ec9fc1a309b1d | 37,856 |
def default(d, k, i, default=None):
"""Returns d[k][i], defaults to default if KeyError or IndexError is raised."""
try:
return d[k][i]
except (KeyError, IndexError):
return default | c48c57b7698f23e075d45043917e2427e1b39c2d | 37,858 |
def line_1d(x, slope, offset):
"""Return the value of a line with given slope and offset.
Parameters
----------
x : float or iterable of floats
The x-value to calculate the value of the line at.
slope : float
The slope of the line. Must be finite.
offset : float
The y-of... | 9befd9fdd13db12e27be4e000501c09a51c231e8 | 37,860 |
def decimal_all_finite(x_dec_list):
"""Check if all elements in list of decimals are finite.
Parameters
----------
x_dec_list : iterable of Decimal
List of decimal objects.
Returns
-------
y : bool
True if all elements are finite.
"""
y = all(x.is_finite() for x in ... | 610f95d7022047a8b020d5af48ceb3923d168e5d | 37,877 |
def coord_shift180(lon):
"""Enforce coordinate longiude to range from -180 to 180.
Sometimes longitudes are 0-360. This simple function will subtract
360 from those that are above 180 to get the more user-friendly
[-180, 180], since slicing is a lot easier.
Parameters
----------
lon: nump... | cdf4ccbfc0e0dbb0201012826b88720934231d32 | 37,881 |
def temperature_over_total_temperature(
mach,
gamma=1.4
):
"""
Gives T/T_t, the ratio of static temperature to total temperature.
Args:
mach: Mach number [-]
gamma: The ratio of specific heats. 1.4 for air across most temperature ranges of interest.
"""
return (1 + (... | a1fea37f80df9eff21716f273b6270cfa7fcd302 | 37,882 |
from functools import reduce
def words_in_chapters(chapters: list) -> list:
"""
Returns all words in the given chapters, without any special characters (no punctuation or quotation characters)
:param chapters: Chapter objects
:return: all words in the given Chapters as a list of words
"""
ret... | ef30472d3096f7b5cf58cab2ab7bdeed41c9fa85 | 37,885 |
import json
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the res... | d3cdff425da3a7a01369ae89890d1d00ab7fe000 | 37,888 |
def slices_overlap(slice_a, slice_b):
"""Test if the ranges covered by a pair of slices overlap."""
assert slice_a.step is None
assert slice_b.step is None
return max(slice_a.start, slice_b.start) \
< min(slice_a.stop, slice_b.stop) | db9cfc0dcfa64f6c7c52f2410a140088f9d03b13 | 37,890 |
def get_requirements(fname):
"""
Extracts requirements from requirements-file <fname>
"""
reqs = open(fname, "rt").read().strip("\r").split("\n")
requirements = [
req for req in reqs
if req and not req.startswith("#") and not req.startswith("--")
]
return requirements | 1b091b89cf6835f544560eb8e2235d9bb02f2952 | 37,892 |
def camelcase(name):
"""Converts a string to CamelCase.
Args:
name (str): String to convert.
Returns:
str: `name` in CamelCase.
"""
return ''.join(x.capitalize() for x in name.split('_')) | 2a0052d52faf1aabb45ae9909f76482c927ba395 | 37,901 |
def completed(lines):
"""
Check if the output file shows successful completion
"""
return lines[-1][:14] == 'TOTAL RUN TIME' | 2dcb9ff850086f4e7496a46a82c510297f0488d6 | 37,905 |
import torch
import random
def create_sample_batch(speaker_data, batch_size, vector_dim):
"""
Return torch tensors ((input1, input2), target) for siamese
network training (for mutual information).
Constructs each batch to have roughly equal amount of target
and non-target samples to keep training... | 71edfa9f239b84a8414a645d391330f929cd2e2d | 37,909 |
import six
def safe_shadow(text):
"""
Shadow string to first and last char
:param text:
:return:
>>> safe_shadow(None)
'None'
>>>safe_shadow("s")
'******'
>>>safe_shadow("sssssss")
's******s'
>>> safe_shadow(1)
'******'
>>> safe_shadow([1, 2])
'******'
"""... | 46d63b4a598bbc45ae32335e105539f7c43f1c9e | 37,910 |
def _merge_notebooks_feedback(notebook_ids, checksums):
"""
Returns a list of dictionaries with 'notebook_id' and 'feedback_checksum'.
``notebook_ids`` - A list of notebook IDs.
``checksum`` - A dictionary mapping notebook IDs to checksums.
"""
merged = []
for nb_id in notebook_ids:
... | 6e45fa2f5889b94b9dd6e0164ab7554e284fa3b9 | 37,912 |
import random
def generate_random(power: int) -> list:
"""
Generate list with 2 ** power random elemnts.
"""
array = [random.random() for i in range(2 ** power)]
return array | b822277c6f4ca0a28339ef2feddfcec485e4d686 | 37,918 |
def findmax(L):
"""
>>> L1 = [ 1, 4, 5, 10 ]
>>> findmax(L1)
10
>>> L2 = [ 1, 3, 9, 33, 81 ]
>>> findmax(L2)
81
"""
return max(L) | 3fbb99b5189ee8a4a4867642ec4ebc73f06c04f0 | 37,920 |
def dayOfWeek(julian):
"""Get day of week from a julian day
:param `julian`: the julian day
:returns: the day of week as an integer and Monday = 1
"""
return int((julian + 1) % 7) | 0aa478cb8d597097a73f998cb6d4de128a06611c | 37,922 |
def recall(tp_count, targets_count):
"""Calculates recall.
:param tp_count: Number of true positives.
:param targets_count: Number of targets.
:return: The recall rate.
"""
if targets_count == 0:
return 0.0
else:
return tp_count / float(targets_count) | 985c5c4567c9be12e4bd248d2a3054a2def1f29f | 37,926 |
def intersect_interval(interval1, interval2):
"""Computes the intersection of two intervals.
Parameters
----------
interval1: tuple[int]
Should be `(x1_min, x1_max)`
interval2: tuple[int]
Should be `(x2_min, x2_max)`
Returns
-------
x_intersect: tuple[int]
Should be the intersection. If th... | 5db8daefa083b680c89a970224e2fc67a07beb5e | 37,928 |
def get_order_by_from_request(request):
"""
Retrieve field used for sorting a queryset
:param request: HTTP request
:return: the sorted field name, prefixed with "-" if ordering is descending
"""
sort_direction = request.GET.get("dir")
field_name = (request.GET.get("sort") or "") if sort_di... | 9324e8e03bb8b5a48cd37f3daf6807712b57ad97 | 37,933 |
def turn_strat_into_label(stratum):
"""
Convert age stratification string into a string that describes it more clearly.
Args:
stratum: String used in the model
Returns:
label: String that can be used in plotting
"""
if 'up' in stratum:
return stratum[4: -2] + ' and up'
... | fb2ce3810359a150948905913ba48e7627875769 | 37,934 |
def diff(prev_snapshot, next_snapshot):
"""Return a dict containing changes between two snapshots."""
snapshot_diff = {
'left_only': [],
'right_only': [],
'changed': [],
'common': [],
}
for path in set(prev_snapshot.keys()) | set(next_snapshot.keys()):
if path i... | 040be0018e4b517cfc884a1e4a0f9cc030032fa9 | 37,936 |
def make_table_row(contents, tag="td"):
"""Given an iterable of string contents, make a table row.
Args:
contents: An iterable yielding strings.
tag: The tag to place contents in. Defaults to 'td', you might want 'th'.
Returns:
A string containing the content strings, organized into a ta... | 346301a77954829f6869a47ace6c1de52d787ffa | 37,938 |
def typical_price(data, high_col='High', low_col='Low', close_col='Close'):
"""
Typical Price
Source: https://en.wikipedia.org/wiki/Typical_price
Params:
data: pandas DataFrame
high_col: the name of the HIGH values column
low_col: the name of the LOW values column
close_c... | 3c47cb01d4bd02351269f00c394d73abca862bc8 | 37,940 |
def get_family_name_from(seq_name_and_family):
"""Get family accession from concatenated sequence name and family string.
Args:
seq_name_and_family: string. Of the form `sequence_name`_`family_accession`,
like OLF1_CHICK/41-290_PF00001.20. Assumes the family does not have an
underscore.
Returns:... | d75d48c72ebee14ef43edf9d0ab42b2f85999713 | 37,943 |
from bs4 import BeautifulSoup
def extract_html_links(text):
"""
Grab any GOV.UK domain-specific links from page text.
:param text: Text within a details sub-section, refer to filtered for keys.
:return: list of links
"""
links = []
try:
soup = BeautifulSoup(text, "html5lib")
... | c7debea7ef2b3c8d239cde39b40913d9f141d3fb | 37,946 |
def pow(a, b):
"""
Finds a^b using recursion.
Params:
a (float) - Base
b (int) - Exponent
Returns:
Value of a^b (float)
"""
if(type(b) != int):
print("ERROR: pow() not callable with doubles!")
return 0
if(b == 0):
return 1
else:
return a * pow(a... | e903a8a430453cc57460a124a2485b7de57473e2 | 37,948 |
def twr(rors):
"""The Time-Weighted Return (also called the
Geometric Average Return) is a way of calculating
the rate of return for an investment when there are
deposits and withdrawals (cash flows) during the period.
You often want to exclude these cash flows so that we can
find out how well t... | d9346efca7f8db311643818a8f13f30ab0ee12f5 | 37,951 |
def NoEmbedding(X):
"""Return X without changes."""
return X | c33dd4175999dab4eb3568753f8d4980c809b294 | 37,952 |
def bytes_split(bytes_, length):
"""Split bytes into pieces of equal size."""
n_pieces, excess = divmod(len(bytes_), length)
if excess:
raise ValueError('Bytes of length {} cannot be equally divided into '
'pieces of length {}'.format(len(bytes_), length))
return [bytes_... | 7c70146e4ebbef70371e7cfb3ce3a1abe6df3c97 | 37,955 |
def diamag_correction(H, H0, Mp, Mpp, m_sample, M_sample, Xd_sample, constant_terms=[], paired_terms=[]):
"""
Calculates a diamagnetic correction of the data in Mp and Mpp and calculates
the corresponding values of Xp and Xpp
Input
H: amplitude of AC field (unit: Oe)
H0: strength of applied... | 6b29fd46ff6fd2457b6b3572efc544c3d84956c1 | 37,956 |
def rearange_base_link_list(table, base_link_index):
"""Rarange base link to beginning of table"""
value = table[base_link_index]
del table[base_link_index]
table.insert(0, value)
return table | 08d94b515d6c1e1fcaf47fecdda7816d7fcb6470 | 37,963 |
import html
def decode_html_entities(v):
"""Decodes HTML entities from a value, converting them to the respective
Unicode characters/strings."""
if isinstance(v, int):
v = str(v)
return html.unescape(v) | 852fa968ab99e0618eb1d845b6ef74322e137a42 | 37,964 |
def exe_success(return_code: int) -> bool:
"""Check if **return_code** is 0
Args:
return_code (int): Return code of a process.
Returns:
bool: True if return code is equal to 0
"""
return return_code == 0 | cfea5a87f750c3629714832cb0758fcd3c18ad9a | 37,966 |
def extract_pairs_from_lines(lines):
"""Extract pairs from raw lines."""
collected_pairs = []
for i in range(len(lines) - 1):
first_line = lines[i].strip()
second_line = lines[i+1].strip()
if first_line and second_line:
collected_pairs.append([first_line, second_line])
... | 071d75bf422fa2ef61daff301837c85c0e0f3af6 | 37,967 |
def _replace_nan_with_none(
plot_data,
plot_keys):
"""Replaces all instances of nan with None in plot data.
This is necessary for Colab integration where we serializes the data into json
string as NaN is not supported by json standard. Turning nan into None will
make the value null once parsed. The vis... | 887fff7f110945f8444f5ffec205828edf63f1f6 | 37,968 |
def bytearray_to_long(byte_array):
"""
Converts a byte array to long.
:param byte_array:
The byte array.
:returns:
Long.
"""
total = 0
multiplier = 1
for count in range(len(byte_array) - 1, -1, -1):
byte_val = byte_array[count]
total += multiplier * byte_val
multiplier *= 256
... | 7dee1685dacd7e693a6cc50bf0ac704f78aa42bd | 37,974 |
def identity(*args):
"""
Return whatever is passed in
"""
return args if len(args) > 1 else args[0] | f0f1276beb43a13c49311974013caa330588e734 | 37,975 |
def WordStartWithUppercase(word):
"""Return whether a word starts with uppercase letter"""
if len(word) == 0:
return False
firstChar = word[0]
return firstChar == firstChar.upper() | 71b775fa9168abac586470e2a454194ce9103efe | 37,976 |
def heading_level(line):
"""Return heading level of line (1, 2, 3, or 0 for normal)"""
for i in range(4):
if line[i] != '#':
return i
return 3 | 47a21dd52d827b33dc467c02a31ce16c85b2b41b | 37,980 |
def validate_sequence_length(sequence):
"""
Validates that the sequence passed into it has a minimum length of 100 n.t.
"""
try:
assert len(sequence) >= 100
return True
except AssertionError:
return False | 3f9aecbd050e52a6d264a4753acc4215e6227c9e | 37,985 |
def obtain_valid_painter(painter_class, **kwargs):
"""Returns a valid painter whose class is <painter_class>. You can try any
argument you want ; only arguments existing in painter's __init__ method
will be used.
"""
try:
painter = painter_class(**kwargs)
except TypeError:
painte... | 259f36dc3f75de608dfb53c3db23cf018df07adb | 37,997 |
def percent_diff(value1: float, value2: float, frac: bool = False) -> float:
""" Return the percentage difference between two values. The denominator
is the average of value1 and value2.
value1: float, first value
value2: float, second value
frac: bool, Default is ... | cffe298fb4218adc60bf75ff659090c41ae86922 | 37,999 |
def scheduler(epoch):
"""
Learning rate scheduler
"""
lr = 0.0001
if epoch > 25:
lr = 0.00001
elif epoch > 60:
lr = 0.000001
print('Using learning rate', lr)
return lr | c65e57cc31926c4eb911c312e709f3209102e92a | 38,002 |
def occurs_once_in_sets(set_sequence):
"""Returns the elements that occur only once in the sequence of sets set_sequence.
The elements are returned as a set."""
occuronce = set()
deleted = set()
for setx in set_sequence:
for sety in setx:
if (sety in occuronce):
d... | 21344df038bf3af83584a9a1ef2dda1d6642af72 | 38,003 |
def allow_guess(number):
"""
Input: Takes in the number which the user is to guess
Gets user input and tells the user whether the number is too high
or too low
Returns false if the guess is wrong and True if correct
"""
print('Guess a number')
guess = input()
guess = int(guess)
... | be3f97b8118c6a80bf0cc907fcc946bf89f0e9a0 | 38,009 |
def check_def_file(universe, res_name, atoms_name):
"""Check if atoms from the definition file are present in the structure in `universe`.
This function return false if there is one missing in the structure.
Print also an error message.
Parameters
----------
universe : MDAnalysis universe inst... | f2cff1286aca9a3be7e71b1d2f2d5cd810a93838 | 38,010 |
import re
import logging
def GetChromeosVersion(str_obj):
"""Helper method to parse output for CHROMEOS_VERSION_STRING.
Args:
str_obj: a string, which may contain Chrome OS version info.
Returns:
A string, value of CHROMEOS_VERSION_STRING environment variable set by
chromeos_version.sh. Or None ... | d0dc48eb6c5f9c501024f155535e6e9adb1061c0 | 38,011 |
def JavaFileForUnitTest(test):
"""Returns the Java file name for a unit test."""
return 'UT_{}.java'.format(test) | 6a524204c50084188b5144ba10434b586f2bc735 | 38,012 |
def get_descendant(node, desc_id):
"""Search the descendants of the given node in a scipy tree.
Parameters
----------
node : scipy.cluster.hierarchy.ClusterNode
The ancestor node to search from.
desc_id : int
The ID of the node to search for.
Returns
-------
desc : scip... | 99e081b2ee8dce513aad8fccbadb6cd94a017365 | 38,014 |
def length(x):
"""Calculate the length of a vector.
This function is equivalent to the `length` function in GLSL.
Args:
x (:class:`~taichi.Matrix`): The vector of which to calculate the length.
Returns:
The Euclidean norm of the vector.
Example::
>>> x = ti.Vector([1, 1, ... | bab7dfde88c3cb7d9dc4a2f697dfe2443e9acabd | 38,017 |
import hashlib
def hash_csv(csv_path):
"""Calculates a SHA-256 hash of the CSV file for data integrity checking.
Args:
csv_path (path-like) : Path the CSV file to hash.
Returns:
str: the hexdigest of the hash, with a 'sha256:' prefix.
"""
# how big of a bit should I take?
bl... | 690c7c281d6c2f74c37195462f89dc75bf227fc1 | 38,018 |
import requests
def retrieve_info(url, apidata):
"""
Return a dictionary from the HTSworkflow API
"""
web = requests.get(url, params=apidata)
if web.status_code != 200:
raise requests.HTTPError(
"Failed to access {} error {}".format(url, web.status_code))
result = web.jso... | c30cdc0bc8b556062195da0dc43d836446652a6b | 38,020 |
def pvct(pv: float, compr_total: float):
""" Pore Volume times Total Compressibility
Parameters
---
pv : float
pore volume
compr_total : float
total compressibility
Return
pvct : float
pore volume total compressibility
"""
return pv*compr_total | 31c84e4dc94cb2f1c78c9e26ba02cec4c81f0800 | 38,022 |
def format_datestr(v):
""" Formats a datetime or date object into the string format shared by xml and notation serializations."""
if hasattr(v, 'microsecond'):
return v.isoformat() + 'Z'
else:
return v.strftime('%Y-%m-%dT%H:%M:%SZ') | 3f149e3babf7703281583d5b31b56e2b1d261fcb | 38,024 |
def betterFib(n):
"""
Better implementation of nth Fibonacci number generator
Time complexity - O(n)
Space complexity - O(n)
:param n: The nth term
:return: The nth fibonnaci number
"""
fib = [None] * n
#print fib
if n == 0:
return 0
elif n == 1:
return 1
... | 9374446b2f63943862b5b07c24d087c0083b319f | 38,025 |
def top_level(symbol):
"""A rule that matches top-level symbols."""
return (symbol and ('.' not in symbol)) or None | 71a80314e80e2242d7b505a19939e26eb060dded | 38,026 |
def _seq_id_filter(id: str) -> str:
"""
Replaces underscores and semicolons with dashes in the sequence IDs.
This is needed to have nice output filename templates with underscore
as a delimiter for parameters
"""
result = id.replace("_", "-")
return result.replace(";", "-") | e6355b1f94e76d255a1052072706619299ea4b51 | 38,028 |
import hashlib
def _md5_hash_as_long(input_value):
"""Return the hash of the input value converted to a long."""
hex_hash = hashlib.md5(str(input_value).encode('utf-8')).hexdigest()
return int(hex_hash, 16) | 748cf6d783a17f07c3ea25280b9faae3d76211be | 38,032 |
def _get_name(f):
"""Gets the name of underlying objects."""
if hasattr(f, '__name__'):
return f.__name__
# Next clause handles functools.partial objects.
if hasattr(f, 'func') and hasattr(f.func, '__name__'):
return f.func.__name__
return repr(f) | c6f5c35b004afea321d981b5db9dd7be52b5efa6 | 38,036 |
def if_none(obj, default):
"""
Returns `obj`, unless it's `None`, in which case returns `default`.
>>> if_none(42, "Hello!")
42
>>> if_none(None, "Hello!")
'Hello!'
"""
return default if obj is None else obj | fd851c9eb1eaa0048e3a0ac2d45b15fb208080a3 | 38,043 |
def _swiftmodule_for_cpu(swiftmodule_files, cpu):
"""Select the cpu specific swiftmodule."""
# The paths will be of the following format:
# ABC.framework/Modules/ABC.swiftmodule/<arch>.swiftmodule
# Where <arch> will be a common arch like x86_64, arm64, etc.
named_files = {f.basename: f for f in ... | 59e978f22f4b1959ef32b0f2d68b0d92ec7fabe0 | 38,046 |
from typing import Dict
def get_bags_inside(color: str, dependency_dict: Dict[str, Dict[str, int]]) -> int:
"""Recursively count the bags stored wthin color, including itself"""
count = 1
inner_bags = dependency_dict[color]
for bag_color, bag_count in inner_bags.items():
count += bag_count * g... | b97da4a194d3aba89f7eec9ac684812e139d116b | 38,052 |
def pick(seq, func, maxobj=None):
"""Picks the object obj where func(obj) has the highest value."""
maxscore = None
for obj in seq:
score = func(obj)
if maxscore is None or maxscore < score:
(maxscore, maxobj) = (score, obj)
return maxobj | 707f9534fdec3b66bd311238689e2fe8e3456fbd | 38,060 |
from typing import BinaryIO
from typing import List
def _create_test_file(tfile: BinaryIO, nlines=10) -> List[str]:
"""Helper function for populating a testing temp file with numbered example lines for comparison"""
lines = [f"This is an example line {i}\n".encode('utf-8') for i in range(1, nlines+1)]
tfi... | 4eac8c5e351c415ddc5734fa93e7e2aed0e61e2e | 38,061 |
import ntpath
import base64
def send_file(path, filename=None, mime_type=None):
"""
Convert a file into the format expected by the Download component.
:param path: path to the file to be sent
:param filename: name of the file, if not provided the original filename is used
:param mime_type: mime ty... | efd32f249f292ec5e15924b6e30f5b107029e90b | 38,062 |
import re
def extract_bibtex_items(latex_source):
"""Extract all bibtex items in a LaTeX file which are not commented out."""
bibtex_item_regex = re.compile(r"""(?<!%) # Lookbehind to check that the bibtex item is not commented out.
(\\bibitem{.*?}.+?) # Match the entire bibt... | 995a9d9559a6da564af010254fd466a8b729beb2 | 38,065 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.