content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import copy
def create_full_dict(param, name_list, fixed_list=["adjust_element2", "adjust_element3"]):
"""
Create full param dict so each item has the same nested dict.
This is for GUI purpose only.
Pamameters
----------
param : dict
all parameters including element
name_list : li... | bbe73ad221c21610327597aba81ca12b377f008a | 618,166 |
def _echo_value(value):
"""To use when no unit conversion is desired"""
return value | b193bb63eaf6daad8c9f243a4a9274fe4984678c | 618,172 |
def MakeExt( ext ):
"""Returns a file extension, starting with a dot if the given one does not."""
return ( '' if not ext or ext.startswith( '.' ) else '.' ) + ext | d72cd03b25723f3e04050d7f35e837459e66a984 | 618,173 |
def isNotBH(q):
"""In : q (state : string)
Out: Boolean
Given a state q, check if non-black-hole,
i.e. not 'BH'.
"""
return (q != 'BH') | 7e87b20b51c7ffec2e7698b1fb1f9d742c0b9ca7 | 618,174 |
import unicodedata
def _strip_accents(word):
"""Removes accent from the input word."""
return ''.join(char for char in unicodedata.normalize('NFD', word) if unicodedata.category(char) != 'Mn') | bedc10ae5e1eb74707d5df3f097af9be8b21d9d9 | 618,177 |
def clean_line(str, delimiter):
"""Split a string into 'clean' fields.
str the string to process
delimiter the delimiter string to split 'line' with
Returns a list of 'cleaned' field strings.
Any fields that were initially zero length will be removed.
If a field contains '\n' it isn't... | 3ffc71562065ccdc378fda61b75b60e0b2367592 | 618,179 |
import re
def split_line(line):
""" Split a line
Treat part enclosed by parentheses as a single unit
"""
line = re.sub('\s*=\s*','=',line)
parts = []
for p in re.split(',|\s',line):
part = p.strip()
if len(part)>0:
parts.append(part)
output = []
i = 0
#... | 43ed317a8e9c112855616450f7ba1a18b9b6d898 | 618,181 |
def local_indicies(lead_step, child_steps):
"""
Returns a tuple of indices surrounding the lead_step
"""
imin = 0
imax = len(child_steps) - 1
mid = 0
while imin < imax:
mid = (imax + imin)/2
if(child_steps[mid][0] < lead_step):
imin = mid + 1
else:
... | 2c97b99be1e69d5a2407d0c2af7caae7fa97cbd7 | 618,187 |
import yaml
def load_from_yaml(path, verbose=False):
"""
Load python object stored in yaml file.
:param path: file path to load
:param verbose:
:return: loaded object
"""
with open(path, 'r') as f:
if verbose:
print("Loading data from '" + path + "'")
return yam... | 375c9db684bdc6abf120b2a119a2a7a2f248df73 | 618,189 |
def split_and_prune_lines(lines):
"""Split input lines into tokenized lines, suppressing comment
(beginning with hash token) or empty lines.
Tokenization is by whitespace, i.e., with split.
The tokenized lines are returned as tuples rather than lists to
support downstream processing. For instance... | a4a6ff9e55c4d344f6b51b35b561f76a01fced0b | 618,192 |
def _loc(target):
"""Return target location for constructing commands.
Args:
target: Blaze target name available to this build.
Returns:
$(location target)
"""
return "$(location %s)" % target | 5b2d3b4641e027a47ee6f3a19f04faf8855de5a7 | 618,193 |
def _list_display(short_description=None, admin_order_field=None):
"""
Set the short_description and admin_order_field attributes on the decorated
function.
"""
def decorator(f):
if short_description:
f.short_description = short_description
if admin_order_field:
... | 929e975a127061bbb2e6a328ae386a54c32f28d6 | 618,194 |
def ints_to_rgb(r, g=None, b=None):
"""Convert ints in the [0...255] range to the standard [0...1] range.
Parameters:
:r:
The Red component value [0...255]
:g:
The Green component value [0...255]
:b:
The Blue component value [0...255]
Returns:
The color as an (r, g, b) tuple in... | d24e336f13beb3538428724ce56532f1efb8fb6f | 618,197 |
def _format_optionals(optionals, extra_optionals):
"""
Formats a list of optional clauses into a string containing
multiple OPTIONALs.
"""
optional_str = ""
if optionals:
for optional in optionals:
optional_str += """OPTIONAL
{{
{}
}}
... | b110d43639c2ac97487a4349d37b1f7219068e17 | 618,199 |
def sortbykey(dictlist, sortkey):
"""
Sort a list of dictionaries by a common key and return the sorted list
>>> sortbykey([{'A': 3}, {'A': 1}, {'A': 2}])
[{'A': 1}, {'A': 2}, {'A': 3}]
:param dictlist: a list of dictionaries sharing a common key
:param sortkey: a dictionary key used t... | bcb0b5ce8097a85327473465621a44460335c493 | 618,200 |
def venv(request):
"""Fixture for --venv."""
return request.config.getoption("--venv") | 94d457ae9c32d52c92373061af9fd13cdd51b4b3 | 618,201 |
def slice_geo_data(ld):
"""given a list of raw record dictionaries, pull out geo data,
and convert to floats
"""
float_fields = ["latitude","longitude"]
result = []
for rec in ld:
newr = {}
for field in float_fields:
newr[field] = float(rec[field])
result.app... | 1f4ef50fc7866e37297f7e1b977143251842b87b | 618,204 |
def missing_edges(x,y):
"""
Counts edges that are present in the original structure (x) but
are missing in the learned structure (y). (lower is better)
"""
missing = 0
for rv in x.nodes():
if not y.has_node(rv):
missing += x.degree(rv)
else:
for child in x.children(rv):
if child not in y.children(rv... | 3c27a0bbc89dc28b5b9cfa1eeebd826c957967a0 | 618,205 |
def constraint_adjacent(m, n) :
"""Returns True if m and n are adjacent, otherwise False.
Assume m and n are ints."""
if abs(m-n) == 1:
return True
else:
return False
raise NotImplementedError | 7f434886d299e45d0e8b0ac6dc4b796d29cb43d2 | 618,206 |
from bs4 import BeautifulSoup
def parse_html_for_quotes(html):
""" Parse html for quote pattern, return list of quotes that match """
soup = BeautifulSoup(html, features='html.parser')
quotes = soup.find_all('li')
return [str(q) for q in quotes if '<ul>' in str(q)] | bdf206b37d6274d7a853d50558f724a08287bbf6 | 618,207 |
def bin2str(b):
"""
Binary to string.
"""
ret = []
for pos in range(0, len(b), 8):
ret.append(chr(int(b[pos:pos + 8], 2)))
return ''.join(ret) | f7a8db4b5d70284520d734309e8d1c4c5dc8f247 | 618,212 |
def grad_l2_squared(beta, rng=None):
"""Gradient of the function
f(x) = (1 / 2) * |x|²_2,
where |x|²_2 is the squared L2-norm.
"""
return beta | 3c85e04d55e674db3e8ea3783ed9973228581c2f | 618,214 |
from functools import reduce
from operator import mul
def accumulating_product_reduce(items):
"""Calculate the accumulating product of a list.
Uses functools.reduce.
Arguments:
items {[list]} -- List of numbers.
Returns:
[list] -- List of accumulating products.
"""
return [... | cac1adf5f0b048ba2a8a4005e7cddc99a1206e57 | 618,218 |
from typing import Any
from typing import Sequence
def _get_value_str(value: Any, arguments: Sequence[str], index: int = 0) -> str:
"""Returns the `value_str` given parsed `arguments` and the desired `index`.
Args:
value: The input value to generate a string representation for.
arguments: The input seque... | 55f26ee7b9c286df53efa83d3251a660f69242f9 | 618,219 |
def has_snapshot(html):
"""Given a BeautifulSoup instance containing the HTML of a search result webpage
from archive.org, this method will search the HTML for an id='error' tag. If there
is such a tag, that means there is no snapshot of the URL searched for. If there is
no error tag, that means there i... | 4119cc5ffa9066cc36ff7d82f05d308da9bdee0b | 618,220 |
def split_fields(fields):
"""
>>> from comma.csv.applications.csv_eval import split_fields
>>> split_fields('')
[]
>>> split_fields('x')
['x']
>>> split_fields('x,y')
['x', 'y']
"""
return fields.split(',') if fields else [] | 349366fed95103c5b793c08e04a8ea748f2e171e | 618,222 |
import torch
from typing import Optional
def lower_vector_to_matrix(
lower_flat: torch.Tensor, matrix_dim: Optional[int] = None
) -> torch.Tensor:
"""Convert a valid vector to a lower triangular matrix.
Parameters
----------
vector : torch.Tensor
vector
matix_dim : Optional[int]
... | 90422f4f218240470f9a9181965d7dcce678daf0 | 618,225 |
def sound_exposure(pressure, fs, axis=-1):
"""
Sound exposure :math:`E_{T}`.
:param pressure: Instantaneous sound pressure :math:`p`.
:param fs: Sample frequency :math:`f_s`.
:param axis: Axis.
.. math:: E_T = \\int_{t_1}^{t_2} p^2 (t) \\mathrm{d}t
"""
return (pressure**2.0/fs).sum(ax... | b06083b7e44c24fe526f74934e26c650b13e6951 | 618,226 |
def get_default_nncf_compression_config(h, w):
"""
This function returns the default NNCF config for this repository.
The config makes NNCF int8 quantization.
"""
nncf_config_data = {
'input_info': {
'sample_size': [1, 3, h, w]
},
'compression': [
{
... | 34784f65ea6b2c1fd953f7d6ac0395ba9300bf43 | 618,227 |
def f2c(f):
"""Fahrenheit to Celsius"""
return (f - 32)*5/9 | 2b623abaccc1ff89b217861849f3d9c4df515d6e | 618,230 |
def get_weighted_completion_scores(job_list):
"""
Gets the weighted completion score for a set of jobs by taking the sum of
the total time elapsed at the end of each job * job weight.
"""
total_length, score = 0, 0
for job in job_list:
total_length += job[1]
score += (total_leng... | 41e69b152c1ffedf6e0b3ee64da53fbc963d2a24 | 618,231 |
import pytz
def validate_timezone(zone):
"""Return an IETF timezone from the given IETF zone or common abbreviation.
:param str zone: in a strict or a human-friendly format
:return: the valid IETF timezone properly formatted
:raise ValueError: when ``zone`` is not a valid timezone
Prior to check... | 25cdc74124625502455e261e33d969b70ea3e3ab | 618,232 |
def cipher(text, shift, encrypt=True):
"""
Encrypt the text using shift coding.
Args:
text (str): represent the source text
shift (int): the shift size
encrypt (bool): True for encrypt and False for decrypt
Returns:
str: represent the cipher
Examples:
>>> ciph... | b2552dd7cc74cff4ff4b02e7955835e2bad058a9 | 618,235 |
def is_git_diff_header(diff_header):
"""Returns True if the diff was generated with git."""
return any(l.startswith('diff --git') for l in diff_header.splitlines()) | 4a09fb015535e680ec6c6684599e8b1ce1d74eff | 618,238 |
def str2bool(v):
"""
Converts a string to boolean
Args:
v (str) : string to be percieved as true or false
Returns:
(bool) : True or false based on string
"""
return v.lower() in ("yes", "True", "true", "t", "1") | 5754c116fe3ec030ae057078e0369aa1463bd06d | 618,239 |
def hamming_distance(input_bytes_1: bytes, input_bytes_2: bytes):
"""Takes in two byte strings. Outputs the hamming distance (https://www.tutorialspoint.com/what-is-hamming-distance) between those strings"""
xor_result = ((a ^ b) for (a, b) in zip(input_bytes_1, input_bytes_2))
joined_binary_string = "".join([bin(nu... | 11c882f8cce935e9b3dcf31e7b286c9b1f7f9f6e | 618,241 |
def string_date_range(hr_data):
"""
Using the list of tuples from the `parse_heart_json` method, determines the date range
of data present. Two outputs are possible:
1) Data for only one day: Will return the one day in month-day-year format: i.e. Dec16-2019
2) Data spanning multiple days: Will retu... | 1de438c35882261dfd800830834fdb84406b55e9 | 618,244 |
def line_to_coords(linestring):
"""
Converts (Multi)LineString to 2d-array of Point coordinates
Parameters
----------
line : (Multi)LineString
Returns
-------
coords : list
List of points representing the endpoints of the (Multi)LineStrings
"""
allowed_types = [
... | f934ca9a624872fda1e1d850b9fd2bf89af5927f | 618,251 |
def draw_line(x, y, x2, y2, stroke_width=0.5, color='black', stroke_dasharray='None'):
"""Draw a line for svg"""
return f'<line x1="{x}" y1="{y}" x2="{x2}" y2="{y2}" stroke="{color}" \
stroke-width="{stroke_width}" stroke-dasharray="{stroke_dasharray}" />' | c4888134a8a969874a155a62121882f1882b51ca | 618,253 |
import torch
def mean_jaccard_index(target, predictions):
"""
Semantic segmentation metric. Calculates mean intersection over union over all classes.
Works for batches of data.
"""
intersection = torch.logical_and(target, predictions)
union = torch.logical_or(target, predictions)
interse... | c001b3a07a5c2ce899d9979245d4f5a40b6acf43 | 618,258 |
def _bonds(mol, node_idx, use_order=True):
"""
Returns how many explicit bonds the specified node has. If use_order is
False, treat all bonds as if they are order 1.
Parameters
----------
mol : nx.Graph
The molecule.
node_idx : hashable
The node to look at. Should be in mol.
... | a5313ccb67631f28bb07aeabadbf449bb47e5e81 | 618,264 |
import re
def getCleanSpaces(inputText, minimumLength=0, lineCutTrigger="", keepSpaceSepators=False):
"""
Removes spaces and comments from the input expression.
`minimumLength` of a line to not be ignored
`lineCutTrigger` all lines after a line starting with this string will be ignored
... | c300b46242e8efa5490a89efa217c7f631e95d23 | 618,267 |
def get_mean_param(params):
"""Return the parameter used to show reconstructions or generations.
For example, the mean for Normal, or probs for Bernoulli.
For Bernoulli, skip first parameter, as that's (scalar) temperature
"""
if params[0].dim() == 0:
return params[1]
elif len(params) ==... | 6887b3f867d96f83d70a97074d5799d09b81b1f2 | 618,268 |
def longest_common_subsequence(x: str, y: str):
"""
Finds the longest common subsequence between two strings. Also returns the
The subsequence found
Parameters
----------
x: str, one of the strings
y: str, the other string
Returns
-------
L[m][n]: int, the length of the longes... | b6580553ddeec716f3b5b035fb1b11002c195b65 | 618,270 |
def multimax(k, key=None):
"""Returns an in-place list of the max values in the k.
Args:
k(lazy iteration, generator or list): contains the list of items
key: a key by which to sort the items
Returns:
A list of the max values in the input.
"""
p = list(k)[:]
if not p: r... | 7cde36cd6609f8b01e2f154729f3e49e25e20184 | 618,271 |
import json
def get_json_bytes_for_sign_data(sign_data):
"""
Convert SignData object to JSON bytes for signing.
Args:
sign_data (SignData): The sign data object.
Returns:
bytes: The sign data in JSON bytes.
"""
return json.dumps(sign_data._asdict(),
sor... | c76e64d3bba8d7ebb7579bfa97f53ae7ce1a19f3 | 618,274 |
import torch
def _to_complex(x: torch.Tensor) -> torch.Tensor:
"""View real tensor as complex."""
return torch.view_as_complex(x.view(*x.shape[:-1], -1, 2)) | dc53c99773f8d6e2d6e01ceb499f3a1a0a87aaad | 618,277 |
def calc_row_checksum(row_data):
"""
Method for calculating the checksum for a row.
"""
min_val = 0
max_val = 0
first = True
for cell in row_data.split("\t"):
if first:
min_val = int(cell)
max_val = int(cell)
first = False
else:
... | b91b1fdff98b1afc3afa4398daa80ae27d666b14 | 618,279 |
import re
def binder_spec_from_github_url(github_url):
"""
Converts GitHub origin into a Binder spec.
For example:
git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master
https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master
"""
if github_url.endswith('.git... | 69471a74895e24d365cc042732bbd65c5c01bdd1 | 618,283 |
import torch
def aggregate_accuracy(test_logits_sample, test_labels):
"""
Compute classification accuracy.
"""
return torch.mean(torch.eq(test_labels, torch.argmax(test_logits_sample, dim=-1)).float()) | eff4f6b6613f053bed8d790502e967cb74d58bab | 618,285 |
def _float(text):
"""Return text as a float (PRIVATE)."""
if text is not None:
try:
return float(text)
except Exception:
return None | 0ffab7e9ba5055f77f52665456552204a6d390bd | 618,286 |
import glob
import logging
def get_all_waves(directory: str) -> list:
"""
Return all wave files (recursively) from the provided directory in sorted order
:param directory: path to the directory
:return: list of files (possibly empty)
"""
files = glob.glob(directory + '/**/*.wav')
if not fi... | 3802e4b07339a842396e52c944b5eefbb412b1a1 | 618,288 |
import math
def _isnum(val) -> bool:
"""Returns true when the given value is a number."""
if isinstance(val, (float, int)):
return not math.isnan(val)
return False | 4f9d22e60783ae83f37877d50f004344fc1b8286 | 618,289 |
def year_month_period(start_year, start_month, end_year, end_month):
"""
Generate all year,month tuple between given time period
:param start_year: int, start from this year
:param start_month: int, start from this month
:param end_year: int, end to this year(inclusive)
:param end_month: int, en... | df03fb333ccdcb1471c4e1f64431602698487075 | 618,293 |
def clean_whitespaces(text):
"""
Remove double whitespaces and trailing "." and "," from text.
"""
return ' '.join(text.strip().rstrip(".,").split()) | 6f4e8d1c9dbc3234f953a77439eb867fb89e3802 | 618,297 |
from typing import List
import random
def ga_crossover(parents: List[List[str]],
num_pop: int) -> List[List[str]]:
"""Create the next generation from parents
A random index is chosen and genes up to that index from
the first chromosome is used and genes from the index to
the end is us... | 5329b763e24ec5652e7381a23a5758d638967f56 | 618,298 |
import time
def timestampToSeconds(timestamp):
"""
Given a timestamp in the form '2021-08-17:21:41:18', return the number of
seconds since epoch. Returns 0 on invalid input.
"""
fmt = '%Y-%m-%d:%H:%M:%S'
try:
time_struct = time.strptime(timestamp, fmt)
except ValueError:
return 0
return int(... | b925a66ca4a5842cdcad942ce542d90389de291d | 618,302 |
def calculate_issn_checkdigit(s):
"""
Given a string of length 7, return the ISSN check digit.
"""
if len(s) != 7:
raise ValueError('seven digits required')
ss = sum([int(digit) * f for digit, f in zip(s, range(8, 1, -1))])
_, mod = divmod(ss, 11)
checkdigit = 0 if mod == 0 else 11 -... | b8b3e78361e1bd630a0d38888619b151f0ce7a5a | 618,305 |
import copy
def pop(x, k):
"""Returns copy of dict `x` without key `k`."""
x = copy.copy(x)
del x[k]
return x | 653e280f09d6314f350a3d6bfab100ae7d3cee60 | 618,306 |
import torch
from typing import Tuple
def intersectionAndUnionGPU(
output: torch.Tensor,
target: torch.Tensor,
K: int,
ignore_index: int=255,
cuda_available: bool=True
) -> Tuple[torch.Tensor,torch.Tensor,torch.Tensor]:
"""
Note output and target sizes are N or N * L or N * H * W
... | 010ab0a65e5c0f2eb7ab960fa13a4d731319344c | 618,307 |
def create_switch_to_profile_payload(context: str, device: str, profile: str):
"""Create and return "switchToProfile" dictionary to send to the Plugin Manager.
Args:
context (str): An opaque value identifying the instance's action you want to modify.
device (str): Unique device identifier.
... | 75fe23f391c39a6b9663e26f885469c1fd5f8188 | 618,308 |
import base64
import quopri
def decode_payload(encoding, payload):
"""Decode the payload according to the given encoding
Supported encodings: base64, quoted-printable.
:param encoding: the encoding's name
:param payload: the value to decode
:return: a string
"""
encoding = encoding.lower... | 2f657159edcfa20fdf55a0b2f6d248b3eaecf1e9 | 618,310 |
def reverse_int(i):
"""
Given an integer, return an integer that is the reverse
ordering of numbers.
reverse_int(15) == 51
reverse_int(981) == 189
reverse_int(500) == 5
reverse_int(-15) == -51
reverse_int(-90) == -9
"""
negative = i < 0
tmp = abs(i)
tmp_str = str(tmp)[::-... | 557aa041a00b06b5213ee438895c523fbd06ab94 | 618,312 |
def delattr_call(obj, attr_name, *args, **vargs):
"""
Call the deleter for the attribute `attr_name` of `obj`.
If the attribute is a property, pass ``*args`` and ``**kwargs`` to the deleter (`fdel`); otherwise, ignore them.
"""
try:
return getattr(type(obj),attr_name).fdel(obj,*args,**vargs... | 554eef98d745777597739faea27a21d6e626d2a9 | 618,313 |
def get_smaller_and_greater(a, b):
"""compare two elements then return smaller and greater"""
if a < b:
return a, b
return b, a | b110e1115841ef9220fd85fa789e684c6ae91d91 | 618,314 |
def det(tensor):
"""Detach a torch Tensor to a cpu numpy version
Args:
tensor (torch.Tensor): A tensor to be detached and turned into an ndarray
Returns:
(ndarray): The same data as an ndarray
"""
return tensor.cpu().detach().numpy() | d37c9ede3fd7e40fa56bb6ddbf42d83b94c1787b | 618,315 |
def sext_8(value):
"""Sign-extended 8 bit number.
"""
if value & 0x80:
return 0xffffff00 | value
return value | 735f7c7ae62878f688335bf4f58bbf20f0a0444d | 618,335 |
def b2mb(num):
""" convert Bs to MBs and round down """
return int(num/2**20) | a1f6f555c464edddc928bb23a212b1672d7f0c13 | 618,336 |
def lower(value):
""" Functor to return a lower-case string.
"""
return value.lower() | 55fed20deadf8fb51549623de4236a7594f9a247 | 618,339 |
import torch
def sample_z(batch_size, dim_z, device, distribution=None):
"""Sample random noises.
Args:
batch_size (int)
dim_z (int)
device (torch.device)
distribution (str, optional): default is normal
Returns:
torch.FloatTensor or torch.cuda.FloatTensor
"""... | b61a03a30c6bdcb20c3caebf0e620abccb310151 | 618,340 |
def is_short_term(date1,date2):
"""
Return True if it's a short term gain for buying at date1 and selling at date2
"""
date1Months = date1.year*12+date1.month
date2Months = date2.year*12+date2.month
if date2Months - date1Months > 12:
return False
elif date2Months - date1Months == 12 ... | 3a9aa10aed5ecab62924bdef41a9e04a25fd45e5 | 618,344 |
def get_pxe_address_x64(virtual_address, pte_base):
"""
The functions gives the PTE address for a virtual address
Based on: https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
@param virtual_address: the virtual address to convert
@param pte_base: the base address for... | f6ad914de74d9cb0150860f101a4082fc34168fb | 618,345 |
def normalize_list(items, width, filler = None):
#===============================================================================
"""
Normalize list to a specified width, truncating or filling as needed.
Filler data can be supplied by caller. The filler will be copied to each
added item. None will be us... | c0620b66adde654eedcdd6f92709eacff96a644a | 618,347 |
def draw_sure(deck, n, exclusions):
"""Draw n cards from a deck but skip any cards listed in
exclusions. Please note this func always returns a list, unlike
native deuces draw function.
"""
drawn = []
while len(drawn) < n:
c = deck.draw()
if c in exclusions + drawn:
c... | 4e43998962e15916b397843cb1ea254b10a1c1b9 | 618,350 |
def getEntireFamilyTree(cls):
"""Returns a list of classes subclassing the input class
One large caveat is it can only locate subclasses that had been imported somewhere
Look to use importEntirePackage before searching for subclasses if not all children
are being found as expected.
"""
return ... | 4a4d829ff9678110ddfc43606c85d5ca6575ada4 | 618,352 |
def _supports_fileno(stream):
"""
Returns True if 'stream' supports the file descriptor and allows fileno().
"""
if hasattr(stream, 'fileno'):
try:
stream.fileno()
return True
except IOError:
return False
else:
return False | 692c286a598845267a531b196c8c9d2d89d5f0c3 | 618,355 |
def base_count(seq):
""" Count the number of A, C, G, T in a given sequence """
return seq.count('A'), seq.count('C'), seq.count('G'), seq.count('T') | 723ea1708e11570a7aab5d008bda16867f262252 | 618,359 |
import torch
def get_r1_src_target(k_in=2, k_out=1):
"""
Returns the r1 experiment src and targets tensors
"""
# torch.set_default_dtype(torch.float64) # works best in float64
points_tens = torch.tensor(
[[-k_in, 0, 0], [k_in, 0, 0]]).unsqueeze(0).float()
target_points_tens = (
... | d5d7690d2b4f72edf3fd8d1fffcbf6026de9d7f1 | 618,364 |
import collections
def duplicates(arr):
"""
Returns a list of Axis objects which have duplicate names in arr
Arguments:
arr: The iterable of Axis objects to check for duplicates in.
Returns:
list of Axis: duplicate Axis found in arr
"""
# group axes by name
axes_by_name =... | 5fd57de5a54a2e8b01beb71aa93e835d5e35fdc7 | 618,365 |
def find_zone(domain, zones):
"""
Does the domain exist in a tracked zone?
"""
if domain is None:
return ""
for zone in zones:
if domain.endswith("." + zone) or domain == zone:
return zone
return "" | 036adcbb31cefaf823f8959e0136ceaa01ea1481 | 618,366 |
def config(ctx):
"""show current cli configuration"""
return """Base url: %(base_url)s
username: %(username)s""" % {
'base_url': ctx.obj.connection.api_url,
'username': ctx.obj.connection.credentials.username
} | 1ba94d1b42cf034cecc1cf06601e64518f1ad82a | 618,368 |
def min_max_comparison(value, value_to_compare, condition):
"""
Translate the values and condition to comparison operator and get result.
:param value: (numeric) original value
:param value_to_compare: (numeric) value to compare with, the value to beat.
:param condition: (str) min/max condition. If ... | c3de036c507fd34ae7647bfe87830f28db654a1a | 618,376 |
def check_preconditions(key, value):
"""
Check if the filter applies to the current element in the syntax tree.
:param key: The type of pandoc object.
:type key: str
:param value: The contents of the object.
:type value: list | str
:return: ``True`` if the filter applices to the current ele... | 071ad5524587f10ae57dc221aab48e033a24b784 | 618,381 |
def as_dict(keys, values):
"""Take two iterables, one with keys and other
with values and return a dict
"""
try:
_ = iter(keys)
except TypeError:
return {keys: values}
return dict(zip(keys, values)) | dd55e74addcc84e5629e20c1796e37f1a918f734 | 618,382 |
def divide(a: int, b: int = 1) -> int:
"""Simple division function for testing run_hook
Args:
a (int): Dividend
b (int, optional): Divisor. Defaults to 1.
Returns:
int: Quotient
"""
return int(a/b) | 441606ec728a478b1b961437632d590c07b0bef5 | 618,393 |
def parse_repeat(n, msg) -> tuple:
"""
Parse the argument for the repeat command.
:param n: the number of times of repeat.
:param msg: the message to be repeated.
:return: (number of times of repeat, message to be repeated)
:raises ValueError:
if n is not an integre between 1 and 5, or m... | 960ea3320d75a974e319b356363946980ddfd2af | 618,399 |
def delete_list_of_keys( d, *keys ):
"""
elimina las keys de un dicionario
Parameters
==========
d: dict
dicionario del que se eliminaran las keys
keys: tuple
llaves a eliminar
Examples
========
>>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' }
>>>delete_list_of_keys... | cc24baad026e5a12af3c4c42468d019142a2a681 | 618,401 |
def zero_cross(data, zero=0):
"""
Calculate the number of times the data
crosses the `zero` value.
Parameters
----------
data : ndarray
Time series of data values.
zero : scalar, default=0
Crossing point to analyze.
Returns
-------
cross : float
Number of times the data crosses `zero`.
"""
return (... | 794914183346e7fff0e95fb33cb325d73664a781 | 618,402 |
def remove_by_min_overlapping_users(keen_keen_graph, min_overlapping_user):
"""It only keeps the edges whose weight >= min_overlapping_user"""
filtered = {}
for ka, ints in keen_keen_graph.items():
new_ints = {kb: n_users for kb, n_users in ints.items() if n_users >= min_overlapping_user}
if... | 045ba80f0021a634ef24571bb8fed1e4a49a6dd5 | 618,405 |
def _format_as_index(indices):
"""
Construct a single string containing indexing operations for the indices.
For example, [1, 2, "foo"] -> [1][2]["foo"]
:type indices: sequence
"""
if not indices:
return ""
return "[%s]" % "][".join(repr(index) for index in indices) | da1e383d0a4cf9ffdbe7c0066bfe3c71e074a30f | 618,407 |
def get_dfg_graph(dset):
"""
return the dfg graph for a dataset
"""
# helpesk dfg graph
graphs = {}
graph = {}
graph[0] = {1:3644, 3:108, 0:1} #end of process instance 1, start of instance 2
graph[3] = {1:105}
graph[1] = {8:3483,1:394}
graph[8] = {2:42, 9:851, 6:4150,4:9, 7:4} #... | 250a8da707bc54c3c593eb5b223b02833b1995c1 | 618,409 |
def _ical_escape(text):
"""
Format value according to iCalendar TEXT escaping rules.
from https://github.com/collective/icalendar/blob/4.0.2/src/icalendar/parser.py#L20
"""
return (
text.replace(r'\N', '\n')
.replace('\\', '\\\\')
.replace(';', r'\;')
.replace(',', r'... | e0a7c62ca0297b34d5cfe65a7c90fae7fce1215f | 618,410 |
def at_left_obstacle(Rover, safe_pixs=50):
"""
Check if obstacle is to the left of rover.
Keyword arguments:
safe_pixs -- minimum number of pixels to keep from left obstacles
"""
nav_pixs_left = len(Rover.nav_angles_left)
return nav_pixs_left < safe_pixs | 52990cba3e04c38a334901b2eeb73ae039d0d9e9 | 618,411 |
def get_llvm_type(context, type):
"""Returns the LLVM Value corresponsing to a Numba type.
Args:
context: The LLVM context or the execution state of the current IR
generator.
type: A Numba type object.
Returns: An Python object wrapping an LLVM Value corresponding to the
... | e6ee3fd34a8ff30cbd5b29ab16acc0cb36bd3680 | 618,415 |
def diagpq(p,q=0):
"""
Return string equivalent metric tensor for signature (p,q).
"""
n = p+q
D = ''
rn = list(range(n))
for i in rn:
for j in rn:
if i ==j:
if i < p:
D += '1 '
else:
D += '-1 '
... | 97f52da6a6b488eb74f9d9b759de0b2907b4295d | 618,416 |
from typing import Union
from pathlib import Path
def find_base_index_path(alignment_index: Union[Path, str]) -> Path:
"""
When BWA indexes a reference genome, it produces five files:
reference.fasta -> [
reference.fasta.amb
reference.fasta.ann
reference.fasta.bwt
referen... | 06bae0be079984d5da4079b13ec27b6292245a9d | 618,422 |
def arraybin2(arr, rowbin=1, colbin=1):
"""
Binning a 2D array
:Parameters:
arr : numpy array
array to bin
rowbin : int | 1
row binning
colbin : int | 1
column binning
:Return:
arrbinned : numpy array
binned ar... | 3fc881964a441604ea65eba450d2202941ce931b | 618,423 |
def _decode_text(text: list[int]) -> str:
"""
Converts the text from numerical values to literal values.
Uses the inverse table conversion of that used in _encode_text.
Args:
text (list[int]): List with each position
representing a character to be decoded.
Returns:
str:... | 709377126eb486ff8806cb9c514ae9ba5fb51ecc | 618,424 |
def is_key_value_exist(list_of_dict, key, value):
"""
Check if at least one value of a key is equal to the specified value.
"""
for d in list_of_dict:
if d[key] == value:
return True
return False | b4ea785fdfe3f9b1284f0afd1e58af67817cedd0 | 618,426 |
def _create_ip_range(range_start, range_end):
"""
Given a start ip, eg 192.168.1.1, and an end ip, eg 192.168.1.254,
generate a list of all of the ips within that range, including
the start and end ips.
"""
ip_range = []
start = int(range_start[range_start.rfind('.')+1:])
end = int(range... | af3d96862c0522d3737c2587ff0c57477fc4cad3 | 618,427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.