content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def _setup_filetree_for_priority_test(tmp_path: Path) -> Path:
"""
root
└─ dir_1
└─ dir_1_1
└─ file_1.py
Returns: path for file_1.py
"""
root_dir = tmp_path / 'root'
root_dir.mkdir()
dir_1 = root_dir / 'dir_1'
dir_1.mkdir()
dir_1_1 =... | a7feb4ce8f8265ee590bbeff6e7a11c64b21ae08 | 654,899 |
def simple_incorrect_scan_and_codes(simple_scan):
"""
Return a scan and error codes, representing a small mesh which produces a
couple of known requirement and advisory statements, and the relevant
statement codes.
Errors as follows:
mesh missing cf_role (but identified from datavar) --> R1... | ce72a6c736a0e8bc1de29e8877ad05b32b13daed | 654,900 |
def key(request) -> int:
"""Get instance key."""
return request.param | 09a31f43493f65165fc8dcf32e555966d17c7e53 | 654,901 |
def derive_table_from(source):
"""Ease the typical use case /somewhere/TAB.txt -> TAB.json."""
table = source.stem.upper()
return table, f'{table}.json' | 08f364d70750c887915ca8464fe76fb09e7687d8 | 654,903 |
def remove_alignments(group, min_length: int=1000, min_coverage: float=0.2):
"""
Since MUMmer aligns sections of a sequence, it can produce multiple regions
of alignment for a given sequence. We filter out low alignments using this
function.
Args:
group: A pandas group_by group.
... | 1bc5bd3d5da0a03e4b8fbf46b123f696f61174ab | 654,904 |
import functools
def require_owner(message=None):
"""Decorate a function to require the triggering user to be the bot owner.
If they are not, `message` will be said if given."""
def actual_decorator(function):
@functools.wraps(function)
def guarded(bot, trigger, *args, **kwargs):
... | dfd6f692a3816bb7e5e8498d10462928eb52ea09 | 654,905 |
import socket
def ip_sort_key(ip_address):
"""Get a sort key for an IPv4 or IPv6 address"""
if ':' in ip_address:
# IPv6
return b'6' + socket.inet_pton(socket.AF_INET6, ip_address)
# IPv4
return b'4' + socket.inet_aton(ip_address) | de8632eb66c40f4a9237ffc35757b6fdf5ce879c | 654,917 |
def lha2scale(lha):
"""Extract the high scale from a dictionary eturned by pylha from
a DSixTools options file."""
return dict(lha['BLOCK']['SCALES']['values'])[1] | a633e64d4cc523f31105b33aef929cb7bed73c12 | 654,918 |
def generate_dot(dc):
"""
Generates a dot format graph of docker-compose depends_on between services
:param dict dc: Docker comppose configuration loaded as a python dict
:rtype: string
"""
lines = []
lines.append("digraph docker {")
for service_name, service in dc["services"].items():
... | 6b9fcfbb939e779593b1e559065ab7daa1a4ba28 | 654,919 |
def find_mirror_next(seq, max_window_size, mirror_centre):
"""Find the next token that will lead to a mirror pattern.
Searches in the range of `window_size` tokens to the left from the
`mirror_centre` if it's found.
E.g., in [a, b, AND, a] the next token should be 'b' to create a mirror
pattern.
... | 9631878ce09032c3f38405db90b1ee022698c045 | 654,926 |
import requests
def exchange_code_for_token(code, token_url, client_id, client_secret, redirect_uri):
"""exchange a OAuth2 authorization code for an access token
https://docs.github.com/en/free-pro-team@latest/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github
Para... | 56e16585ef80c361a27bd22e88132a327a8e6bf8 | 654,929 |
def query(query_string, data):
"""
Return a query string for use in HTML links. For example, if
query_string is "?page=foo" and data is "date=200807" this function
will return "?page=foo&date=200807" while if query_string were "" it
would return "?date=200807".
"""
if query_s... | a779834da9cea1d913dc88f5909dcaee1f35231c | 654,930 |
def return_item(item, key, silently=False):
"""Depending of the type of item, return the value corresponding to `key`
or the attribute `key` of the object item.
Args:
item (dict or object): Python object to explore
key (str): key to search in the object
silently (bool, optional): wh... | 3d79845db67bbad68b26480c89a64a0ee4d94815 | 654,931 |
import json
def typeforms_embed(url, selector, options={}, mode='widget'):
"""Embed a typeforms form.
Parameters
----------
url : str
Typeform share typeform_url.
selector : str
CSS selector to place typeform_id into.
options : dict, str
Accepts a dictionary or JSON as... | d4ef65c43b9ebe52664aecf03f6d4553741522b8 | 654,934 |
def de_dup_and_sort(input):
"""
Given an input list of strings, return a list in which the duplicates are removed and the items are sorted.
"""
input = set(input)
input = list(input)
input.sort()
return input | ed3bd85a7544e1121fcf31a3c83c0b9e6f77f229 | 654,936 |
def get_volume(shade_client, name_or_id, filters=None):
"""Get a volume by name or ID.
:param name_or_id: Name or ID of the volume.
:param filters: A dictionary of meta data to use for further filtering.
:returns: A volume ``munch.Munch`` or None if no matching volume is found.
"""
return shad... | dd98d3437e18b2e9db1e587452dacf57ab2ef75b | 654,939 |
def generate_group_by_range_and_index_str(group_by, data_str, value_str,
index_str):
"""
Generate the range and index string for GROUP BY expression.
Args:
group_by (str): the column name to be grouped.
data_str (str): a string that represents the t... | b3c12081747e644c1a9f5e331305846db727fc1e | 654,942 |
def compute_xi_t(return_t, risk_free_rate, sigma_t):
"""
Compute innovation xi at time t as a function of return t, rf rate, and sigma t
"""
return return_t - risk_free_rate + 1/2 * sigma_t | f123d4e7f786455edde7b1f0cf33eb51f64910f4 | 654,945 |
def _cholesky_solve(M, rhs, dotprodsimp=None):
"""Solves ``Ax = B`` using Cholesky decomposition,
for a general square non-singular matrix.
For a non-square matrix with rows > cols,
the least squares solution is returned.
Parameters
==========
dotprodsimp : bool, optional
Specifies... | 20be045035367b1144cdae5fc7cd4618a45cacb6 | 654,948 |
def rstrip(val: str) -> str:
"""Remove trailing whitespace."""
return val.rstrip() | 2b844784420cd0a41e4dc46bcfb229a48d720b01 | 654,949 |
def intprod(xs):
"""
Product of a sequence of integers
"""
out = 1
for x in xs:
out *= x
return out | ba4b32876a07044b14f1af34e1f0488c30cf2d3b | 654,951 |
def safe_float(val):
"""
Convert the given value to a float or 0f.
"""
result = float(0)
try:
result = float(val)
except (ValueError, TypeError):
pass
return result | 1da3879fb93a5d8bf0cde98b5032e211743866fe | 654,952 |
import requests
def get_html(url, session_obj=None, headers=None):
"""
Request to the server and receiving a response,
in the form of an html code of a web page.
"""
try:
request = session_obj if session_obj else requests
response = request.get(url, timeout = 5, headers=headers)
... | 80bc1ba9babbebde0b6fef61c21ac008b484789b | 654,953 |
def _MetadataMessageToDict(metadata_message):
"""Converts a Metadata message to a dict."""
res = {}
if metadata_message:
for item in metadata_message.items:
res[item.key] = item.value
return res | a68ea5fcd46ce110f247bd8e60dc068acd8a6210 | 654,956 |
from pathlib import Path
def get_abs_path_from_here(relative_path: str, calling_file_name: str) -> Path:
"""
return absolute path to file, based on path from the calling location
:param calling_file_name: optional name of the calling script that will serce as reference
:param relative_path: relative p... | 5dab7f30b67d7e574d929b630a97c482e4584ac8 | 654,957 |
def lerpv3(a,b,t):
"""linear interplation (1-t)*a + (t)*b"""
return ( (1-t)*a[0] + (t)*b[0], (1-t)*a[1] + (t)*b[1], (1-t)*a[2] + (t)*b[2] ) | f82021ccfd0f71abfec6d7c724e03a4a400ed6bd | 654,959 |
def get_venv_name(dockenv_name):
"""
Helper function to split the user-defined virtual env name
out of the full name that includes the dockenv tag
:param dockenv_name: The full name to pull the virtual env name
out of
"""
# Format of tage name if dockenv-**NAME**:latest... | addc198d36b50b61fb2db5bad5de8af86cd54a7c | 654,962 |
from pathlib import Path
from typing import Optional
from typing import List
import uuid
def make_metakernel(kernel_dir: Path, kernels: Optional[List[str]] = None) -> Path:
"""Create a uniquely-named SPICE metakernel in ``kernel_dir`` and return its path. If ``kernels`` is `None`, this
function searches ``ker... | b60bc7d68d5de76b720d346d5fff13990dae5828 | 654,965 |
def _Aij(A, i, j):
"""Sum of upper-left and lower right blocks of contingency table."""
# See `somersd` References [2] bottom of page 309
return A[:i, :j].sum() + A[i+1:, j+1:].sum() | 97f1153876d21cad8d7cba45877605d7326c96e3 | 654,967 |
from typing import Callable
from typing import Any
def get_func_name(
func: Callable[..., Any],
prepend_module: bool = False,
repr_fallback: bool = False,
) -> str:
"""Extract and return the name of **func**.
A total of three attempts are performed at retrieving the passed functions name:
1.... | b09b04796483170a84798127344d97401fdd4419 | 654,968 |
def mimic_case(old_word, new_word):
"""
>>> print(mimic_case('EtAt', 'état'))
ÉtAt
"""
if len(old_word) != len(new_word):
raise ValueError("lengths don't match")
return ''.join([
new_word[i].upper() if old_word[i].isupper() else new_word[i].lower()
for i in range(len(old_... | c4ca9536a6e2f6fb5d6c4f512ed86172810cd07e | 654,969 |
def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" ") -> list:
""" Convert text to word list
:param text: test list
:param filters: filter rules, filter all punctuation marks, tabs, newlines, etc. by default
:param lower: whether to convert text to lowerc... | 36f52f40baff004d926ae58658fe596b72b65603 | 654,971 |
def phase(x):
"""Returns 1 if the input is even and -1 if it is odd. Mathematically equivalent to (-1)^x"""
if x % 2 == 0:
return 1
else:
return -1 | a8307b21b598bec33fd9fb05719addf7127872ef | 654,972 |
def calculate_chunk_slices(items_per_chunk, num_items):
"""Calculate slices for indexing an adapter.
Parameters
----------
items_per_chunk: (int)
Approximate number of items per chunk.
num_items: (int)
Total number of items.
Returns
-------
list of slices
"""
a... | fd42f9be9149d7a59498e17bb76329a8e96a6ae7 | 654,976 |
import math
def rotate_point(x,y,theta):
"""Rotate a point around the origin by an angle theta.
Args:
x (float): x coordinate of point.
y (float): y coordinate of point.
theta (float): rotation angle (rad).
Returns:
list: [x,y] coordinates of rotated point.
"""
"... | 5b2aa1fd7240e9cb1164849c6da3c1333cba67d2 | 654,978 |
def iterable(obj):
"""Utility to check if object is iterable"""
try:
iter(obj)
except:
return False
else:
return True | e39525f0da629dea5af15c5fb85869930c9ca99b | 654,979 |
import pathlib
def zcoord(path:pathlib.Path) -> float:
"""
Return the putative Z coordinate for a image file path name
"""
return int(path.name.split(".")[0]) / 10 | fc8363fad50ca4eaecfca900198bde1e6550a505 | 654,982 |
from pathlib import Path
def can_override(path: Path, override: bool) -> Path:
"""Check if it's allowed to override a `path`.
Args:
path: path, where we are going to write
override: permission to override flag
Returns:
The input `path`to facilitate chaining in mapping in code.
... | c727f2fff98324564408d919c098f08d2f545bf4 | 654,985 |
def isLarger(ser1, ser2, fractionTrue=1.0, startIdx=0):
"""
Checks that arr1[startIdx:] > arr2[startIdx:]
Parameters
----------
ser1: pd.Series
ser2: pd.Series
fractionTrue: float in [0, 1]
startIdx: int
Returns
-------
bool
"""
numTrue = sum(ser1.loc[startIdx:] > s... | 6969938694c2a62d113cb215a0e3efb2d0262d62 | 654,987 |
import glob
from itertools import chain
from typing import Iterable
def poly_iglob(filenames_or_patterns: Iterable, *, recursive=True, ignore_case=True):
"""
Read sequence of file names with or without wildcard characters.
Any wildcards are replaced by matching file names using glob.iglob().
:param f... | ed95d6949bb8cb287a4015b157d31206eb60c94f | 654,988 |
from typing import Iterable
from typing import Sequence
def report_invalid_whitelist_values(
whitelist: Iterable[str], items: Sequence[str], item_type: str
) -> str:
"""Warns the user if there are entries in ``whitelist`` which don't
correspond to any item in ``items``. Helps highlight typos.
"""
... | a7ad1007abdaa88dea9ff2ef90194e9490998f12 | 654,991 |
def _count_of_curr_and_next(rule):
"""Count tokens to be matched and those to follow them in rule."""
return len(rule.tokens) + len(rule.next_tokens or []) + len(rule.next_classes or []) | 8005128554a40ee53156c2dcafbd7b223bbbf430 | 654,992 |
def get_charge(lines):
""" Searches through file and finds the charge of the molecule. """
for line in lines:
if 'ICHRGE' in line:
return line.split()[2]
return None | 913ec1403cdf1dba5ad4b549b61cec23d3546dc7 | 654,993 |
def tvi(b3, b4, b6):
"""
Transformed Vegetation Index (Broge and Leblanc, 2001).
.. math:: TVI = 0.5 * (120 * (b6 - b3) - 200 * (b4 - b3))
:param b3: Green.
:type b3: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b6: Red-edge 2.
:type b6: numpy.ndar... | f7681f078e33386e5c946d33befa605a0c8e14df | 654,994 |
from typing import Callable
def _derive_template_name(view_function: Callable) -> str:
"""Derive the template name from the view function's module and name."""
# Select segments between `byceps.blueprints.` and `.views`.
module_package_name_segments = view_function.__module__.split('.')
blueprint_path... | 117ab8058eac4c199e7e688a35011cd0c650f62d | 654,995 |
def count_incident_type(incidents, type):
"""
Gets total number of incidents of a certain type
:param incidents: dictionary -- set of incidents to parse
:param type: string -- key to parse within incidents
:return: int -- total incidents
"""
total = 0
for _, incident in incidents.item... | 8981fd0f3ac25f7647d3882f287d7d15cdadb70f | 654,998 |
def load_data(path):
""" Load input data from a given path. Data is stored as word,label\nword,label\n ...
:param path: path to file
:return: (list of words, list of labels)
"""
words = []
labels = []
with open(path, encoding='utf-8') as f:
lines = f.read().splitlines()
for ... | 4526eea8fb0dc9782123d2b64d6c023b6e527f3d | 655,001 |
from typing import List
def get_clabe_control_digit(clabe: str) -> int:
"""Generate the checksum digit for a CLABE.
:param clabe: CLABE.
:return: The CLABE checksum digit.
"""
factors = [3, 7, 1]
products: List[int] = []
for i, digit in enumerate(clabe[:17]):
products.append((int... | 3df768c43c6643480aaec9505e8ae464d7aba66e | 655,004 |
def _getcalday(instcal, date):
"""
Get index of row for current night in instrument calendar table.
"""
for i in range(len(instcal['date'])):
if instcal['date'][i] in date:
return i
print('\n Date '+date+' not found in instrument configuration calendar.')
raise ValueError('Da... | 97dfa39d43197ec567fcea41a4f1545e7db045b6 | 655,008 |
def comp(DNA: str, pat_len: int) -> list:
"""Sort all substrings of pat_len length
:param DNA: the string to pull substrings from
:type DNA: str
:param pat_len: the length of substrings to pull
:type pat_len: int
:returns: all substrings, sorted
:rtype: list (of strs)
"""
if not DN... | 04cddfb893fe1e4b0b03d9997b53ac80b8f6e606 | 655,009 |
def get_model_config(ckpt_path):
"""Returns the model configuration to be used with each checkpoint."""
config = {
'audio_backbone': 'resnet50',
'audio_model_kwargs': {
'bn_config': {
'create_offset': True,
'create_scale': True,
'decay_rate': 0.9,
... | 2e55faea2e1c578c4c9dcc3166076dd6d0fac4e7 | 655,010 |
def get_single_value(group, name):
"""Return single value from attribute or dataset with given name in group.
If `name` is an attribute of the HDF5 group `group`, it is returned,
otherwise it is interpreted as an HDF5 dataset of `group` and the last value
of `name` is returned. This is meant to retriev... | 4bd6ff890ece8a4fc0c94fb67caa8ae111c574df | 655,011 |
import typing
def lane_offset_width_meters(shape: typing.Sequence[int],
poly_evals: typing.Tuple[typing.List[float], typing.List[float]],
xm_per_pix: float) -> typing.Tuple[float, float]:
"""Calculate center-offset of the lane, given polynomial curves for ... | b41479d72240f5f1ffc6364e9805024a0dab5d59 | 655,017 |
def z_inverse(x, mean, std):
"""The inverse of function z_score"""
return x * std + mean | fc283bb11bc1109759e34cd26eb21cd24e453c4d | 655,018 |
def get_product_images(product):
"""Return list of product images that will be placed in product gallery."""
return list(product.images.all()) | 64108e6ba906f9fcafd16af172c2af9f34d2eb20 | 655,021 |
import random
def choose_between_by_p(l1, l2, p, count):
"""
Choose `count` elements from `l1` (w/ prob `p`) and `l2` (w/ prob `p`-1).
"""
assert 0 <= p
assert p <= 1
return [random.choice(l1) if random.random() <= p else random.choice(l2) for _ in range(count)] | 0a47c256db8a7d57654377ecf69cef6afcf49b5a | 655,022 |
def mol_file_basename(tag):
"""Covert a tag into a molecular data file name"""
return 'c%06d.' % tag | 95ba73740de6cf283fea5a84adc79732c65bb7b8 | 655,026 |
def python_trailing(n):
"""Count the number of trailing zero bits in abs(n)."""
if not n:
return 0
t = 0
while not n & 1:
n >>= 1
t += 1
return t | 2b595e183d95e22eb9f801d008bca318c60958e7 | 655,032 |
import torch
def flip_segment(X_spikes, segment):
"""
Flips the values of a segment in X_spikes format
:param X_spikes: spiking input data from spike generator
:param segment: segment in X_spikes to be flipped
:return: spiking data with flipped segment
"""
_, (d, t_start, t_end) = segment
... | 4c3421ce9a7c3da5b44b5af3477f872c23766122 | 655,034 |
def valueFactory(zeroValue, elemValue):
"""
Return elemValue converted to a value of the same type as zeroValue.
If zeroValue is a sequence, return a sequence of the same type and length,
with each element set to elemValue.
"""
val = zeroValue
typ = type(val)
try:
# If the type i... | 60ab7618fb7fee65a03033269499c12efc8c6091 | 655,035 |
def tts_version(version):
"""Convert a version string to something the TTS will pronounce correctly.
Args:
version (str): The version string, e.g. '1.1.2'
Returns:
str: A pronounceable version string, e.g. '1 point 1 point 2'
"""
return version.replace('.', ' point ') | 2c01d0ce7a72f162f43193bb41a4bb52f15c3fac | 655,036 |
def to_sec(d=0, h=0, m=0, s=0):
"""Convert Day, Hour, minute, seconds to number of seconds."""
secs = d*86400
secs += h*3600
secs += m*60
secs += s
return secs
################## | 423b314377b59b250309cb4957379c63f7d4173f | 655,041 |
def alpha_for_N(comps,Influx=10,Outflux=1000):
"""calculates alpha based on required outflux for given influx"""
c=(Outflux/Influx)**(1/float(comps))
alpha_sol= (c-2)/(c-1)
return alpha_sol | 4532f6c8f32f54960562c8d6763d5051fb5b2567 | 655,044 |
def _created_on_to_timestamp_ms(created_on):
"""
Converts the Message CreatedOn column to a millisecond timestamp value.
CreatedOn is number of 100 nanosecond increments since midnight 0000-01-01.
Output is number of millisecond increments since midnight 1970-01-01.
"""
return created_on / 1000... | 30ba13c0d45b2850a266a05024f37ea3aa3b6cdd | 655,047 |
from typing import List
def left(lst: List[int], idx: int) -> int:
"""Return left heap child."""
left_idx = idx * 2 + 1
if left_idx < len(lst):
return left_idx
else:
return -1 | 4a8424fd3cd40eb278bd637779cf8d7c7d8162ea | 655,048 |
from datetime import datetime
def outputSPDX(doc, spdxPath):
"""
Write SPDX doc, package and files content to disk.
Arguments:
- doc: BuilderDocument
- spdxPath: path to write SPDX content
Returns: True on success, False on error.
"""
try:
with open(spdxPath, 'w') as f... | 8659c3091b41665082d0c1af7e5f54a86c7e0150 | 655,050 |
def write_nonequilibrium_trajectory(nonequilibrium_trajectory, trajectory_filename):
"""
Write the results of a nonequilibrium switching trajectory to a file. The trajectory is written to an
mdtraj hdf5 file.
Parameters
----------
nonequilibrium_trajectory : md.Trajectory
The trajectory... | 158bc16eacfd945a77ce50ac1819b852b3a3f3d4 | 655,051 |
import random
def random_IP() -> str:
"""
Get random IP
"""
ip = []
for _ in range(0, 4):
ip.append(str(random.randint(1, 255)))
return ".".join(ip) | f96527bc72bcf06658e4acc2a6298ec8d9716823 | 655,052 |
import hashlib
def compute_checksum(path, algorithm: str) -> str:
""" Generates a hex digest using specified algorithm for a file. """
buffer_size = 65536
hash_builder = hashlib.new(algorithm)
with open(path, 'rb') as f:
while True:
data = f.read(buffer_size)
if not d... | b98188f5e487884b84ec43dbd0757c3add59c432 | 655,053 |
def rev_bit_str(n: int, bitlen: int) -> int:
"""
Reverses the bitstring of length bitlen of a number n and returns the
bitreverses integer. I.e. rev_bits(3, 4) => "0011" => "1100" => 12
"""
bits = bin(n)[2:] # Truncate first 2 characters to avoid '0b'
start_pow = bitlen - len(bits)
return s... | 1899d2e20968b225ec32be58a7fb3bd9488fcd20 | 655,054 |
def pattern_count(pattern, text):
"""
The number of times that a pattern appears as a substring of text.
Args:
pattern (str): the substring pattern to find in the given text.
text (str): the string space for looking.
Returns:
String, number of substring pattern that appears in ... | 367a82213a60585d1f22343c702de2f21aa33180 | 655,058 |
def sort_seconds(timestamps):
"""
Sorts a list of 2-tuples by their first element
"""
return sorted(timestamps, key=lambda tup: tup[0]) | 0c66b2e8d3a7360afd7d49d62bdda477820b8329 | 655,060 |
def all_nums(table):
"""Returns True if table contains only numbers
Precondition: table is a (non-ragged) 2d List"""
cnt = 0
number_cnt = 0
for row in table:
for item in row:
cnt += 1
if type(item) in [int, float]:
number_cnt += 1
if cnt != number_... | 0721406eedda5040d39e373557540a00a14ee133 | 655,065 |
def e(parameters, p, r_v):
"""
Returns an expression for the partial pressure of water vapour
from the total pressure and the water vapour mixing ratio.
:arg parameters: a CompressibleParameters object.
:arg p: the pressure in Pa.
:arg r_v: the mixing ratio of water vapour.
"""
epsilon... | 99b4ab64689547366b0a6b903408a60e237d3aba | 655,070 |
from typing import Dict
from typing import Any
def check_is_legacy(sample: Dict[str, Any]) -> bool:
"""
Check if a sample has legacy read files.
:param sample: the sample document
:return: legacy boolean
"""
files = sample["files"]
return (
all(file.get("raw", False) is False for... | 8fab1d1e1e448d534817f0971239a72cadbd7ba4 | 655,073 |
def genotype_likelihood_index(allele_indices):
"""Returns the genotype likelihood index for the given allele indices.
Args:
allele_indices: list(int). The list of allele indices for a given genotype.
E.g. diploid homozygous reference is represented as [0, 0].
Returns:
The index into the associated... | 646cdfa8e895480d7f7bd022461721ebf68af60d | 655,078 |
import re
def text_area_extractor(text):
"""
Textbox extractor function to preprocess and extract text
Args:
text: Raw Extracted Text from the News Article
Returns:
text: Preprocessed and clean text ready for analysis
"""
text = text.lower()
text = re.sub(r'[^a-zA-Z0-9\s]',... | 202168bb6763b96b93aec51821cc13a1bf697f5e | 655,080 |
import calendar
import time
def time_string_to_unix(time_string, time_format):
"""Converts time from string to Unix format.
Unix format = seconds since 0000 UTC 1 Jan 1970.
:param time_string: Time string.
:param time_format: Format of time string (example: "%Y%m%d" or
"%Y-%m-%d-%H%M%S").
... | 1b091a425b9bd16ff0dcc8f7e4acbd6980ee1252 | 655,082 |
import click
def read_user_variable(var_name, default_value):
"""Prompt the user for the given variable and return the entered value
or the given default.
:param str var_name: Variable of the context to query the user
:param default_value: Value that will be returned if no input happens
"""
#... | c731ed7313924f00b4117fda451f87cbcf50a463 | 655,089 |
def gvariant(lst):
"""Turn list of strings to gvariant list."""
assert isinstance(lst, list), "{} is not a list".format(lst)
content = ", ".join(
"'{}'".format(l) for l in lst
)
return '[{}]'.format(content) | fb98a4996981c9f20622cedb0c6e7eab11c1572f | 655,100 |
def compss_open(file_name, mode='r'):
# type: (str, str) -> object
""" Dummy compss_open.
Open the given file with the defined mode (see builtin open).
:param file_name: The file name to open.
:param mode: Open mode. Options = [w, r+ or a , r or empty]. Default=r.
:return: An object of 'file' ... | 040668276c54cb2799a36d639cfc2da2605b9677 | 655,103 |
def can_view_cohorts(user):
"""To access Cohort views user need to be
authenticated and either be an admin, or
in a group that has the 'view cohorts' permission."""
return user.is_authenticated and user.has_perm('release.view_releasecohort') | 23c13e604e78a53e1a130a5bb12430d058276770 | 655,111 |
from typing import Counter
import math
def conditional_entropy(x, y):
"""
Calculates the conditional entropy of x given y: S(x|y)
Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy
:param x: list / NumPy ndarray / Pandas Series
A sequence of measurements
:param y: list / NumPy ... | 56af850404476a213222d2100737e708cf9ab4ca | 655,112 |
def evaluate_error(model, test_gen, no_test_sam):
"""
DESCRIPTION: Evaluate the network performance
INPUT: The trained model, the test set generator,
number of testing images
OUTPUT: List of statistics about the performance of the model
"""
stats = model.evaluate_generator(test_gen, no_test_... | d76fcc9fffeee3bb79d399f728b8cb35432ec2e9 | 655,116 |
import torch
def get_valid_negative_mask(labels):
"""
To be a valid negative pair (a,n),
- a and n are different embeddings
- a and n have the different label
"""
indices_equal = torch.eye(labels.size(0)).byte()
indices_not_equal = ~indices_equal
label_not_equal = torch.ne(labels.unsqueeze(1), labels.unsqu... | 08c408ad4cec3ee2367b6224aaabf397f2c8eea1 | 655,118 |
def compoundInterestFutureValue(p, r, c, n):
"""Compound interest future value
Returns: future value
Input values:
p : principal
r : interest rate
c : number of compounding periods in a year
n : (c * t) , total number of compounding periods
"""
fv = (p * (1 + (r / c))) **... | 19f865d29c8dd541b7aba5e043babc81828340db | 655,119 |
def signature(self):
"""
Returns the signature of the quadratic form, defined as:
number of positive eigenvalues - number of negative eigenvalues
of the matrix of the quadratic form.
INPUT:
None
OUTPUT:
an integer
EXAMPLES:
sage: Q = DiagonalQuadraticForm(Z... | b87114af527ae465a5f686ee403da357fc8e3115 | 655,123 |
def rgb_to_hex(r, g, b):
"""
Convert RGB color to an Hexadecimal representation
"""
return "%02x%02x%02x" % (r, g, b) | 4f5edefa2a1137e910b7cf20041667e59b04f700 | 655,124 |
def binary_lookup(index, offsets):
"""
Given a character index, look up the index of it in the offsets. This will
be the number at which the next index is greater
"""
bottom = 0
top = len(offsets) - 1
if index > offsets[top]:
return top
while top - bottom > 1:
mid = ... | 924a24d8bbcba135911c58ff0ad166a352c7e137 | 655,128 |
import random
def snp(sequence):
"""
Function takes a sequence string and introduces a single nucleotide polymorphism (SNP)
Randomly finds an index in the string and replaces the value at the index with a new
letter from the given alphabet. If the value is the same as the previous value, the
funct... | 37ad64080b02d36d204efa0fe18265aee12bb258 | 655,133 |
import csv
def load_training3(infile):
"""Load training data with normalized unigram count, hamming distance, and
query length.
Args:
infile: file name to load data from
"""
X = []
Y = []
with open(infile, 'r') as f:
reader = csv.reader(f)
for row in reader:
if reader.line_num == ... | 317d0e82781539ca7089c5552249104000d69715 | 655,134 |
def compute_whitespace(d):
"""Calculates the percentage of empty strings in a
two-dimensional list.
Parameters
----------
d : list
Returns
-------
whitespace : float
Percentage of empty cells.
"""
whitespace = 0
r_nempty_cells, c_nempty_cells = [], []
for i in ... | 9b137632654f54ba1fedfdc12dfca7f430b45679 | 655,135 |
import time
import torch
from typing import OrderedDict
def load_model(model, model_file, is_restore=False):
"""Load model.
:param model: created model.
:param model_file: pretrained model file.
:param is_restore: set true to load from model_file.
"""
t_start = time.time()
if isinstance(m... | c949d44b6099c417f00e688f7f2bc12746963ca1 | 655,137 |
import re
def camel_case(words):
"""Convert a noun phrase to a CamelCase identifier."""
result = ''
for word in re.split(r'(?:\W|_)+', words):
if word:
if word[:1].islower():
word = word.capitalize()
result += word
return result | 4707e5c48f803c78ebd08a2b3099bc5b25cab0df | 655,138 |
def key(profile):
"""Get a sorting key based on the lower case last name, then firstname"""
components = profile["name"].lower().split(" ")
return " ".join([components[-1]] + components[:-1]) | 3615e439a249065eb5c428f417d7b4d0aa311d68 | 655,139 |
def insertion_sort(A, reverse = False):
"""Assumes A is a list of integers, by default reverse = False
Returns the sorted A in non-decreasing order if reverse = False,
and in non-increasing order if reverse = True.
****************************************
The complexity of the algorithm... | 01898d6f7836f3fdfd8be3a7d49becd9a1186cee | 655,141 |
import random
import json
def _retrieve_quote(json_filename):
"""
Retrieve a random quote entry from json_filename, very quickly,
without loading the entire file into memory
:param str json_filename: Name of .json file to open
:return: Tuple of the form: (str(quote_text), str(quote_author))
... | 5c36e812e9219acc7fabc6483f6773abfa76e473 | 655,149 |
def compute_overdose_deaths(run, start_year, end_year, config, intervention):
"""Compute number of opioid overdose deaths from start_year to end_year.
Parameters
----------
run: whynot.dynamics.Run
Run object produced by running simulate for the opioid simulator
start_year: int
... | 308959e39e99e10bc78728bd262d47b7c16b17cc | 655,152 |
def sequential_search(target, lyst):
"""
in()
顺序搜索
Returns the position of the target item if found, or -1 otherwise.
:param target:
:param lyst:
:return:
"""
position = 0
while position < len(lyst):
if target == lyst[position]:
return position
positio... | 9a686606dd70b95568a016f4155c6b9ae55efca0 | 655,157 |
def check_obs(idx, obs):
"""Check every term in every sequence of obs and see if any term is >= idx
or < 0. If true, return false. Otherwise return true.
"""
for o in obs:
for term in o:
if (term >= idx) or (term < 0):
return False
return True | d61086d5a90e794b284edd530c0f3a72e9cf49ab | 655,160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.