content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def file_or_filename(input):
"""Open a filename for reading with `smart_open`, or seek to the beginning if `input` is an already open file.
Parameters
----------
input : str or file-like
Filename or file-like object.
Returns
-------
file-like object
An open file, positioned... | e23faac638ba7adab92640f9785b190de9ece09a | 77,514 |
def _get_channels(image):
"""Get the number of channels in the image"""
return 0 if len(image.shape) == 2 else image.shape[2] | 3c7fb1e76252af7f396bcc055fbdb1cc75c66606 | 77,515 |
def missing_int(array: list):
"""given array return the missing integer in the continuous sequence
the following algorithm provides the missing integer in O(N) time
"""
full_sum = (len(array) + 1) * len(array) / 2
array_sum = sum(array)
return int(full_sum - array_sum) | 7f3602424a05e8f90a3cc2a8dc9218463cdac9bc | 77,518 |
def find_largest_true_block(arr):
"""
Given a boolean numpy array, finds the starting and ending indices
for the largest continuous block of """
start_index = -1
max_start_index = -1
max_length = -1
length = -1
i = 0
is_in_block = False
while i < len(arr):
if arr[i] and n... | f55d5a473fd5ca6c032e5ca4e4be3c6e6a07d8c3 | 77,520 |
def str2list_row(row):
"""
convert str to list in a row.
"""
row = row.strip('\n') # delete '\n'.
row = row.strip('\r') # delete '\r'.
row = row.split(',')
return row | 167ae610a45f2a41fd778ea020ff802769649a59 | 77,522 |
def suspensionDE(Y, t, m, c, k):
"""
Colin Simpson's code...
But the beautiful docstring is all mine
Y: array_like
contains initial conditions
t: array_like
time values
m: float
mass parameter
c: float
damping coeffcient parameter
k: float
spring constant parameter
"""
return [... | c1a58c3479002abb1ccc9e252f5e7c454c8b5d85 | 77,524 |
import re
def regex_negative_match(pattern, value):
"""
Return False if the regex is "negative" and is a complete match for the
supplied value, True otherwise.
"""
if pattern[0] != '~':
# this is a positive regex, ignore
return True
return not re.match(pattern[1:] + '\Z', value... | 6282f21818d9792cfc2aceff00f71e861ad49695 | 77,526 |
import time
def shell_sort(array: list) -> tuple:
"""
Return sorted list, name of sorting method, number of comparisons
and execution time using Shell Sort method
"""
name = "Shell sort"
comparisons = 0
array_length = len(array)
start = time.time_ns()
h = array_length // 2
whil... | 25b4a467e652157d2c46a37fdcedd7b623179013 | 77,531 |
def _to_int(x):
"""Converts a completion and error code as it is listed in 32-bit notation
in the VPP-4.3.2 specification to the actual integer value.
"""
if x > 0x7FFFFFFF:
return int(x - 0x100000000)
else:
return int(x) | de155dce733dc93c3112d5bbc10f0dbc20110978 | 77,536 |
def sum_unit_fractions_from(m, n):
"""
What comes in: Two positive integers m and n with m <= n.
What goes out: Returns the sum:
1/m + 1/(m+1) + 1/(m+2) + ... + 1/n.
Side effects: None.
Examples:
-- sum_unit_fractions_from(6, 9) returns
1/6 + 1/7 + 1/8 + 1/9
whic... | a27aeebc8a452afcaeb72aae947721ba9ad84020 | 77,541 |
def commands_match(user_command, expected_command):
"""
Checks if the commands are essentially equivalent after whitespace
differences and quote differences.
Returns:
match: boolean
True if the commands appear to be equivalent.
"""
def normalize(command):
return comman... | e0b8632f7e815c306fc8d68d01e26aae3d9f15ab | 77,542 |
def get_form_field(form, field_name):
"""
Return a field of a form
"""
return form[field_name] | 76b16c4084e8c129d31ab4b75c27e66ecd934e15 | 77,544 |
def add_survey(surveys, new_survey):
"""
Add survey to list of surveys then reorder list base on MD, survey list is list of tuples (md, inc, azm, *).
surveys parameter is existing list. new_surveys parameter is survey to be added. new_surveys should
be tuple of (md, inc, az). Brute force method for now ... | 596cc9eef0b9a0057e0c077b10a2800c2df7f2fe | 77,546 |
from typing import List
import click
def list_options(options: List) -> int:
"""
This is a utility for click (cli) that prints of list of items as a numbered
list. It prompts users to select an option from the list.
For example, `["item1", "item2", "item3"]` would print...
```
(01) item1
... | 62253091f6c05b688c4d8cb62d9ef81021c3bcb0 | 77,547 |
import json
def load_dataset(path_dataset):
"""Load dataset from a JSON file
Args:
path_dataset (str): file path to a dataset
Returns:
list: list of features's dictionary
"""
with open(path_dataset, 'r', encoding='utf-8') as fd:
dataset = json.load(fd)
return dataset | 9449df4ea30c94b5af3ef62e96c685c2ae5af7b7 | 77,549 |
def correct_max_relative_intensity(replicate_mass_peak_data):
"""Check that the max peak is 100%.
If not, find largest peak, set to 100% and apply correction factor to other peak intensities.
"""
max_average_relative_intensity = 0
max_intensity_mass = 0
max_intensity = 0
for replicate_mass... | 2ccadb5bf798f824b7a537629ffd7f807d6c1483 | 77,551 |
def compress(speakers, talks):
"""Reduce consecutive dialogue by the same person into single records"""
i = 0
current_text = ""
current_speaker = ""
compressed_speakers = []
compressed_talks = []
for speaker, text in zip(speakers, talks):
if speaker == current_speaker:
... | 23e70d879bac9d8f5c4224c9eeb86c2338a91be0 | 77,555 |
from typing import Dict
from typing import Union
from typing import Tuple
from typing import List
import torch
def get_flatten_inputs(
model_inputs: Dict[str, Union[Tuple, List, torch.Tensor]]
) -> Dict[str, torch.Tensor]:
"""This function unwraps lists and tuples from 'model_inputs' and assigns a
unique ... | 2ddea01cdff5eddea3d8a55b53e216500315158a | 77,557 |
def provider_names(providers):
"""
Returns the names of the given Provider instances.
"""
return [p.provider_name for p in providers] | 3479909a7ef94a398b6c1784a23d79307f219904 | 77,559 |
def read_plain_vocabulary(filename):
"""
Read a vocabulary file containing one word type per line.
Return a list of word types.
"""
words = []
with open(filename, 'rb') as f:
for line in f:
word = line.decode('utf-8').strip()
if not word:
continue
... | 3c83c5813b206147a5a4130d8fa1b9a4ffe57d85 | 77,560 |
def is_valid_host(host):
""" Check if host is valid.
Performs two simple checks:
- Has host and port separated by ':'.
- Port is a positive digit.
:param host: Host in <address>:<port> format.
:returns: Valid or not.
"""
parts = host.split(':')
return len(parts) == 2 or par... | e7d22558e8a41b3b3345e863e11cdeec1a37d984 | 77,561 |
def cmpExonerateResultByQueryAlignmentStart(e1, e2):
"""Comparator function for sorting C{ExonerateResult}s by query alignment start.
@param e1: first exonerate result
@type e1: C{ExonerateResult}
@param e2: second exonerate result
@type e2: C{ExonerateResult}
@return: one of -1, 0 or 1
@rtype: C{int}
"""
if e... | 633779c2f95282978ed5a807ba743d261937653f | 77,565 |
import math
def pixel_coords_zoom_to_lat_lon(PixelX, PixelY, zoom):
"""
The function to compute latitude, longituted from pixel coordinates at a given zoom level
Parameters
----------
PixelX : int
x coordinate
PixelY : int
y coordinate
zoom : int
tile map service z... | 021e000c22a10cf3bb3dd0642a02be136db3484c | 77,572 |
def get_firing_cells(df, cells, min_firing_frequency=1):
"""
Only returns the cells that fire over a certain frequency
(across entire recording)
:param df:
:param cells:
:param min_firing_frequency: in hz
:return: Cells that meet the criteria
"""
total_time = df.index.max() - df.inde... | e3c77433152d9c478c1bc4e3b3c31be338b36763 | 77,574 |
def pkcs7_unpad(text):
"""
删除PKCS#7方式填充的字符串
:param text:
:return: str
"""
# 每个填充值等于填充序列的长度
return text[: -text[-1]] | 33bb33355eaca5ebf3b5a7ea2c678d30bffc1512 | 77,577 |
import random
def mockify(text: str):
"""
Randomizes character case in a string.
:param text: Text to randomize case on
:return: str
"""
return ''.join(random.choice((str.upper, str.lower))(x) for x in text) | 4119cd2aa154de12eb7c2391f65af7feee37e919 | 77,578 |
def flip_cost(variant, target_value):
"""Returns cost of flipping the given read variant to target_value."""
if variant.allele == target_value:
return 0
else:
return min([x for x in variant.quality if x !=0]) | 6eb0e776d9e894218adb57ceaee831d0428eff60 | 77,580 |
import math
def circularity (
area: float,
perimeter: float
) -> float:
""" Calculates the circularity shape factor with given area and perimeter.
Args:
area (float):
area of a shape
perimeter (float):
length of the perimeter of a shape
Returns... | a481aea8788c0ae0b844bfcb076d5eb842f96860 | 77,581 |
def encode_time(time):
""" Converts a time string in HH:MM format into minutes """
time_list = time.split(":")
if len(time_list) >= 2:
return (int(time_list[0]) * 60) + int(time_list[1])
return 0 | 938f0eba5dbbf2b8e61eeeddd249eb605bc618fd | 77,582 |
from typing import Dict
from typing import List
from typing import Set
import functools
import operator
def reshape_meta(o: Dict[int | str, int]) -> List[Set[int]]:
"""Convert the CSV data to sets
Parameters:
- `o`: `Dict[int | str, int]`, data to be converted
Returns: `List[Set[int]]`
- The f... | 33e634d464f5673dbc76920ebfb5f20686f1b484 | 77,584 |
def binary_search(dep_times_list, start_time):
"""
Function representing the binary search algorithm, from a list of ordered
values (departure times) chooses value equal or closest (higher) to given
parameter
Parameters
----------
dep_times_list: list of ordered datetime objects
start_ti... | 4a756d70df2ab372ea2b3c55267fb7e7b71f6903 | 77,585 |
def gi(arr, index, default=None):
"""Get the index in an array or the default if out of bounds."""
if index >= len(arr):
return default
return arr[index] | 8755973e9c0c49b0af67d6ee0a62caf00f1ea98b | 77,586 |
import ntpath
def _path_leaf(path: str) -> str:
"""
Return the leaf object of the given path.
:param path: directory path to parse
:return: leaf object of path
"""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head) | 6053adea690b129024e3760ebe352573b17dd43b | 77,588 |
def head(list1: list) -> object:
"""Return the head of a list.
If the input list is empty, then return `None`.
:param list list1: input list
:return: the first item
:rtype: object
>>> head([])
None
>>> head([1,2,3])
1
"""
if len(list1) == 0:
return None
... | 14b60ccb29c9c551d45958f8c6efc9b85050551b | 77,589 |
def add_fixed_mods(seqs:list, mods_fixed:list, **kwargs)->list:
"""
Adds fixed modifications to sequences.
Args:
seqs (list of str): sequences to add fixed modifications
mods_fixed (list of str): the string list of fixed modifications. Each modification string must be in lower case, except f... | 1e81c265fee6ce18071165920e770ffdb940adb0 | 77,601 |
from typing import Mapping
def render_callable(
name: str,
*args: object,
kwargs: Mapping[str, object] | None = None,
indentation: str = "",
) -> str:
"""
Render a function call.
:param name: name of the callable
:param args: positional arguments
:param kwargs: keyword arguments
... | 8d507335be5bb5e070c5c28807df301ca7572913 | 77,606 |
def format_time(seconds, total=None, short=False):
"""
Format ``seconds`` (number of seconds) as a string representation.
When ``short`` is False (the default) the format is:
HH:MM:SS.
Otherwise, the format is exacly 6 characters long and of the form:
1w 3d
2d 4h
1h 5m... | 456438e356b375af77fe1527f35ea22d230450f0 | 77,607 |
import torch
def get_topk_from_heatmap(scores, k=20):
"""Get top k positions from heatmap.
Args:
scores (Tensor): Target heatmap with shape
[batch, num_classes, height, width].
k (int): Target number. Default: 20.
Returns:
tuple[torch.Tensor]: Scores, indexes, categor... | cff0800fac35269234fdaa3fd35d5461efca11ad | 77,608 |
def trimMatch(x, n):
""" Trim the string x to be at most length n. Trimmed matches will be reported
with the syntax ACTG[a,b] where Ns are the beginning of x, a is the length of
the trimmed strng (e.g 4 here) and b is the full length of the match
EXAMPLE:
trimMatch('ACTGNNNN', 4)
>>>'ACT... | 43bfbcfa0286646fae75c73bccb245a9f113131e | 77,611 |
def manhattanDistance(current: list, target: list):
"""
Calculates the Manhattan distance between two 3x3 lists
"""
count = 0
curr_1d = []
tgt_1d = []
for i in range(3):
for j in range(3):
curr_1d.append(current[i][j])
tgt_1d.append(target[i][j])
for x in ... | 4ed95397294655d0ff9996b785fb9ed4787c0eeb | 77,613 |
def getMetricsDense(dfA, dfC):
"""
Return metrics from binary list such as [0,1,0], [1,1,0] where the index should be the same events
dfA are the samples where the antecedent are True or False
dfC are the samples where the consequents are True or False
"""
support = dfA.sum()
precision = (d... | 71f3ecc9121f9d95c0982a57a77d4aaa2c864fc3 | 77,617 |
def _tup_equal(t1,t2):
"""Check to make sure to tuples are equal
:t1: Tuple 1
:t2: Tuple 2
:returns: boolean equality
"""
if t1 is None or t2 is None:
return False
return (t1[0] == t2[0]) and (t1[1] == t2[1]) | 524c0144ba21ee6f877a2fb2d83660f92a1facf8 | 77,619 |
from typing import Union
def get_precision(num: Union[int, float]) -> int:
"""Returns the precision of a number."""
if type(num) == int:
return 0
return len(str(num).split('.')[1]) | 72f3dcb09e8480b51b1d29ee6859af74491a5abd | 77,620 |
def assert_is_dict(var):
"""Assert variable is from the type dictionary."""
if var is None or not isinstance(var, dict):
return {}
return var | 3ed3e970662213a920854e23b6e4a18042daddf0 | 77,622 |
def _text_indent(text, indent):
# type: (str, str) -> str
"""
indent a block of text
:param str text: text to indent
:param str indent: string to indent with
:return: the rendered result (with no trailing indent)
"""
lines = [line.strip() for line in text.strip().split('\n')]
return ... | 00101ea91edf3207983b57aa0d9022c08a4956ba | 77,626 |
def get_textual_column_indexes(train, test):
"""Return a tuple containing an ndarray with train and test textual column indexes.
Keyword arguments:
train -- the train dataframe
test -- the test dataframe
"""
txt_cols_train = train.select_dtypes('object').columns
txt_indexes_train = train.columns.ge... | c95ee41eef37d90b3c4945a3a6d73d8295fac8ea | 77,628 |
import time
def get_timeout(max_time):
"""
Calculates the moment in time when a timeout error should be raised.
:param max_time: maximum time interval
:return: the moment in time when the timeout error should be raised
"""
return time.time() + max_time | b71c5a3bff3826c172758d37dda1a22723d612e5 | 77,629 |
def make_table(oldtable=None, values=None):
"""Return a table with thermodynamic parameters (as dictionary).
Arguments:
- oldtable: An existing dictionary with thermodynamic parameters.
- values: A dictionary with new or updated values.
E.g., to replace the initiation parameters in the Sugimoto ... | 8ac7e50041e2fbf85bd94af20f5bc68bd024fdaf | 77,630 |
def item(index, thing):
"""
ITEM index thing
if the ``thing`` is a word, outputs the ``index``th character of
the word. If the ``thing`` is a list, outputs the ``index``th
member of the list. If the ``thing`` is an array, outputs the
``index``th member of the array. ``Index`` starts at 1 for... | c22da02ba1ea583c5d4799d71ab728cd5f2882ac | 77,631 |
import math
def aire_disque(r: float) -> float:
"""Précondition : r>0
Retourne l’aire πr2 d’un disque de rayon r
"""
return math.pi * r*r | 2e43f630ae3327ecbcb14d1644bef094053bc88b | 77,633 |
def multi_replace(text, patterns):
"""Replaces multiple pairs in a string
Arguments:
text {str} -- A "string text"
patterns {dict} -- A dict of {"old text": "new text"}
Returns:
text -- str
"""
for old, new in patterns.items():
text = text.replace(old, new)
retu... | 434d5bee6cbefc56292f77234e58316ce1146d60 | 77,635 |
def check_share_access(shares, con):
"""
Checks if a list of shares are accessible
Args:
shares: (list) A list of share objects
con: (SMBConnection) The SMB connection objects
Returns:
A list of shares that were accessible
"""
accessible = []
for share in shares:
... | b6d19c25c19d46c67308eb204fe2f0a13e7dacae | 77,636 |
def caption_time_to_milliseconds(caption_time):
"""
Converts caption time with HH:MM:SS.MS format to milliseconds.
Args:
caption_time (str): string to convert
Returns:
int
"""
ms = caption_time.split('.')[1]
h, m, s = caption_time.split('.')[0].split(':')
return (int(h... | 36e923e89718fb2319a97da29662f9d8ecf4cb3d | 77,637 |
def keybase_lookup_url(username):
"""Returns the URL for looking up a user in Keybase"""
return "https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s" \
% username | 7c44d47ae2dfef9cdc699f7d7e9ee4c07adbfda3 | 77,643 |
def make_token_dict(sentences, pad_token=None, extra_tokens=None):
"""Extract tokens from tokenized *sentences*, remove all duplicates, sort
the resulting set and map all tokens onto ther indices.
:param sentences: tokenized sentences.
:type sentences: list([list([str])])
:param pad_token: add a to... | 35fe2d17e136559ac189d0273a2e1b93c8f439cc | 77,644 |
def getContentChild(tag):
"""Returns true if tag has content as a class"""
if tag.get('class', None) and 'content' in tag['class']:
return True
return False | dc632c6fd4c8b57a0d2924e4030c2384cc4c3fd4 | 77,648 |
def test_for_a_stretch(seq, a_stretch):
"""
Test whether or not the immediate downstream bases of the PAS are A
throughout the a_stretch distance.
>>> test_for_a_stretch("AAAAATTTTTTTTTT", 5)
'a'
>>> test_for_a_stretch("AAAATTTTTTTTTTT", 5)
''
"""
return 'a' if seq[:a_stretch].count... | d974a85a0fd7548758731f6f67ee40f4ffcd0be3 | 77,649 |
import csv
def make_empty_features_csv(fpath):
"""
creates an empty csv file to hold extracted features
returns fpath to the file
"""
# save empty csv to hold features
with open(fpath, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
print('outputting features to: ', fpa... | 123d3dfb795fbd3be963fbf7c15d704713f502b8 | 77,654 |
def read_fasta(fname):
"""Read in a Fasta file and returns a list of sequences."""
temp = []
seqs = []
with open(fname, 'r') as f:
for line in f.readlines():
if line.startswith('>'):
temp.append(line[1:].strip())
seqs.append('')
else:
... | f56d51c891f80cdd3077e244231cb63c6febdf4d | 77,655 |
def build_project(project_name):
"""Builds eclipse project file.
Uses a very simple template to generate an eclipse .project file
with a configurable project name.
Args:
project_name: Name of the eclipse project. When importing the project
into an eclipse workspace, this is the nam... | 255207d917c6f413ec7774c018f454cc309ae537 | 77,657 |
def var(string: str, dic: dict={}):
"""Replaces a string using a dict."""
for key in dic.keys():
string = string.replace('{' + str(key) + '}', str(dic[key]))
return string | d5f8ea56259b9421fee0507df47c9a3dfa40e0e0 | 77,660 |
import time
def format_time(t):
"""Formats time into string with minutes and seconds
:param t: The time in seconds
:type t: float
:return: Formatted string with minutes and seconds
:rtype: string
"""
time_string = time.strftime("%M:%S", time.gmtime(t))
time_list = time_string.split(":... | 7bad6fdde1cf1cdee10c1d7eeee9a95e31e7a007 | 77,661 |
from typing import Dict
from typing import Callable
from typing import Any
import inspect
def getObjPublicMethods(obj: object) -> Dict[str, Callable[..., Any]]:
""" Return a dictionary of object public methods that does not start
with '_' or '__'. Each item represents: 'name': <reference to a method>
No... | e5c31a2af3475553b615e3137760e896591705ab | 77,668 |
from typing import Tuple
from pathlib import Path
def read_lean_template(file_name: str = 'template.lean') -> Tuple[int, str]:
"""Read a template Lean file containing at least one sorry.
Returns the line number of the first sorry"""
text = Path(file_name).read_text()
nb = 0
for line in text.split(... | b275b9371af15392faa2513ecf27992f748cde6b | 77,669 |
import re
def name_string_to_list(composite_names):
"""
Split comma separated slurm composite node name format.
Composite node names contain commas so ignore them within brackets.
:param composite_names: str: a comma separated nodename list
:return: list of composite node names
"""
splitte... | 3da10aa422862946310c065673dcf5316e64db5a | 77,670 |
def _normalize_block_name(block_name):
"""Implements Unicode name normalization for block names.
Removes white space, '-', '_' and forces lower case."""
block_name = ''.join(block_name.split())
block_name = block_name.replace('-', '')
return block_name.replace('_', '').lower() | eead462770a826e8d0c6f6c03a0da00cd94b7bf3 | 77,680 |
def kumaraswamy_invcdf(a, b, u):
"""Inverse CDF of the Kumaraswamy distribution"""
return (1.0 - (1.0 - u) ** (1.0 / b)) ** (1.0 / a) | 0fef516b653079a1b046886cecc37ba66f6a186a | 77,682 |
def get_classes(classes_path):
"""
Reads the class names from a file and returns them in a list.
Parameters
----------
classes_path : string
Path that points to where the class name information is stored.
Returns
-------
class_names : list
A list of format:
['cl... | 9cc59762779276dfce857c9411220a208c270079 | 77,685 |
def crop_image_to_multiple_eight(image):
"""Returns a crop of an image to be multiples of 8."""
dimensions = image.size
width = dimensions[0]
height = dimensions[1]
new_width = width - (width % 8)
new_height = height - (height % 8)
box = (0, 0, new_width, new_height)
return image.crop(bo... | 8b261fa96be1695c9f00e0fc7d54fac7e98d54fd | 77,687 |
def lineToList(line):
"""Converts a tab-delimited line into a list of strings, removing the terminating \n and \r."""
return line.rstrip("\n\r").split("\t") | 1f0b6ad23504d29004f5fd77506ed33cc728f8f3 | 77,689 |
def calc_prefix(_str, n):
"""
Return an n charaters prefix of the argument string of the form
'prefix...'.
"""
if len(_str) <= n:
return _str
return _str[: (n - 3)] + '...' | e7c666667dc24941ad496158f321bbc7706a5d06 | 77,693 |
def removeEmptyElements(list):
""" Remove empty elements from a list ( [''] ), preserve the order of the non-null elements.
"""
tmpList = []
for element in list:
if element:
tmpList.append(element)
return tmpList | 140a9d93ff9ce18462d36d54b5e2634cecf5f4d3 | 77,694 |
import glob
def get_all_files(path, valid_suffix):
"""
Get all files in a directory with a certain suffix
"""
files = []
for suffix in valid_suffix:
files.extend(glob.glob(path + "*/**/*" + suffix, recursive=True))
return files | 79dac548b982cd82069bb9595ec335667a09da0a | 77,696 |
def option_rep(optionname, optiondef):
"""Returns a textual representation of an option.
option_rep('IndentCaseLabels', ('bool', []))
=> 'IndentCaseLabels bool'
option_rep('PointerAlignment', ('PointerAlignmentStyle',
[u'Left', u'Right', u'Middle']))
=> 'PointerAlignment PointerAlig... | 005462286006469ce333ca9973c4fb1ee056be9e | 77,698 |
def isString(strng, encoding):
"""
Returns true if the string contains no ASCII control characters
and can be decoded from the specified encoding.
"""
for char in strng:
if ord(char) < 9 or ord(char) > 13 and ord(char) < 32:
return False
try:
strng.decode(encodi... | 4ac7f542e1e48591ace7b07797c796434e420c76 | 77,700 |
def electrokinetic2(row):
"""
notes: 1) zeta potentials are in mV. if in V, remove the 1e3
2) relative dialectric is for water, if this is not true,
make a column and change the function.
references:
(1) You-Im Chang and Hsun-Chih Chan.
"Correlation equation ... | ee1fd24883b85163300986a7ab279d6522d130e0 | 77,706 |
def build_quarter_string(operational_year, operational_quarter):
"""
Helper function to build quarter name for JIRA.
:param String operational_year:
:param String operational_quarter:
:return: Formatted Quarter name
:rtype: String
"""
return 'Y%s-Q%s' % (operational_year, operational_qu... | eb2e1591d1f99b6bb01fed5af6d7b820514ccb3f | 77,711 |
def derive_queue_len_from_count(df_x_name, predicted_rf_counts):
"""Use the ML classifications of queue count to estimate queue length for each link"""
# get the index values from X
idx = df_x_name.index.tolist()
# replaced veh_len_avg_in_group with avg_veh_len IF Na/0
# get the veh_len_avg_in_group... | 5809195f04155ab369553b8a0720fd7054c37269 | 77,714 |
def is_legacy_data(sorald_stats: dict) -> bool:
"""Detect whether this data is detailed stats output from modern Sorald or
legacy data (from the old PRs.json file or simply empty).
"""
return all(
isinstance(key, str) and isinstance(value, (int, str))
for key, value in sorald_stats.items... | 0d3aa3265f64af2681ac10fcfe35fcbede2779ea | 77,715 |
def create_canvas(width, height, enable_color = True):
"""
Create a new char canvas.
Parameters
----------
height: height of the game view (int).
width: width of the game view (int).
enable_color: enable color in the game view (bool)
Return
------
canvas: 2D ascii canvas (dic).... | b0ba6648eb47533e939321d107f64e1323e9a81d | 77,720 |
def get_element_text(dom_element):
"""
Get the content of the element from it's text node (if one exists)
"""
return " ".join(t.nodeValue for t in dom_element.childNodes if t.nodeType == t.TEXT_NODE) | f7972accb717f543b1f5a49a3a4795db1bbf06a3 | 77,725 |
import re
def _strip_sql(sql: str) -> str:
"""Returns a copy of sql with empty lines and -- comments stripped.
Args:
sql: A SQL string.
Returns:
A copy of sql with empty lines and -- comments removed.
"""
lines = []
for line in sql.split('\n'):
line = re.sub(r'\s*--.*', '', line)
if line.... | e5f3ff9509133889e090337f9718280138e44549 | 77,726 |
def fasta_header(exp, N):
"""Generates random headers for the fasta file
Parameters
----------
exp : str
name of experiment (no spaces)
N : int
number of headers to be generated
Returns
-------
headers : list
names for each sequence (arbritrary)
"""
... | e2a76a4509f524b6514e59d7a0154894b4311ad4 | 77,730 |
import torch
def sm_sim(q, M):
"""
q : D
M : M x D
returns : M
Computes the dot product, followed by softmax between vector q, and all vectors in M.
I.e. the distribution we aim to model using Noise Contrastive Estimation or Negative Sampling.
"""
return torch.softmax(M @ q, 0) | b1506381892ef6f5ee58ea2a4f1249ede18a7e12 | 77,731 |
def parse_user_prefix(prefix):
"""
Parses:
prefix = nickname [ [ "!" user ] "@" host ]
Returns:
triple (nick, user, host), user and host might be None
"""
user = None
host = None
nick = prefix
host_split = prefix.split('@', 1)
if len(host_split) == 2:
nick = h... | b3f48eda6599dcc6d503937bae4de71c6e81098c | 77,733 |
def calculate(not_to_exceed):
"""Returns the sum of the even-valued terms in the Fibonacci sequence
whose values do not exceed the specified number"""
answer = 0
term_one = 1
term_two = 2
while term_two < not_to_exceed:
if not term_two % 2:
answer += term_two
next_ter... | 36f8dc57d25afb1dfa700b8cd391b03a80cd4e11 | 77,735 |
import decimal
def places(astring):
"""
Given a string representing a floating-point number,
return number of decimal places of precision (note: is negative).
"""
return decimal.Decimal(astring).as_tuple().exponent | 7d613e2e36c407b8f62963aa8fe7bd83fa338dc1 | 77,736 |
def list_dictify(obj):
"""
Function for building a dictionary from all attributes that have values
"""
list_dict = {}
for attr, value in obj.__dict__.items():
if value:
list_dict[str(attr)] = value
return list_dict | 7827043d3763b49556c10d73e9f6b9d758013be9 | 77,737 |
def get_row_name(element):
"""Row name getter"""
return getattr(element, '__name__', None) | 91a16f6698f40c0faa2773f9895a3003d09feab5 | 77,740 |
def zero_matrix(matrix):
"""
Given an m x n matrix of 0s and 1s, if an element is 0,
set its entire row and column to 0.
Given a matrix A as input.
A = [[1, 0, 1],
[1, 1, 1],
[1, 1, 1]]
On returning the matrix A should have the rows and columns
containing the... | d5609381529f3eba5526f75a8aa12bebfb3865a4 | 77,741 |
def unipolar(signal):
"""
Inverse to bipolar().
Converts a bipolar signal to an unipolar signal.
"""
return signal * 0.5 + 0.5 | b36f0245f367b63023b7ef39e6358b0bf1068b32 | 77,745 |
import re
def _StripTrailingDotZeroes(number):
"""Returns the string representation of number with trailing .0* deleted."""
return re.sub(r'\.0*$', '', str(float(number))) | 0036f2a9bc5bc22a54a01fbfc236a48a2373e6a4 | 77,748 |
def clear_rightmost_set_bit(n):
"""Clear rightmost set bit of n and return it."""
return n & (n-1) | 250e9bd42ec23d24443084fe7f603fdd7271692b | 77,750 |
def latex_float(f, precision=0.2, delimiter=r'\times'):
""" Convert a float value into a pretty printable latex format
makes 1.3123e-11 transformed into $1.31 x 10 ^ {-11}$
Parameters
----------
f: float
value to convert
precision: float, optional (default: 0.2)
the precision w... | b3d31afcfbf8a564d85f5f5b099b0d63bc8d89f8 | 77,753 |
def look_and_say_next(number: str='1') -> str:
"""Следующее число последовательности "Посмотри и скажи"
:param number: число последовательности, defaults to '1'
:type number: str, optional
:return: следующее за number число
:rtype: str
"""
k, last, result = 1, number[0], ''
for digit in... | 473faeacb78d7f65b745a7bab7caaaaf426e03f5 | 77,760 |
def get_type(props):
"""Given an arbitrary object from a jsdoc-emitted JSON file, go get the
``type`` property, and return the textual rendering of the type, possibly a
union like ``Foo | Bar``, or None if we don't know the type."""
names = props.get('type', {}).get('names', [])
return '|'.join(name... | d97dec6e9340ff977194dafe17b396c4318a2b60 | 77,763 |
import re
def find_screen_size(handle):
"""
Find the screen size of a previously written EDL file
Parameters
----------
handle : file-like object
EDL path to read screen size
Returns
-------
dimensions : tuple
Width and height of screen
Raises
------
Valu... | 3bbcc7325c5f2c8c49f8e9f23430fff5a4aa3169 | 77,766 |
def get_lib_extension(lib):
"""Return extension of the library
Takes extensions such as so.1.2.3 into account.
Args:
lib: The library File.
Returns:
String: extension of the library.
"""
n = lib.basename.find(".so.")
end = lib.extension if n == -1 else lib.basename[n + 1:]
... | 51252410843d279143b83f45baa008833d6868d6 | 77,775 |
import random
def randomize(x, y, length):
"""Randomize order of values in x & y"""
random_indices = list(range(length))
random.shuffle(random_indices)
x = x[random_indices]
y = y[random_indices]
return x, y | e9ba94bbe4d538b5862e3b709194541079ac8e03 | 77,776 |
from typing import Tuple
def get_input() -> Tuple[int, int]:
"""Returns N x M integer input for Designer Doormat.
Returns:
Tuple[int, int]: N x M, representing length & width.
"""
n, m = [int(x) for x in input().split()]
if n % 2 == 0:
raise Exception("Not odd!")
if m != 3* n... | c0a9166a0c61bbcb1a72966b7957556896340bc2 | 77,777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.