content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def slave_passes_blacklist(slave, blacklist):
"""
:param slave: A single mesos slave with attributes
:param blacklist: A list of lists like [["location_type", "location"], ["foo", "bar"]]
:returns: boolean, True if the slave gets passed the blacklist
"""
attributes = slave['attributes']
for ... | 4aff5e7b7200cf9046f510ec554d575782700735 | 154,274 |
from typing import List
import re
def number2kansuuzi(tokens: List[str]) -> List[str]:
"""
>>> number2kansuuzi(['大引け', 'は', '147円', '高', 'の', '14000円'])
['大引け', 'は', '147円', '高', 'の', '1万4000円']
>>> number2kansuuzi(['10000円', '台'])
['1万円', '台']
"""
def convert(token: str) -> str:
i... | 39175f36e755bac96d0e0f978e3d436efd499b51 | 607,359 |
def _is_undefok(arg, undefok_names):
"""Returns whether we can ignore arg based on a set of undefok flag names."""
if not arg.startswith('-'):
return False
if arg.startswith('--'):
arg_without_dash = arg[2:]
else:
arg_without_dash = arg[1:]
if '=' in arg_without_dash:
name, _ = arg_without_das... | a058a89836e32e749c3aeb0d583553f90e079185 | 599,526 |
def needs_batch_dim(image):
"""Determines whether an image has or is missing a batch dimension."""
if not hasattr(image, 'shape'):
raise TypeError(
"Can only determine batch dimensions for numpy arrays or tensors.")
if len(image.shape) == 2:
return True
elif len(image.shape) ... | 4452af473d2a308666458e1abb8e265d8aecb976 | 366,967 |
def remove_keys_filter(row,keys):
""" Remove given keys from the row """
for key in keys:
row.pop(key,None)
return row | 38b0020c931c8c62949b613941daa8270bc1c052 | 314,574 |
def is_letter(_code : int) -> bool:
""" Detect letter """
lower : bool = _code >= 65 and _code <= 90
upper : bool = _code >= 97 and _code <= 122
#space_lowdash : bool = _code == 95 or _code == 32
space : bool = _code == 32
if lower or upper or space:
return True
return False | 61f6a69c7e43d5a4e1e53c610e82b5c5b7634304 | 175,807 |
import asyncio
async def review_embed(bot, ctx, embed) -> bool:
"""Given an embed, send it and wait for a review"""
m = await ctx.send("Preview:\nYes | No", embed=embed, delete_after=35)
await m.add_reaction("👍")
await m.add_reaction("👎")
def check(reaction, user):
return user.id == ctx... | 52205d7ff693db486aa886f14b230194470e6f46 | 265,750 |
def first_index_not_in_set(seq, items):
"""Returns index of first occurrence of any of items in seq, or None."""
for i, s in enumerate(seq):
if not s in items:
return i | 22a72425ea961ebfef5351c7332af6ddb09b4d02 | 340,139 |
def apmapr(a, a1, a2, b1, b2):
"""Vector linear transformation.
Map the range of pixel values ``a1, a2`` from ``a``
into the range ``b1, b2`` into ``b``.
It is assumed that ``a1 < a2`` and ``b1 < b2``.
Parameters
----------
a : float
The value to be mapped.
a1, a2 : float
... | 52615600981a96b75d3ace32a2dd9d4c2d350e43 | 487,667 |
def euclidean_dist(p1, p2):
"""
Returns the euclidean distance between points (p1, p2)
in n-dimensional space.
Points must have the same number of dimensions.
"""
if len(p1) != len(p2):
raise ValueError("Points must have the same number of dimensions.")
return sum((d1 - d2) ** 2 for... | 3f2ff5da253e14765074b97e322bc3042fbe58b9 | 606,272 |
from typing import List
def strip_common_prefix(parts: List[List[str]]) -> str:
"""Find and remove the prefix common to all strings.
Returns the last element of the common prefix.
An exception is thrown if no common prefix exists.
>>> paths = [["a", "b"], ["a", "b", "c"]]
>>> strip_common_prefix... | 92cc5e3a7e2cd65ed967ddd9ea57329d04b14cee | 152,654 |
from typing import Iterable
import re
def filter_regex(regex: str, data: Iterable[str]) -> Iterable[str]:
"""
filter_regex takes a string iterator and returns an iterator that only has
values that match the regex.
"""
r = re.compile(regex)
return filter(lambda datum: r.search(datum), data) | 4d7eeafeeaf9bd39add157159dfc0cf1f130432b | 363,696 |
def partition_seq(seq, size):
"""
Splits a sequence into an iterable of subsequences. All subsequences are of the given size,
except the last one, which may be smaller. If the input list is modified while the returned
list is processed, the behavior of the program is undefined.
:param seq: the list... | 599e48da0db19b7fe7a5730a0659ac7ca130abf2 | 654,424 |
def all_diff(*values):
"""Returns True if all values are different, False otherwise"""
return len(values) is len(set(values)) | 6bda2a82c1971d16177d73ca84dfe01795f265ad | 546,436 |
import re
def isIdentPub(s):
"""Returns True if string s is valid python public identifier,
that is, an identifier that does not start with an underscore
Returns False otherwise
"""
if re.match(r'^[a-zA-Z]\w*$',s):
return True
else:
return False | 361ce246de4efd8e005938d3b9d3b810787d9dec | 327,813 |
import torch
def rms(samples):
"""Root Mean Square (RMS)."""
return torch.sqrt((samples**2).mean()) | 989d5faae35b09f1860ab7e327dbe1a7f24b765d | 90,025 |
def node_is_inline(node):
"""
Test if a node is in an "inline" context.
"""
return node.parent.tagname in ['paragraph'] | 274c64c4e2109240b9928d79e5f25755437eefc3 | 383,434 |
import six
def _ExtractKey(option):
"""Helper to extract a key for an option dictionary."""
if " " in option:
# The option was quoted so it is a value.
return None
if six.ensure_str(option, "utf-8").startswith("--"):
return option[2:]
elif six.ensure_str(option, "utf-8").startswith("-"):
retur... | 3ba8c6318b7a92d60514621ba2f162bb37d970d3 | 240,939 |
def _IsCurrentCommitTagged(raw):
"""True if the current commit is tagged, otherwise False"""
# If this condition hits, then we are currently on a tagged commit.
return (len(raw.split("-")) < 4) | 8b72de72230e4f9f0013ec4c1a8d705dde7e66fe | 163,977 |
import re
def preprocess_ents(label, text):
"""
Preprocess an entity
Parameters
----------
label: str:
The named entity label
text: str:
The name entity text
Returns
-------
tuple: returns a tuple of strings containing the label and text
"""
pattern = ':... | 17d99929266a630733faa101d227a318db561990 | 640,948 |
def get_role(action):
"""Maps action from input to a role (promote or demote)"""
if action == "demote":
return 'user'
if action == "promote":
return 'admin' | 1291927260b667d58572e2f4ea44f1063c76a744 | 126,079 |
import re
def get_single_junction_overhang(cigar):
"""
Returns the number of reads left/right of a junction as indicated
by the LEFTMOST N in a cigar string. Return -1, -1 for reads that don't span
junctions.
:param cigar: string
:return left: int
:return right: int
"""
cigar_over... | 96331b12ba05eb13ae783aab76589a5556fb1166 | 31,947 |
def fixed_len(s, length, append=None, no_linebreaks=False, align_right=False):
"""Returns the given string with a new length of len
If the given string is too long, it is truncated and ellipsis are added.
If it is too short, spaces are added. Linebreaks are removed.
Args:
s (str): The string t... | e872e10e5f28e9aa275516ccf93b70a174dfa5d1 | 259,499 |
def mag(initial, current):
"""
Calculates the magnification of a specified value
**Parameters**
intial: *float*
initial value (magnificiation of 1)
current: *float*
current value
**Returns**
magnification: *float*
the magnification of the current value
"""
... | abc8d3603f11e62f57a62c47dc372b4b9ea19b0c | 701,722 |
def parse_vars(vars):
"""
Transform a list of NAME=value environment variables into a dict
"""
retval = {}
for var in vars:
key, value = var.split("=", 1)
retval[key] = value
return retval | e2c6ae05cdf0151caaf8589eb7d7df90dcdd99a1 | 709,480 |
from typing import Any
def repr_or_str(o: Any) -> str:
"""
repr_or_str function
Returns a string representation of the input:
- If input is bytes returns the hex representation
- If input is str returns the string
- If input is None returns empty string
:type o: ``Any``
:param o: Inpu... | 5e334d639ef7e6bb7d373d2264db29683077b23b | 122,758 |
def _remove_batch_rule(rules):
"""Removes the batch rule and returns the rest."""
return [(k, v) for (k, v) in rules if k != "batch"] | 0bd19cb9a4be86c89571820244aeb37d030658b8 | 461,692 |
import pytz
def parse_timezone(tz):
"""
Parse a timezone description into a tzinfo object
>>> parse_timezone("America/Los Angeles")
<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>
>>> parse_timezone("America/Los_Angeles")
<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>
"""
return p... | 7fb4f4f6506afb3f2057fae5020cb904f88e16a6 | 106,920 |
def remove_group(api, assessment_id):
"""Remove all groups from an assessment."""
allGroups = api.groups.get()
for group in allGroups:
if group.name.startswith(assessment_id):
api.groups.delete(group.id)
return True | 0513ecd4fe9ebfcb6e70cbe69dd540b40401dd7e | 442,516 |
def _fortran_float_converter(in_string: bytes) -> bytes:
"""
This utility converts fortran double precision float strings to python float strings by replacing D with e
:param in_string: The fortran string containing double precision floats
:return: The string ready for ingest by python float utilities
... | da838699d1f26354970c3984fa2a47e7344c5e52 | 340,627 |
def get_p2p_scatter_pfold_over_mad(model):
"""
Get ratio of median of period-folded data over median absolute
deviation of observed values.
"""
return model['scatter_pfold_over_mad'] | b2cb60d8ea744059a1dbaecd0a280cb5a499e70a | 343,669 |
def find_period(samples_second):
""" # Find Period
Args:
samples_second (int): number of samples per second
Returns:
float: samples per period divided by samples per second
"""
samples_period = 4
return samples_period / samples_second | c4a53e1d16be9e0724275034459639183d01eeb3 | 707,539 |
from typing import Union
def _to_int(value: Union[str, int]) -> int:
"""Converts a vendor or product ID, specified either in hexadecimal notation
as a string, or in decimal notation as an integer, to its integer
representation.
Parameters:
value: the value to convert
Returns:
the... | 2b2153493a6e80564db32ac9735387853c9aa4f3 | 367,279 |
import logging
def logger(name: str) -> logging.Logger:
"""
Obtain a logger which is configured with the default refinery format.
"""
logger = logging.getLogger(name)
if not logger.hasHandlers():
stream = logging.StreamHandler()
stream.setFormatter(logging.Formatter(
'(... | e90451475d4587d4bf1e88ebf070db3df2405b46 | 181,509 |
def clean_venue_name(venue_name: str) -> str:
"""Clean the venue name, by removing or replacing symbols that are not allowed in a file name.
Args:
venue_name: Original venue name.
Returns:
Cleaned venue name.
"""
return venue_name.replace("*", "").replace("/", "_").replace(" ", "_"... | 90b6f8b3787af17750c548bb816383bf8a5b07a4 | 695,990 |
def list_manipulation(lst, command, location, value=None):
"""Mutate lst to add/remove from beginning or end.
- lst: list of values
- command: command, either "remove" or "add"
- location: location to remove/add, either "beginning" or "end"
- value: when adding, value to add
remove: remove ite... | c847257ea5508f60b84282c3ac8237b43cd3825a | 709,243 |
def public(view):
"""
Decorator that indicates that a view is visible to all users, including
anonymous users.
It's for purely semantic purposes and has no functionality.
"""
return view | 8f4160e40e57ca29f0feae63ae8220109384d44b | 506,654 |
from functools import reduce
def get_average(lst):
"""
Function to compute the average of a list of values.
Arguments:
list of values: In this case these are timedelta objects
Returns:
average: Average value of the timedelta objects
"""
average = reduce(lambda a,b: a + b, lst... | fee0575808e5a91a12127ad7491f97507786e46c | 284,653 |
def filter_out_non_passable_items(config: dict, depth: int):
"""Recursively filters out non-passable args started with '.' and '_'."""
if not isinstance(config, dict) or depth <= 0:
return config
return {
k: filter_out_non_passable_items(v, depth - 1)
for k, v in config.items()
... | fc586a4f2135bec7c91c7060485dd6fb92a55308 | 198,321 |
def argToInt(value):
""" Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes.
In case of neither KB or MB was specified, 0x prefix can be used.
"""
for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ]:
i... | 089d1d674b249d8ddb24432cce8df013bb9c8abb | 657,278 |
from typing import List
from typing import Tuple
def percent_edges_in_other_edges(edge_list: List[Tuple[str, str]], edge_list2: List[Tuple[str, str]]) -> float:
"""Calculate what proportion of the first list of edges can be found in the second list.
checks edges in both node orders to account for directed ed... | 0d7d7c80c1d560034ec59a2575d88563e8d250d9 | 579,971 |
def predict_cluster(vectorizer, model, abstract):
"""Map the given abstract to its cluster."""
Y = vectorizer.transform([abstract])
prediction = model.predict(Y)
return prediction[0] | 18a1aa71960015e19073056e130ee58787c3deb0 | 457,454 |
def bits_to_number(bits):
"""convert the binary representation to the original positive number"""
res = 0
for x in bits:
res = res * 2 + x
return res | 9280170a3bfbad88363cd886384a2253e83d5db9 | 50,193 |
def jumpTime(player, jump=30):
"""
jumpTime:
jump in episode time
@param player (vlc.MediaPlayer):
@param jump (int): a time jump, in seconds
"""
if player.is_playing()==1:
currentTime = player.get_time()
player.set_time(currentTime + jump*1000)
else:
print('... | 3058df1b6f57d18c0c0428fef063f0186f2e288e | 372,056 |
import string
import base64
def encode_base64_ondemand(s):
"""
Decode string to base64 if it isn't ascii. Also put leading ': ' so that LDAP
knows the string is b64 encoded.
>>> encode_base64_ondemand("Hej")
' Hej'
>>> encode_base64_ondemand("Höj")
": SMO2ag=="
"""
if not all(c in... | 90ae315600aa60688e3c4ee1088d11696f443bb9 | 450,521 |
def check_special_value(expected, value):
"""Check if value equals to Null, Not null, empty or expected value."""
if expected == "NULL":
return value is None
elif expected == "NOT_NULL":
return value is not None
elif expected == "EMPTY":
return value == ""
elif expected == "N... | d4309ea27742fd38c8980d86314e00dc1ccf54a2 | 230,301 |
def to_datetime_string(value):
"""
gets the datetime string representation of input value with utc offset.
for example: `2015-12-24T23:40:15+03:30`
:param datetime value: input object to be converted.
:rtype: str
"""
return value.isoformat(timespec='seconds') | 12e053a5ea0ab582f0212a8b74591f6ae72310ea | 188,896 |
def convert2Ddistance(dists, header=None, row_order=None):
"""returns a 2 dimensional list, header and row order
Parameters
----------
dists : dict
a 1Ddict with {(a, b): dist, ..}
header
series with column headings. If not provided, the sorted top level dict
keys are used.
... | 26e99589bcfcb6aa319d991b216dd669e2b7bd8b | 412,626 |
def generate_order_by_clause(params):
"""Generates order_by clause strings from the given list.
:param list params: A list of column names to sort the result to::
params = [
'id', 'name', 'full_path', 'parent_id',
'resource', 'status', 'project_id',
'task_type', 'en... | 9f9a74d6a16b53cd65542a000fe4215a9d16ced1 | 32,669 |
import torch
def batch_to_time(x: torch.Tensor, block_size: int) -> torch.Tensor:
"""
Inverse of time_to_batch. Concatenates a batched time-signal back to
correct time-domain.
Args:
x: The batched input size [Batch * block_size × Channels × Length]
block_size: size of the blocks used ... | 38aa42fdb83bf9f326f371815e67b5b2396c090c | 489,837 |
import json
def load_json(json_path):
"""Load JSON file and parse it to a native object.
Args:
json_path: str
File path from which to load the JSON file.
Returns:
object : Typically a nested structure of ``list`` and ``dict`` objects.
"""
with open(json_path, "r", encoding="... | 2e5a8171d4489fb53fb940adbddcee408dc08e48 | 404,209 |
import base64
def base64_string_encode(data):
"""
Encodes a string into it's base64 string representation
:param data: str: string to encode
:return: str
"""
return base64.b64encode(data.encode('utf-8')).decode('utf-8') | 542937dbf8050e0e2adb97c5f34b9852ca62af6a | 351,103 |
def _get_rows(x):
"""
Return 2D signal rows.
"""
return [x[i, :] for i in range(x.shape[0])] | 5de2275515b9b5df7139cb96c0a13f89e4bc9ccf | 549,655 |
def sentence_starts(sentences, start_length):
"""
Returns a list of tuples that contain the first start_length number of words from a list of sentences.
"""
# pull all the sentence starts
starts = []
for sentence in sentences:
if len(sentence) > start_length:
starts.append(tu... | 92be32a9669e7ae2addf6e3c9fa23044564c9915 | 433,231 |
def ask(question, options, default):
"""
Ask the user a question with a list of allowed answers (like yes or no).
The user is presented with a question and asked to select an answer from
the given options list. The default will be returned if the user enters
nothing. The user is asked to repeat his... | baf3e9e00b01573921e94bd7c508ee7fb0381392 | 581,268 |
def is_str_like(content):
"""Check if an instance is string-like
Parameters
----------
content : str
The content to check
Returns
-------
bool
True if is str like else False
Note
----
Function identical to :func:`numpy.is_str_like`, credits to the author
"""... | 23453c67c05ea003d1f658f31958cf22726a3815 | 149,187 |
import pkg_resources
def get_renderer_name(name: str) -> str:
""" Return the name of the renderer used for a certain file extension.
:param str name: The name of the extension to get the renderer name for. (.jpg, .docx, etc)
:rtype : `str`
"""
# `ep_iterator` is an iterable object. Must convert... | 26ea05431111b1d00afccf519606cf1864183a7b | 531,076 |
def _get_dihedral_rb_torsion_key(dihedral, epsilon_conversion_factor):
"""Get the dihedral_type key for a Ryckaert-Bellemans (RB) dihedrals/torsions
Parameters
----------
dihedral : parmed.topologyobjects.Dihedral
The dihedral information from the parmed.topologyobjects.Angle
epsilon_conver... | 6e706227adff4892be02a799720274c0419c0427 | 594,229 |
def clear_line(buf, linenum):
"""Clear a line
Args:
buf (obj): Nvim buffer
linenum (int): Line Number
Returns:
suc (bool): True if success
"""
buf[linenum] = []
return True | 1dc668d1b882286e7b9f44c2580d61a7447ec997 | 498,492 |
def standard_slices(problem_size, num_agents, overlap=0):
"""Create standard slices for a problem.
We assume that the problem size is exactly divisible by the number
of agents; hence all agents have exactly the same subproblem size.
Parameters
----------
problem_size : int
problem size... | d98e9b6b4be42352bcd9f1060074bcdb1809fb78 | 108,073 |
def values_of_series_of_invest(
rates_between_periods,
invest_amounts=None,
final_only=True,
invest_at_begining_of_period=False,
):
"""
Total values after investing each of the values in invest_values, the running total increasing
by the percentage in rate_between_values from one investment ... | 96df5c3a713ba4de97a46709d64c5d4a0b3904a4 | 300,287 |
def create_table(title: str, data: dict, headers: str, **kwargs):
"""
Creates table given object and headers
Usage: `{% create_table 'carparks' carpark 'name|description' %}`
"""
return {'title': title, 'headers': headers.split("|"), 'data': data, **kwargs} | 6ef4abb5859bd179fdf4064b5dbe6df075eb75d0 | 530,447 |
def bool_yes_no(process, longname, flag, value):
""" Phrase Boolean values as 'YES' or 'NO' """
if value==True:
return "YES"
if value==False:
return "NO"
# Anything else wasn't a bool!
raise ValueError("Flag value '%s' wasn't boolean." % repr(value)) | b6b5d63eb56284c3ccd475ad8b666727bda186ca | 566,508 |
def find_an_even(L):
"""Assumes L is a list of integers
Returns the first even number in L
Raises ValueError if L does not contain an even
number"""
for i in L:
if i % 2 == 0:
return i
raise ValueError('L does not contain an even number.') | 82a987adea07bc291c38a35d45c01a93f9d9d1bb | 239,093 |
import sqlite3
def open_db(database):
""" Helper functiom to open a database connection
:param db: database file
:return: connection object and cursor
"""
# Make connection to storage database
conn = sqlite3.connect(database)
c = conn.cursor()
return conn, c | 5718a9c1b74382aa7412067ebd0e8c2387be1a09 | 53,708 |
def eulerC1(c2,rho,R):
"""Compute the optimal Euler consumption of old generation
Args:
rho (float): discount parameter
c2 (float): consumption old generation
R (float): gross return on saving
Returns:
(float): optimal Euler consumption o... | 16b2c8aec5d05836383cd2256ccf67b7c218ef85 | 375,654 |
import requests
def fetch_output(input_prefix, input_value, output_prefix, enable_semantic_search=False):
"""Find APIs which can produce the output_prefix
:arg str input_prefix: The prefix of the input, e.g. ncbigene, hgnc.symbol.
:arg str output_prefix: The prefix of the output, e.g. ncbigene, hgnc.symb... | 1ed8f27923695ab7587f49083070aecb040987f6 | 17,839 |
def merge(lst1: list, lst2: list, into: list) -> list:
"""Merge two sorted lists into a single sorted list.
Complexity: O(n) time, O(1) space.
"""
i1 = 0
i2 = 0
i3 = 0
while i1 < len(lst1) and i2 < len(lst2):
# The comparison must be <= for the merge (and hence the sort) to be
... | eeea39da20d3a3998e94a355f61f4f9cee6fad80 | 454,517 |
def has_annotations(doc):
""" Check if document has any mutation mention saved. """
for part in doc.values():
if len(part['annotations']) > 0:
return True
return False | 6b57893bc35af45950ec2eeb5008b663028d48bf | 704,287 |
def is_palindrome(number):
"""
Check if a number is a palindrome.
:param number: The int to check.
:returns: True if the number is a palindrome, else False.
"""
number_string = str(number)
reversed_number = ''.join(reversed(number_string))
return number_string == reversed_number | a1842ec14f095adc6d5c3ea6c1e7e137e457adc7 | 102,100 |
import uuid
def is_valid_uuid(candidate):
"""Test if provided string is a valid uuid version 4 string.
candidate (str): uuid to check
Returns:
bool: True if is a valid uuid v4, False if not
"""
try:
uuid.UUID(candidate, version=4)
return True
except ValueError:
... | 0c0dbe1626d1ebac85782382678904ddb873b8e2 | 545,810 |
def generate_component_annotation_overview(elements, db):
"""
Tabulate which MIRIAM databases the component's annotation match.
Parameters
----------
elements : list
Elements of a model, either metabolites, reactions, or genes.
db : str
One of the MIRIAM database identifiers.
... | 848287af1078ae42c25fe52a8dd8f682a1749078 | 224,040 |
from typing import Union
from pathlib import Path
def find_table_file(root_project_dir: Union[str, Path]) -> Path:
"""Find the EUPS table file for a project.
Parameters
----------
root_project_dir
Path to the root directory of the main documentation project. This
is the directory cont... | 59673a83e0ba9f0bb95e0b4d90f32fa48ac7fdef | 178,234 |
import math
def std(lst):
"""
Helper function that calculates the standard deviation of a numeric sequence
"""
average = sum(lst) / float(len(lst))
variance = sum(list(map(lambda x: (x - average) ** 2, lst))) / float(len(lst))
stdev = math.sqrt(variance)
return stdev | 060be5305eda97f2054862f2ca07c688498245f5 | 248,977 |
def test_datasource_connection(connection, body, error_msg=None):
"""Test a datasource connection. Either provide a connection id, or the
connection parameters within connection object.
Args:
connection: MicroStrategy REST API connection object.
body: Datasource Connection info.
err... | 96b1f08e7313583c12cb10d1b76bf3bdc17b2ab8 | 646,006 |
def get_N_RL(sym_list):
"""
Compute a value denoting the maximum "number of reachable locations", ($N_{r}$), over all possible locations.
From the paper:
Formally $N_{r}$ is calculated from an empirical symbolic time series $\mathcal{T} = \{s_{1}, s_{2}, \ldots, s_{m}\}$,
with the set of all possi... | 67b89b1d74dd2e24c60e5958ae6e8a7f09e1eb19 | 47,977 |
import asyncio
def run_async_method(loop, method, *args):
"""
Run async method.
:param loop: the loop to run method until complete.
:param method: method to run.
:param args: arguments of method.
:return: result of "method".
"""
if not loop:
loop = asyncio.get_event_loop()
... | 852ff87d9766a57227f466bd68b6825c17c840b6 | 606,966 |
def count(matches):
"""Count occurrences of taxa in a map.
Parameters
----------
matches : dict of str or dict
Query-to-taxon(a) map.
Returns
-------
dict
Taxon-to-count map.
"""
res = {}
for taxa in matches.values():
try:
# unique match (sca... | de8c790c102b5f4da4c42a0ac5d1ec03b09d3bc0 | 188,093 |
def get_city(df, city_name=None, city_index=None):
"""
returns an info dict for a city specified by `city name` containing
{city_name: "São Paulo", city_ascii: "Sao Paulo",
lat: -23.5504, lng: -46.6339, country: "Brazil", iso2: "BR", iso3: "BRA",
admin_name: "São Paulo", capital: "adm... | 2a18eb4f4dba2714db522acee58ddd2474915fd2 | 682,178 |
def comment(strng,indent=''):
"""return an input string, commented out"""
template = indent + '# %s'
lines = [template % s for s in strng.splitlines(True)]
return ''.join(lines) | 42386b7ed8de9127d7224481a5f5315d39b6ae97 | 707,661 |
def _index_keys(columns):
"""
Take all the key columns and build a list of possible index
tuples that can arise from them.
For example, given the following schema: "varId|dbSNP,gene"
these are the possible index key lists:
[['varId', 'gene'],
['dbSNP', 'gene']]
"""
keys = [k.split... | ee7cb47b0abe6936ba7f5cfd720a4e92854a0d90 | 628,431 |
def merge_dicts(*dict_args):
"""Merge given dicts into a new dict.
Examples::
>>> merge_dicts({"a": 1, "b": 2}, {"c": 3, "b": 20}, {"d": 4})
{'a': 1, 'b': 20, 'c': 3, 'd': 4}
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result | 1e5bcc15f8d0af402658ce0910850199a1fb90ff | 265,630 |
def insert_or_ignore(session, model, **kwargs):
"""
Adds record to a table (model) or ignores if already exsits based
on 'wid'
Args:
session: db session
model: datastore module table
kwargs: record arguments
"""
if "wid" in... | 065116b81b7ff7db648499f53db2af328991c8fe | 253,944 |
def format_error_message(message, **kwargs):
"""
Replaces the tokens by `kwargs`.
:param message: The message that contains the tokens.
:param kwargs: The args used to replace the tokens.
:return: The message formatted.
"""
if isinstance(message, str):
message = message.format(**kwa... | acb06712d6fd4221bf6a222c381553eefdf2a1c2 | 254,427 |
def remove_last_dim(arr):
"""
Reshapes the given array to remove the last dimension (this makes
the assumption that the last dimension is of shape 1).
"""
return arr.reshape(arr.shape[0], arr.shape[1]) | 8a59c48b08ad5702deebd241e67c7e3379fa9765 | 496,113 |
import csv
def read_test_data(csv_path):
"""
To read the test data from a CSV file. This CSV file should only contain
data and no other value.
:param csv_path: the path to the CSV file
:return: the read data in a two dimension array
"""
with open(csv_path, newline='') as f:
reader... | 403dfd98408ce35fa71bc5c52c8126fa4e597df3 | 141,430 |
def setup_walkers(cfg_emcee, params, level=0.1):
"""Initialize walkers for emcee.
Parameters
----------
cfg_emcee: dict
Configuration parameters for emcee.
params: asap.Parameter object
Object for model parameters.
level: float, optional
Returns
-------
ini_position... | 7a03d5f451a71f60acd64e7b22e852af99a9cefe | 683,536 |
import struct
def read_4(stream):
""" read 4 byte (long) from stream """
return struct.unpack('<L', stream.read(4))[0] | a663f14a3e71c4aed2aa94be5404d836d12035d4 | 611,643 |
def custom(K_0, D_0, L_S, D_S):
"""
Defines the material properties for a custom nonlinear material.
Args:
K_0(float) : Bulk modulus of the material in Pascal for SAENO Simulation (see [Steinwachs,2015])
D_0(float) : Buckling coefficient of the fibers for SAENO Simulation (see [Steinwac... | f3c39bd057ffb308a768e8427ed47eb065ad2fbc | 473,941 |
def in_line(patterns, line):
"""Check if any of the strings in the list patterns are in the line"""
return any([p in line for p in patterns]) | e7715de654ac00ff39a1349767052a7a5df2a37d | 221,686 |
def computeExtendedDependencies(dependencies):
"""
Computes the extended dependencies for the given dependencies.
The extended dependencies are defined as follows:
In the following let E denote the set of existential variables
(i.e. the keys of <dependencies>)
ext_dep(e):=dep(e) union {v in E | dep(v) < de... | 47d0e7603c6bf1cc843b0f420287495ddedcfbb9 | 70,097 |
def checkIdenticalExistingVectors( newgraphs, vectors, v ):
"""
Checks if there exists a vector from 'vectors' corresponding to one of the
graphs from 'newgraphs', that is equal to v (ie, checks if a vector equal to
v has already been generated). If such vector exists, it returns True, and
else it r... | 66797a351bf1666e59630789aa2aefbda9a820d3 | 597,578 |
import hashlib
def file_get_md5_checksum(path, block_size= 2 ** 20):
"""Returns MD% checksum for given file."""
# Function source originally from : https://gist.github.com/juusimaa/5846242.
md5 = hashlib.md5()
try:
file = open(path, 'rb')
while True:
data = file.read(block_size)
if not data:
break
... | d1c51ffd25509d4fcfc36b4c037a67cd4cb22d3e | 125,246 |
def get_changed_pipeline_structure(existing_pipeline, data, is_input=True):
"""
Get pipeline input/output type and field if pipeline input/output changed
:param ubiops.PipelineVersion existing_pipeline: the current pipeline version object
:param dict data: the pipeline input or output data containing:
... | 801ba92efcbf07cc7c9eae26db7cc2b0085f18a1 | 515,556 |
def check_box(iou, difficult, crowd, order, matched_ind, iou_threshold, mpolicy="greedy"):
""" Check box for tp/fp/ignore.
Arguments:
iou (torch.tensor): iou between predicted box and gt boxes.
difficult (torch.tensor): difficult of gt boxes.
order (torch.tensor): sorted order of iou's.
... | af80d9ae0b3ab910b4231d536e6f35d5e5e6c3a4 | 441,423 |
import itertools
def get_chemical_gene_combinations(_dict_):
"""
Parameters
----------
_dict_ : dictionary
Dictionary with annotated entities. Keys: PMID, Values: another
dictionary with keys 'chemicals' and 'genes' and value the
annotation mark
Returns
-------
co... | c87b842709125d1c174e89ba56ad3766bc915bce | 314,759 |
def calc_t_duration(n_group, n_int, n_reset, t_frame, n_frame=1):
"""Calculates duration time (or exposure duration as told by APT.)
Parameters
----------
n_group : int
Groups per integration.
n_int : int
Integrations per exposure.
n_reset : int
Reset frames per integrat... | 4cd01d8dd0dde19c09112a1fd4f328266fcacb03 | 134,233 |
import statistics
def fitness(population, goal):
"""measure fitness by comparing attribute mean vs target"""
avg = statistics.mean(population)
return avg/goal | d1024b87f5b2da4fc555874496db6709a51e9ea4 | 526,650 |
def get_defaults(env_id):
""" Returns dict of default arguments. """
return {
"num-train-steps": 100e6 if "Flagrun" in env_id else 50e6,
"nenvs": 128 if "Flagrun" in env_id else 32,
"num-runner-steps": 512,
"num-epochs": 15,
"num-minibatches": 16 if "Flagrun" in env_id else 4,
"l... | a9ae0461b0f2c135d811a03b068cca1c23078c79 | 316,796 |
import re
def camelize(name):
"""Covert name into CamelCase.
>>> camelize('underscore_name')
'UnderscoreName'
>>> camelize('AlreadyCamelCase')
'AlreadyCamelCase'
>>> camelize('')
''
"""
def upcase(match):
return match.group(1).upper()
return re.sub(r'(?:^|_)(.)', upcas... | 8d3e5dc5669ebce33801edc6b9dd2d6ecf871c11 | 237,663 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.