content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def constraint1(x):
""" Some constraint to ensure that the probabilities sum to one. """
return x[1:].sum() - 1 | 26ce84ab1c40d55b02d7f15db09fd3c7d0ca1680 | 636,247 |
def merge_sorted_lists(list_left, list_right):
"""
Merge two sorted lists
This is a linear operation
O(len(list_right) + len(list_right))
:param left_list: list
:param right_list: list
:return merged list
"""
# Special case: one or both of lists are empty
if len(list_left) == 0:
... | cc59d96d6f5854fa16b531d9238ddca48193f487 | 636,249 |
import re
def bcl_scrub_name(name):
"""Modifies a sample name to be BCL2fastq compatible
Parameters
----------
name : str
the sample name
Returns
-------
str
the sample name, formatted for bcl2fastq
"""
return(re.sub('[^0-9a-zA-Z\-\_]+', '_', name)) | 1e9f5bd95daaca720bf65aff58ff7af6177401f7 | 636,250 |
def groupIntersections(intersections: list, key: int) -> dict:
"""
Function to group horizontal or vertical intersections
Groups horizontal or vertical intersections
as a list into a dict by the given key
Parameters:
intersections (list): List of tuples representing
intersection points
key (int): Tu... | 45f33715dc9917eb224376c2bedede1a8c49c48f | 636,256 |
from unittest.mock import Mock
def get_output_string(patch_obj: Mock) -> str:
"""Helper function to get text pathed to output."""
return patch_obj["output_path"].write.call_args[0][0].strip() | 68aa506fc924117abe8453772d744c7564bc4b35 | 636,259 |
def remove_padding(im, pad=0):
"""
Function for removing padding from an image
:param im: image or prob map to remove padding from
:param pad: number of pixels of padding to remove
:return:
"""
if pad == 0:
return im
else:
return im[pad:-pad, pad:-pad] | c1f70c285cc6245b941923d554e8d2d1582d98b7 | 636,260 |
import hashlib
def get_md5_tmp(path):
"""
return the md5 sum of the path.
if the path is a temporary directory, the md5 is prefixed with "tmp_"
"""
m = hashlib.md5()
m.update(path)
if path.__contains__("temp") or path.__contains__("tmp"):
return "tmp_%r" % m.hexdigest()
... | af06e6415c72d4f102908510be70372bb3f76657 | 636,262 |
def main(argv):
"""Main entry point of the program"""
print("This is a boilerplate") ## NOTE: indented using two tabs or 4 species
return 0 | f29a528faa1d59afba9d9e1a008644af3cf96d3b | 636,264 |
def parse_tags(tagset):
"""Convert the tagset as returned by AWS into a normal dict of {"tagkey": "tagvalue"}"""
output = {}
for tag in tagset:
# aws is inconsistent with tags sometimes they use caps and sometimes not
if 'Key' in tag:
output[tag['Key']] = tag['Value']
if ... | d38b7243f24bb24b95f0e4de06b299747ce8acbf | 636,268 |
def convert(vertical_lists):
"""rotate a given list of lists
converts a list as if it was a matrix
interchanges 'row' and 'columns'
Args:
vertical_lists: list of lists to be rotated
Returns:
list: list of lists
contains the same elements as original
except t... | 58f5d6303045500f64c816f4534e3a77fbe73ff5 | 636,271 |
def pad_hexdigest(s, n):
"""Pad a hex string with leading zeroes
Arguments:
s (str): input hex string
n (int): number of expected characters in hex string
Returns:
(str): hex string padded with leading zeroes, such that its length is n
"""
return "0" * (n - len(s)) + ... | 8486eed39066269e59ede06ff5f8486b4506faa9 | 636,272 |
import json
def catch_json_error(blob, filepath, **kwargs):
"""Wrapper to provide better error message for JSON reads"""
try:
parsed = json.loads(blob, **kwargs)
except ValueError as e:
raise ValueError("JSON error reading {}: {}!".format(filepath,
... | c630a4b886c2b6be9d3095c4ef3e8a1be84c1723 | 636,274 |
def is_oauth_configured(ta_tabs):
"""
Check if oauth is configured in globalConfig.json.
Args:
ta_tabs (list): List of tabs mentioned in globalConfig.json.
Returns:
bool: True if oauth is configured, False otherwise.
"""
for tab in ta_tabs:
if tab["name"] == "account":... | c9ea6f06bb2aefcdfdc960b41155830f16f1a027 | 636,275 |
def translate(curve):
"""
P.translate(numpy.ndarray) -> numpy.ndarray
Take a three dimensional curve defined by a numpy ndarray and translate
that curve so that the mean of each of spatial componenets lies at the
origin.
"""
try:
return curve - sum(curve)/curve.shape[0]
exce... | d8734de5b7c2320e2a4e2c4c03c0a96936514f27 | 636,278 |
def get_last_insert_id(dict_cursor):
"""
return the last inserted id by this client/connection.
see also https://dev.mysql.com/doc/refman/5.7/en/mysql-insert-id.html
"""
dict_cursor.execute('select last_insert_id() as id')
return dict_cursor.fetchone()['id'] | e90c077c6b02f0ba4c649832583533e4951e8d1d | 636,281 |
def full_invoiceitem(faker):
"""Returns a dict for an `InvoiceItem`."""
full_item_dict = {
"service": "Some Material",
"qty": 5.0,
"unit_price": 12.3,
"vat": 19.0,
"description": faker.sentence(nb_words=5),
}
return full_item_dict | 307c430ea0611cf5afef0672b098f1abc73f6504 | 636,285 |
from typing import List
import inspect
def _get_failing_lines(code, lineno: int) -> List[str]:
"""Get list of strings (lines of code) from lineno to lineno+3.
Ideally we'd return the exact line where the error took place, but there
are reasons why this is not possible without a lot of work, including
... | 9256aefe6fcb950cd0b4bf822dcb3c306ac17023 | 636,287 |
import json
def _load_predictions_dicts(filepath):
"""Returns list of predictions dicts."""
predictions_dicts = json.load(open(filepath))
return predictions_dicts | 553c0eb7ad076433cc5d88272f3f77845277a71e | 636,292 |
def train_test_split(df_ml):
""" Split log data into train and test by well ID """
test_wells = set(['B03', 'B05', 'B06'])
train_wells = set(df_ml.HACKANAME.unique()) - test_wells
print('Train well: ', train_wells)
print('Test wells: ', test_wells)
mask_train = df_ml.HACKANAME.isin(train_wells... | cb397c984b94b08922e9fbef6f061bbc91f08d70 | 636,294 |
def _extract_first_argument(args: tuple, kwargs: dict):
"""
Returns the tuple (X, _args, _kwargs) where X is the first argument (
found in either args or kwargs), and _args, _kwargs are the same (with X
removed)
>>> _extract_first_argument((1,2,3), {'d': 4})
(1, [2, 3], {'d': 4})
>>> _extra... | 72ce272e241f1d9a74bda4075859a847d33066aa | 636,295 |
def simple_hello(name="you"):
"""Returns string with greeting."""
return "Hello {}!".format(name) | f4b016d3cc145a3adfca1cf67f5791da2a6ff473 | 636,296 |
def parse_summary_file(summary_file):
""" Parse a summary file generated by this pipeline
and return the metrics as a dictionary {"metric":val}
summary_file : str; the path to the summary file
"""
metrics = {}
with open(summary_file,"r") as IN:
for line in IN:
contents = lin... | 1004c7cfc517f8ad8c254c4fef04eaea6f72fb73 | 636,298 |
def find_shortest(array: list[int]) -> int:
""" Find the shortest element in an array.
find_shortest
=============
The `find_shortest` function takes an array and finds the shortest element
in it.
Parameters
----------
array: list[int]
An array/list of integers
Returns
-------
... | 46d4de53f22e0dcf8c5d3a200c082df0041cbeef | 636,302 |
def _user_keyed_dict(reader):
""" create a dict of the rows of the csv, keyed by the "user" value """
return {row['user']: row for row in reader} | 344f8fcd8e61a7f8cb45762210a80f2fd7e78d0d | 636,305 |
def sign(x):
"""Sign function.
:return -1 if x < 0, else return 1
"""
if x < 0: return -1
else: return 1 | 64d85692c0a26fc1918024c95c9c554d92a3d2e7 | 636,307 |
def get_results_from_dict_of_sets(list_of_elements, dict_of_sets):
"""
We have a list of elements that are in a dict of elements, and every element have a set with results.
We want to extract the results corresponding to our elements.
"""
results = set()
for element in list_of_elements:
... | 38e1d243d149cfdf42712acc8a71f26436c60b69 | 636,308 |
def largest_factor(n):
"""Return the largest factor of n*n-1 that is smaller than n.
>>> largest_factor(4) # n*n-1 is 15; factors are 1, 3, 5, 15
3
>>> largest_factor(9) # n*n-1 is 80; factors are 1, 2, 4, 5, 8, 10, ...
8
"""
factor = n - 1
while factor > 0:
if (n*n-1) % factor ... | deaad22f8a5c11a696c8410b8d179b0dc38c8a93 | 636,311 |
def boolNot(num):
""" return True if num is not 0 """
return num != 0 | 445aee860bf58c174cae51faa48b0aa55c70f553 | 636,315 |
def get_mbean_name(location, existing_names, alias_helper):
"""
Return the mbean name for the specified location.
For unpredictable single folders:
1. if an existing folder name is present, use that name as the mbean name.
2. set the location's token to the mbean name.
:param location: the l... | c973073fd02c82179326d089ec4680012f7fd724 | 636,319 |
def _stanza_handler(element_name, stanza_type, payload_class, payload_key,
usage_restriction):
"""Method decorator generator for decorating <message/> or <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
-... | 8614952f9101f3613a2f8a0e6de6b2fe58c22c44 | 636,322 |
def get_item_from_gcp_response(key_field, key_name, items):
"""
Get item from GCP REST response JSON list by name.
items = [{ 'key_field': 'key_name', 'key_field_value': 'value'}]
:param key_field: item dictionary key
:param key_value: item dictionary value
:param items: list of items(dictionari... | befec2b2059e08c9979e36373bb929ba838450a8 | 636,327 |
import re
def _FormatNameAsConstant(name):
"""Formats a name to be a C++ constant of the form kConstantName"""
name = '%s%s' % (name[0].upper(), name[1:])
return 'k%s' % re.sub('_[a-z]',
lambda m: m.group(0)[1].upper(),
name.replace('.', '_')) | 9ac8d9ca9438e5c4732b37f39e7432bb95fc72d5 | 636,332 |
def is_boxcar(die1, die2):
"""Return true if face values of die total 12."""
BOXCARS = 12
return True if (die1 + die2 == BOXCARS) else False | aa5cbd48e52f9a470d51fbe758907131b427080b | 636,333 |
def is_a_conv_layer_label(layer_label):
""" Returns true if a convolutional layer. """
return 'conv' in layer_label or 'res' in layer_label | aa25733ece3ef837f77bbe2adc61c208e6dfa380 | 636,335 |
import math
import random
def randint_sample(min, max, size):
""" Generate sample of random integers number inclusively """
width = max - min + 1
return [math.floor(random.random() * width + min) for _ in range(size)] | d59047b4c6317fff45c0aaa460887f8d6fbb0665 | 636,339 |
import typing
import pathlib
def is_path_obj(obj: typing.Any) -> bool:
"""Is given object ``obj`` a pathlib.Path object?
"""
return isinstance(obj, pathlib.Path) | 52e44eb1e2b6dc448f6fd828f8e5e2ef758a0bb6 | 636,344 |
def table_to_csv(table_name):
"""
DESCRIPTION: Turn table name into filename, i.e., add .csv
INPUT: table name (filename without extension)
OUTPUT: filename (with extension)
"""
csv_filename = str(table_name) + '.csv'
return csv_filename | 5114f5b5a86644b38fa16f22ff065c804f8222f5 | 636,345 |
def __isInBounds(x: int, y: int, nRows: int, nCols: int) -> bool:
""" Check if x and y is within bounds """
return (x >= 1 and x <= nCols and y >= 1 and y <= nRows) | 36a8640dda0304bb4e8223f1263b35798b673144 | 636,346 |
import unicodedata
def is_wide(char):
"""is_wide(unicode_char) -> boolean
Return True if unicode_char is Fullwidth or Wide, False otherwise.
Fullwidth and Wide CJK chars are double-width.
"""
return unicodedata.east_asian_width(char) in ("F", "W") | f2b0399c25c6d6b7fcdc8d577e0440fa7f7992e5 | 636,347 |
def vrh(kclay, kqtz, vclay):
"""
Voigt-Reuss-Hill average to find Kmatrix from clay and qtz components.
From Smith et al, Geophysics 68(2), 2003.
Works for any two components.
Args:
kclay (float): K_clay.
kqtz (float): K_quartz.
vclay (float): V_clay.
Returns:
... | 7a3461d1643b5ea35e90ebfbd565ea50efaf4034 | 636,348 |
def efd_name(csc, topic):
"""Get a fully qualified EFD topic name.
Parameters
----------
csc : str
The name of the CSC.
topic : str
The name of the topic.
"""
return f"lsst.sal.{csc}.{topic}" | 077ada0d1285741a748a6053720d57d2863702ca | 636,351 |
from datetime import datetime
def month_start(src_time):
"""Return the beginning of the month of the specified datetime"""
return datetime(src_time.year, src_time.month, 1) | ced437ee7c2246bf22a6282725e1c618cbe4c79b | 636,352 |
import string
def base62_encode(num: int) -> str:
"""
Encode a positive number using 62 characters 0-1a-zA-Z
"""
charset = string.digits + string.ascii_letters
size = len(charset)
result = ''
while True:
num, rem = num // size, num % size
result += charset[rem]
if n... | fcf113d30f3ab037b09e83c678c802bcf15d2aa9 | 636,356 |
import re
def extract_path(path_string):
"""Convert a path string to a list of names"""
return re.findall(r"[^/\\]+", path_string) | 85f6894688f458aaa4d8bf168f9a667c8ef2cc01 | 636,357 |
def defaultTransformation(mol):
"""
defaultTransformation() returns the mol it receives as parameter.
For testing, corrsponds to a .sdf copy action without any molecule transformation
"""
return mol | 6f83888da21366eded67d9c8e917aeba4ffbac84 | 636,359 |
from typing import List
import re
def parse_csv(text: str) -> List[str]:
"""Parse comma separated **double quoted** strings in behave steps
Args:
text: double quoted comma separated string
Returns:
List of string tokens
"""
return re.findall(r"\"(.+?)\"\s*,?", text) | 76c2a38fa61d3f298ae26d9eddd0652d8ff94fd5 | 636,361 |
import torch
from typing import cast
import warnings
def predict_segmentation(
logits: torch.Tensor, mutually_exclusive: bool = False, threshold: float = 0.0
) -> torch.Tensor:
"""
Given the logits from a network, computing the segmentation by thresholding all values above 0
if multi-labels task, comp... | f2a3b9ae91e8d3b3d881bf0d4f898548ef09940c | 636,362 |
def _GetMetaDict(items, key, value):
"""Gets the dict in items that contains key==value.
A metadict object is a list of dicts of the form:
[
{key: value-1, ...},
{key: value-2, ...},
...
]
Args:
items: A list of dicts.
key: The dict key name.
value: The dict key value.
R... | 09255e96666a6a29cce3926428834a560d1ba019 | 636,363 |
import math
def round_down_to_multiplicity(multiplicity: int, num: int):
"""
Function to round a number to the nearest multiplicity given the multiplicity
:param multiplicity: multiplicity for rounding
:param num: input number to be rounded
:return: number rounded down to nearest multiplicity
... | 4ecee2a0341c197a9e263116ee4ed61227ae2d2e | 636,364 |
import six
def sort_db_results(results):
"""Deterministically sort DB results.
Args:
results: List[Dict], results from a DB.
Returns:
List[Dict], sorted DB results.
"""
sort_order = []
if len(results) > 0:
sort_order = sorted(six.iterkeys(results[0]))
def sort_ke... | 3cdd879082d60829b3686ac6e2e7a5c7f758c655 | 636,365 |
def Add(xs, **unused_kwargs):
"""Adds two tensors."""
return xs[0] + xs[1] | 40cd7ba1e7d9d76a93deab2bd45fb60b3b116264 | 636,367 |
def create_row(size):
"""Returns a single, empty row with the given size. Each empty spot is
represented by the string '-'.
>>> create_row(5)
['-', '-', '-', '-', '-']
"""
return ['-' for i in range(size)] | 6a9a01efab2bae00f016b58324e187f734f904cd | 636,370 |
def has_valid_token(client):
"""Does the session have a valid token?"""
return client.authorized | 9ede665bb18a25fb05e30f8d640456f73e64c751 | 636,375 |
import re
def get_version(string):
""" Retrieve the ``__version__`` attribute for Layabout. """
flags = re.S
pattern = r".*__version__ = '(.*?)'"
match = re.match(pattern=pattern, string=string, flags=flags)
if match:
return match.group(1)
raise RuntimeError('No version string could ... | 36aa18a6750fc5d17e1da13ba6768afe7b52960d | 636,376 |
def unpack_string_from(data, offset=0):
"""Unpacks a zero terminated string from the given offset in the data"""
result = ""
while data[offset] != 0:
result += chr(data[offset])
offset += 1
return result | b3b8f5524458eae767c1041c450709925aa111d0 | 636,378 |
def code() -> str:
"""
Example G-code module, an arrow.
Please simulate first, before milling.
"""
return ("""
G91
G0 X0 Y2
G0 X0 Y-4
G0 X0 Y2
G0 X-20 Y0
G0 X40 Y0
G0 X-5 Y-5
G0 X5 Y5
G0 X-5 Y5
G0 X5 Y-5
""") | 938b29301916f12464c93984caf2ab791b691a17 | 636,387 |
def to_capital(word: str):
"""
Make the 'word' parameter capitalized
:param word: string to be capitalized
:return: capitalized string
"""
return word.capitalize() | a764b1765ee1f90272ec6671d362a1b7edd07d72 | 636,388 |
def get_count_and_move(s: str, pos: list) -> int:
"""
Extract a repeat {count} from s[pos[0]:]
Args:
s (str): the string to extract from.
pos (list): pos[0] points to the next char in s to start extracting.
Returns:
int: the repeat count that was extracted.
pos[0]: sinc... | a1eba48975c62dd1330930a9208f39aa79e56af4 | 636,390 |
def listwise_delete(data, inplace=False, verbose=False):
"""Delete all rows from a DataFrame where any missing values exist.
Deletion is one way to handle missing values. This method removes any
records that have a missing value in any of the features. This package
focuses on imputation, not deletion. ... | f30fda1c3ca5390f77f75d711ebc4c9fe6c79b76 | 636,393 |
import torch
def to_device(m, x):
"""Function to send tensor into corresponding device
:param torch.nn.Module m: torch module
:param torch.Tensor x: torch tensor
:return: torch tensor located in the same place as torch module
:rtype: torch.Tensor
"""
assert isinstance(m, torch.nn.Module)
... | 4aefa9553f1c865ccc8e83dfad2cf8768ca96db3 | 636,394 |
def naorthreshold(lmbda, mu, costofbalking):
"""
Function to return Naor's threshold for optimal behaviour in an M/M/1 queue. This is taken from Naor's 1969 paper: 'The regulation of queue size by Levying Tolls'
Arguments:
lmbda - arrival rate (float)
mu - service rate (float)
costo... | d43c11a8c0fa98102cfeabfc98de6076c0d97f98 | 636,396 |
import torch
def _tblr_pred_to_delta_xywh_pred(bbox_pred: torch.Tensor,
normalizer: torch.Tensor) -> torch.Tensor:
"""Transform tblr format bbox prediction to delta_xywh format for ncnn.
An internal function for transforming tblr format bbox prediction to
delta_xywh form... | bdc924322f80b90f502f5a0aea9d1cfa057bc1bc | 636,401 |
def get_conn_str(db_name):
"""Returns the connection string for the passed in database."""
return f'postgresql://postgres:postgres123@localhost:5432/{db_name}' | 0197fada49a60f22bc716e65692db4c96f91a0af | 636,403 |
def convert_km_to_length(length):
"""Convert length like '1' to 1000 or '30M' to 30"""
try:
if length[-1:] == "M":
t_length = int(length[:-1]) # Trim off the 'M'
else:
t_length = int(float(length) * 1000) # Convert to meters
length_str = str(t_length)
exc... | 7e5e8d86a67c9038696e1d5a6198b4a499f8cb23 | 636,404 |
def calc_SST(X_act):
"""
This function returns the Sum of Square of actual values.
"""
return (X_act ** 2).sum() | b8da81ae2d9fc530643d3659fe89c773e1aa8b03 | 636,407 |
def transform(addon_df, threshold, num_addons):
""" Converts the locale-specific addon data in to a dictionary.
:param addon_df: the locale-specific addon dataframe;
:param threshold: the minimum number of addon-installs per locale;
:param num_addons: requested number of recommendations.
:return: a... | 58645f967f1bc43e3f7078b878e6d5a46f5261a1 | 636,412 |
def _debian_dist_name(env):
"""
Determine Debian dist name (e.g. squeeze).
"""
return env.safe_run_output("lsb_release -a | grep Codename | cut -f 2") | 1d545bd0229474d8440adaf78432729b7faf549d | 636,415 |
import six
def _get_exec_table_data(headers):
"""Extract a stats table from execution HTTP response headers.
Stats include things like node name, execution time, number of
reads/writes, bytes read/written, etc.
:param dict headers:
`dict` of response headers from a job execution request. It ... | 9724e8c24b2a7e3b6872ac3982d5383bb97721d3 | 636,416 |
import requests
import logging
def recently_traded(symbol):
"""Check if a ticker was recently traded on thetagang.com."""
url = "https://api.thetagang.com/trades"
params = {"ticker": symbol}
trades = requests.get(url, params=params).json()['data']['trades']
# Skip this message if nobody has trade... | 2224a8b449dc6cae96b2488f032297387db9ed1b | 636,417 |
import math
def f_1(scores):
"""Compute the corpus-wide F1 score represented by the scores.
Each score should contain four entries. Consider:
- first/second entry numerator/denominator for recall,
- third/fourth entry numerator and denominator for precision.
Then define r = sum(first ent... | ba4c0648223a1f0ad15ff1870d801a7f64296380 | 636,418 |
def sorted_values(x):
"""Returns the sorted values of a dictionary as a list."""
return [x[k] for k in sorted(x)] | 2d8d3156b8f4ba7b3f13a967c61a341bea39b808 | 636,420 |
def reverse_url(context, name, **parts):
"""
jinja2 filter for generating urls,
see http://aiohttp.readthedocs.io/en/stable/web.html#reverse-url-constructing-using-named-resources
Usage:
{{ 'the-view-name'|url }} might become "/path/to/view"
or with parts and a query
{{ 'item-details... | 963737f6fe4ee2fb3a79bb419051e815295253ef | 636,421 |
import platform
def getSystemBitness() -> int:
"""
Solution adapted from
https://stackoverflow.com/questions/2208828/detect-64bit-os-windows-in-python
"""
machine = platform.machine()
if machine.endswith('64'):
return 64
else:
return 32 | 7ee0c5095b4f34dbb8cc11d52a52ef51ead40dff | 636,422 |
def seatsInTheater(nCols, nRows, col, row):
"""
Given the total number of rows and columns
in the theater (nRows and nCols, respectively),
and the row and column you're sitting in, return
the number of people who sit strictly behind
you and in your column or to the left, assuming
all se... | 294167558d0a9a2e2616670b4a81854ecb8c3a19 | 636,425 |
def prepend_license(license_text, src_text, file_extension):
"""Prepend a license notice to the file commented out based on the extension.
Args:
src_text (str): The text which will have the license prepended.
file_extension (str): The relevant file extension.
Returns:
str: The full... | eda1cf92ac5469fe3879a4884fdadf3cf199eefe | 636,429 |
from typing import Any
from datetime import datetime
def json_encoder(obj: Any) -> Any:
"""json encoder function supporting datetime serialization.
Args:
obj: object to encode to JSON
Returns:
json encoded data
"""
if isinstance(obj, datetime):
return obj.isoformat()
... | 202f77c4be8acd8e51584a32f49419c8feaa7bba | 636,430 |
def _fit_transform_one(transformer,
X,
y,
weight,
message_clsname='',
message=None,
**fit_params):
"""
Fits ``transformer`` to ``X`` and ``y``. The transformed result is retu... | 1f1048f200668dfa274769d4f38c5f7568841cab | 636,431 |
def declr_has_sym(declr, sym):
"""Check if the given declr has sym"""
for existing in declr:
if existing["kind"] == sym["kind"] and existing["name"] == sym["name"]:
return True
return False | 4fb3919d5a83c6173c338b07f916e82948d858ac | 636,432 |
def create_p_yaw_model_tf(d, gp):
"""
Create transfer function for fly yaw dynamics model with proportional
controlller.
Arguments:
d = damping
gp = proportional gain
Returns:
tf = transfer function.
"""
def tf(s):
return gp/(s + d + gp)
return tf | 3b7673565a225036932c1e232d6e29112948d3dc | 636,441 |
def _calculate_insertion_point(existing_knob_list,
knob_point=None, insert_before=False):
"""Encapsulates logic on working out where to insert in a the knob list
Returns an integer index which tells us where to insert.
For example in list [A,B,C]:
- before A is 0
- ... | 0e383e26b996fc803404007e482d2dfb71b41d35 | 636,442 |
def create_and_list(list):
"""
Given a list of 1 items, return item
Given a list of 2 items, return item[0] and item[1]
Given a list of n items, return item[0], item[1], ..., and item[-1]
"""
if len(list) == 1:
return list[0]
elif len(list) == 2:
return list[0] + " and " + l... | 934b9ac2dc32a45cd63b96c836babefb5db551c3 | 636,444 |
def db_list_fields(con, tabel):
"""Return all column names for a specified table"""
cursor = con.cursor()
cursor.execute(f"select * from {tabel} limit 1;")
return [name[0] for name in cursor.description] | e053fa419bdb04006799550adfad2bc0ad8850da | 636,448 |
import six
def has_digit(string_or_list, sep="_"):
"""
Given a string or a list will return true if the last word or
element is a digit. sep is used when a string is given to know
what separates one word from another.
"""
if isinstance(string_or_list, (tuple, list)):
list_length = len... | 2fc03d44134f2255476c083f9323e815ff12007e | 636,452 |
import re
def parse_basename(bname):
"""return tuple (tsh, axis, ddd, hh, this_file, total_files) given basename"""
# input like BXM00018.15R
m = re.match('(?P<tsh>.)(?P<axis>.)(.)(?P<day>\d{3})(?P<hour>\d{2})\.(?P<this_file>\d)(?P<num_files>\d).', bname)
if m:
return m.group('tsh'), m.group('... | 37ebba5d929d863ab245019b0d539100f89d395d | 636,453 |
def check_subtraction_file_type(file_name: str) -> str:
"""
Get the subtraction file type based on the extension of given `file_name`
:param file_name: subtraction file name
:return: file type
"""
if file_name.endswith(".fa.gz"):
return "fasta"
else:
return "bowtie2" | 8522a79c6a8e65439c7b1e998b37987ee99c303a | 636,455 |
def get_configuration_tag(api):
"""
Return tag value for the configuration.
:param ConfigurationAPIUserV1 api: API instance.
:return: Tag as ``bytes``.
"""
return api.persistence_service.configuration_hash() | a8b1ecc8196dc3f1df3e1e456aedadf298959416 | 636,457 |
import random
def yes(specifier=0):
"""
Decide if we should perform this action, this is just a simple way to do something
I do in tests every now and again
:Example:
# EXAMPLE -- simple yes or no question
if testdata.yes():
# do this
else:
# don't do i... | c8c961648b91fe937aca49100da23b5b2992490d | 636,458 |
def _extended_euclidean(a, b):
"""Helper function that runs the extended Euclidean algorithm, which
finds x and y st a * x + b * y = gcd(a, b). Used for gcd and modular
division. Returns x, y, gcd(a, b)"""
flip = b > a
if flip:
a, b = b, a
if b == 0:
return 1, 0, a
x, y, gcd = _extended_eucl... | 4ff6bb3679d9b08337b555d4271ed97041ef8b0b | 636,460 |
def group_aggregation(df, group_var, agg_var):
"""
We need to group the Auto MPG Dataset on the basis of a column.
Then we have to calculate the mean of the grouped data according to another column
parameters
df: A dataframe containing the dataset in the form of a matri... | 3c54aa6ef7d2c421fb58cd7b9e60b9f8ec31b066 | 636,461 |
import torch
def disagreement(logits_1, logits_2):
"""Disagreement between the predictions of two classifiers."""
preds_1 = torch.argmax(logits_1, dim=-1).type(torch.int32)
preds_2 = torch.argmax(logits_2, dim=-1).type(torch.int32)
return torch.mean((preds_1 != preds_2).type(torch.float32)) | 82d12bb657018c4b446fd05c94c8f5834ce4fd59 | 636,464 |
def get_formatted_place (city, country, population):
"""Generate the name of a place and it's population."""
place = f"{city} {country}-Population: {population}"
return place.title() | 9ae4c9bb4898406d2737c003045d5f05384fcddf | 636,465 |
def parse_password_file(file_name):
""" parse the apache password file into usernames and passwords """
passwords = {}
for line in open(file_name, 'r'):
username, password = line.split(':')
passwords[username] = password.strip()
return passwords | cb3e5837ee0266af6facf3b825ba9fb6c6dcb918 | 636,467 |
def generate_pairs(n_rex):
"""Generate list of pairs that will attempt to swap configurations during
replica exchange Monte Carlo.
"""
pairs = list(zip(range(n_rex), range(1,n_rex)))
return pairs[::2], pairs[1::2] | 4f6fde753629a1ad08f57d83c643f380964ce4a4 | 636,468 |
from functools import reduce
import operator
def get_in(keys, coll, default=None, no_default=False):
""" Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys.
If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless
``no_default`` is specified, then it raises KeyError or IndexError.
... | 24a2086a9643f5302cba2245e588def09a5c74ce | 636,474 |
def _make_equal_size(a: str, b: str):
"""
Make the strings a and b equal size, by right-padding with spaces the shortest string
"""
max_length = max(len(a), len(b))
a = a.ljust(max_length).upper()
b = b.ljust(max_length).upper()
return a, b | 6bc50ecbb1b5a178ede833c0b0587685081fe030 | 636,477 |
import socket
def create_socket(port, host=None, connect=True):
"""Creates and returns a socket
Args:
port (int): port number to use
connect (bool, optional): whether socket should be connected (default=True)
host (str, optional): hostname to connect to (default="localhost")
Retu... | da1dd329599882591a8440f9b47dffc6ec83fce0 | 636,483 |
from functools import wraps
import warnings
def suppress_warnings(function):
"""
Decorate the given function to suppress any warnings.
Parameters
----------
function : function
Function to be decorated.
Returns
-------
decorated function
Decorated function.
"""
... | 2f47d470d364cb1e5fbfd869af0351348e2f43c3 | 636,484 |
def get_LDA_potential(vxct, kxct, s):
"""Evaluating the potential of LDA functional in a batch of spherical projection directions.
Parameters
----------
vxct: tuple of (vrho, vs), where vrho and vs are np.ndarray with shape (Ngrid)
The exchange-corelation energy of original LDA function.
... | f2bbefc36587a3db2049f0c16535137096a8b845 | 636,486 |
def TypeCodeToType(typeCode):
"""
Convert a type code to the class it represents
"""
if typeCode in ["b", "d", "f", "s"]:
return float
elif typeCode in ["i", "l"]:
return int
elif typeCode in ["c"]:
return str
else:
raise Exception("Unrecognised type code: " + typeCode)
return | 7ac115f94958842c47168dc6ff9e432caac48404 | 636,488 |
from pathlib import Path
import click
def validate_existing_dir(ctx, param, value: Path) -> Path:
"""
Callback for click commands that checks that a given path is a directory
"""
if not value.is_dir():
raise click.BadParameter(f"{value} is not a directory")
return value | 76cb4b62a964a6192fb34d862005ec7d8ddca977 | 636,491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.