content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def dict2channel_data(task_dict):
"""
Given a task_dictionary (obtained with dict(task))
will return group_name and channel_data ready to be
sent to django channel.
Returned ``channel_data`` (second item of returned tuple) will
have ``type`` trandformed as follows:
new_type = <shortname>.<... | 298826364aed99659f7dfae6dc63ef70020cc59e | 438,046 |
def cfm2m3s(cfm):
"""convert flow cfm to meter^3/second"""
return cfm / 2118.880003 | 7b37ebb63d53ee0dc835c6dc11a24fe133e84f56 | 520,269 |
def _get_build_filename(build):
"""A unique but semi-readable filename to reference the build"""
return "%s-%s-%s.build" % (build.project.domain.name, build.project.name, build.id) | 16121cf6ffaf94f981e03c6513d553e3c3a04b56 | 156,154 |
def elements_of_list_same(iterator):
"""Check is all elements of an iterator are equal.
:param iterator: a iterator
:type iterator: ``list``
:rtype: ``bool``
Usage::
>>> from haproxyadmin import utils
>>> iterator = ['OK', 'ok']
>>> utils.elements_of_list_same(iterator)
Fa... | a08554e6c22b567dde77f79ca30804996eeb9b51 | 369,074 |
def yesno(value, icaps=True):
"""
Return 'yes' or 'no' according to the (assumed-bool) value.
"""
if (value):
str = 'Yes' if icaps else 'yes'
else:
str = 'No' if icaps else 'no'
return str | 9bff0a577c81c900159d9650e78a75c6869e94b9 | 652,071 |
def i16_pcm(wav):
"""Convert audio to 16 bits integer PCM format."""
if wav.dtype.is_floating_point:
return (wav.clamp_(-1, 1) * (2**15 - 1)).short()
else:
return wav | d8f0695be89f997f94dd51ccd06529eaf0cf95c3 | 147,206 |
def CollapsePath(path_tokens):
"""
CollapsePath() takes a list of Strings argument representing a
directory-like path string
(for example '/SUB1A/Sub2A/../Sub2B/sub3b/../sub3c/entry'),
and replaces it with a version which should contain no '..' patterns.
(In the example above, it returns /SUB1A/... | afd4766b5bf688fdb1e9d0d18266f27914c9ee4f | 600,865 |
def get_topic_name(num_partitions, msg_size_bytes):
"""Generate test-topic names describing message characteristics"""
return "parts{}-size{}".format(num_partitions, msg_size_bytes) | 925b4762069e0b5f7642926a7cfd57ba027169ce | 491,522 |
def filter_by_name(cases, names):
"""Filter a sequence of Simulations by their names. That is, if the case
has a name contained in the given `names`, it will be selected.
"""
if isinstance(names, str):
names = [names]
return sorted(
[x for x in cases if x.name in names],
key... | 64c3f4b0b77ba8106b276b74e6a01bd3f6c91ce4 | 75,015 |
def omega(delta_lambda):
"""Calculate the Buchdahl chromatic coordinate."""
return delta_lambda/(1 + 2.5*delta_lambda) | b8659be24bd94b85bf8d82ee4a7b9991628de1ba | 102,476 |
def merge(*dicts):
"""Returns a dict that consists of the rest of the dicts merged with
the first. If a key occurs in more than one map, the value from the
latter (left-to-right) will be the value in the result."""
d = dict()
for _dict in dicts:
d.update(_dict)
return d | 9a624f0b440b1bf0281918abaa7988968495a39d | 73,917 |
def _build_visited_site_rule_info(client, url):
"""Creates a UserListRuleInfo object targeting a visit to a specified URL.
Args:
client: An initialized Google Ads client.
url: The string URL at which the rule will be targeted.
Returns:
A populated UserListRuleInfo object.
"""
... | 12c04398416b233e6c42451d7c1b5fed1e8a7aec | 244,237 |
from typing import Any
def is_boolean(value: Any) -> bool:
"""Checks if value type is boolean.
Parameters
----------
value: Any
The value to check.
Returns
-------
bool: True if value is boolean, False otherwise.
"""
bool_values = ("yes", "y", "true", "t", "1", "no", "n",... | 35f9ddcea21bc04eace7c9480e28b2494930c2d0 | 412,518 |
def spacing(area, shape):
"""
Returns the spacing between grid nodes
Parameters:
* area
``(x1, x2, y1, y2)``: Borders of the grid
* shape
Shape of the regular grid, ie ``(ny, nx)``.
Returns:
* ``[dy, dx]``
Spacing the y and x directions
"""
x1, x2, y1, y2... | 71e803ac463651f67d4f77f876af201cae719059 | 209,015 |
import math
def pdf(x, mu: float = 0, sigma: float = 1):
"""Probability density function"""
return (1 / (math.sqrt(2 * math.pi) * abs(sigma)) *
math.exp(-(((x - mu) / abs(sigma)) ** 2 / 2))) | ba239b8060e92213c5278849026e96a99cec47cc | 193,375 |
import re
def _get_ip_from_response(response):
"""
Filter ipv4 addresses from string.
Parameters
----------
response: str
String with ipv4 addresses.
Returns
-------
list: list with ip4 addresses.
"""
ip = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)... | ac36a3b729b0ce4ba13a6db550a71276319cbd70 | 707,238 |
def get_library_version() -> str:
"""
Returns the version of minecraft-launcher-lib
"""
return "3.2" | 11edc1daa5811f51cfc73ef399c85a7933dc3b2f | 192,074 |
def mixin(cls):
"""
Decorator applied to a class that indicates the class is a mixin and should not
participate in interface verification until it is part of another class.
Example:
class MyInterface(Interface):
@staticmethod
@abstractmethod
def Method1(): pa... | df40e2631736220b624dd8e08d4e6f52250aa5f7 | 373,543 |
import six
def remove_nones(in_dict):
"""
Recursively remove keys with a value of ``None`` from the ``in_dict`` collection
"""
try:
return dict(
(key, remove_nones(val))
for key, val in six.iteritems(in_dict)
if val is not None
)
except (ValueErr... | f742d716fbeb148ca292a7b9f7e8f0ff7eb7e7dc | 336,564 |
def get_mod(modulePath):
"""Import a module."""
return __import__(modulePath, globals(), locals(), ['']) | ccecb2d3c24dc1bc78f08bbedebde0206b2bce7e | 344,869 |
import re
def isComment(line, comment):
"""
Is the line a comment.
"""
if re.match(str('[ \t]*' + comment), line):
return True
else:
return False | db1d030eac29829650cabf451c315b3470b37a77 | 296,055 |
from typing import Dict
def merge_default_parameters(hyperparams: Dict, default: Dict) -> Dict:
"""
Checks if the input parameter hyperparams contains every necessary key and if not, uses default values or
raises a ValueError if no default value is given.
Parameters
----------
hyperparams: di... | 9299dc66910aba10575cf5726236a92cbba2e393 | 343,245 |
import random
def random_selection(population, fitness, eq):
"""
Selection of the best two candidates given fitness function
:param population: list of numpy array
:param fitness: function to fit
:param eq: params to fitness function
:return: tuple of two more promising individuals (numpy vect... | 208f6d958bfdaf339233abd69c4918cf6a75cf5b | 662,549 |
def cross(x, y):
"""Calculate the cross product of two vectors.
The two input vectors must have the same dimension :math:`d <= 3`.
This function calls the `cross` method of :class:`~taichi.Vector`.
Args:
x (:class:`~taichi.Matrix`): The first input vector.
y (:class:`~taichi.Matrix`):... | 992c34e8433ec07193ebc47a40e2b808ebbebfc1 | 453,434 |
def hyperfactorial(k: int) -> int:
"""
Returns the hyperfactorial of the number, the product of all positive integers to the power of themselves smaller
or equal to the number.
By convention an empty product is considered 1, meaning hyperfactorial(0) will return 1.
:param k: A positive integer
... | 0cff03cc91909461de2a0a6c607a029b4aba5c8d | 280,734 |
def max_value_1_highest_weight_value_ratio(weight_value_tuples, max_capacity):
"""
Solution: Compute the max value by finding the item with the highest
weight to value ratio and use it as many times as possible until we need
to find a smaller one that fits into the knapsack but still has the
greatest weight to val... | 00ef3d3c0b155fc47b189ac52660eaf8aba4cf0a | 591,322 |
def cast_string_to_int_error(what):
"""
Retrieves the "can not cast from string to integer" error message.
:param what: Environment variable name.
:return: String - Can not cast from string to integer.
"""
return "ERROR: " + what + " value cannot be cast from string to int" | 9c3645d9cdf9fc90893ab5a7762cea6ccfd8c73e | 177,125 |
def form_neg_pair(info, mode='trn'):
"""
Returns a list of 2 indices correspondign to index values
of info which store different characters.
"""
y = info[info.Mode == mode]
curr_ind = y.Char.sample(1).index.values[0]
curr_char = y.Char.loc[curr_ind]
new_ind = y[~y.Char.isin([curr_char])]... | 1c3a83d41154507a794a270e4d35e5a6bbde5d70 | 437,427 |
def append_story_content(elements, content_type, content):
"""
Append content to story_content list in markdown elements
"""
if 'story_content' not in elements:
elements['story_content'] = []
elements['story_content'].append((content_type, content))
return elements | cdc9b9b3349dd1c7faf5a04218164daad9f7899f | 397,306 |
def cell_multiply(c, m):
""" Multiply the coordinates (cube or axial) by a scalar."""
return tuple( m * c[i] for i in range(len(c)) ) | 43647e4ba857a0eca616a391a614f16494202e4b | 406,749 |
def get_loc_lab(lat, lon):
"""Construct the USGS location label
Construct a lat/lon location label such as n01e002 that is part of the
labels used by the "Staged Products" HTTPS web directory access for USGS
1-arcsecond DEM TIFF files.
Args:
lat (int): Latitude
lon (int): Longitude... | f6f789f480a9998fdecc2420802a0e818ae37c1e | 598,980 |
def set_dtypes_features(df, groups, dtypes):
"""Split the columns of a df according to their given group.
Parameters:
-----------
df : pandas.DataFrame
The data frame to be splitted.
groups : pandas.Series
Series with the features' names or indexs as index and the group as
v... | e0f96b8e686921b8b6f1c5a5359a02d79b0acd7b | 374,213 |
import re
def count_words(word, sentence):
"""Count the number of occurrences of a word in the sentence"""
match = re.compile(word)
return len(match.findall(sentence)) | c6fc464b884bafd335a1d25052408afff2eae2dc | 404,687 |
import math
def getDirectedDist(obj1, obj2, metrics):
"""
Returns delX, delY, delZ, delO from obj1 to obj2
"""
(x1, y1, z1) = metrics[obj1][0]
(x2, y2, z2) = metrics[obj2][0]
return [x2-x1, y2-y1, z2-z1, math.atan2((y2-y1),(x2-x1))%(2*math.pi)] | a08e4d6a4c1709f3183994dce9614df1b9c37939 | 469,659 |
def insert_trace_index_as_event_attribute(log, trace_index_attr_name="@@traceindex"):
"""
Inserts the current trace index as event attribute
(overrides previous values if needed)
Parameters
-----------
log
Log
trace_index_attr_name
Attribute name given to the trace index
... | f2ed24f88b2e45b2397ecb8e78e07b1b6a9aa0fc | 162,078 |
def extract_sample_qc_status(qc_file_handle, file_label):
"""Parses a MEND QC results file handle to "PASS" or "FAIL".
QC results parsing to something else (or failing to parse) indicate a major
failure in the QC script and should interrupt analysis.
The qc_file_handle is as provided by TarFile.extractf... | 1fc99c6b61c790bc424a62ace8da4becaa7f6c8b | 145,632 |
from datetime import datetime
def datetime_to_unix_ms(dt: datetime) -> int:
"""Convert a Python ``datetime`` object to a Unix millisecond timestamp.
This is necessary as the timestamps Cook returns in its API are in
milliseconds, while the Python ``datetime`` API uses seconds for Unix
timestamps.
... | 63b0ed18c800616bfeba2503a26b52d51f452411 | 591,984 |
def pl (listoflists):
"""
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
"""
for row in listoflists:
if row[-1] == '\n':
print(row, end=' ')
else:
print(row)
return None | 1b9bdcbbf46d14477a9ef0165d680e5a48c8dac7 | 199,459 |
def product_except_self(nums: list[int]) -> list[int]:
"""Computes the product of all the elements of given array at each index excluding the value at that index.
Note: could also take math.prod(nums) and divide out the num at each index,
but corner cases of num_zeros > 1 and num_zeros == 1 make code inele... | 15090d4873b0dec9ea6119e7c097ccda781e51fa | 708,576 |
from pathlib import Path
def get_final_path(output_path: Path, set_type: str, samp_name: str) -> Path:
"""Get path of output file
Arguments:
output_path {Path} -- root of output path
set_type {str} -- data set type
samp_name {str} -- name of sample
Returns:
Path -- comple... | 0406a6e6684c8f42b781f0a1d53a05a9ca3fb7cb | 617,338 |
def icevol_corr_prep(record, agelabel, age_in_ky):
"""
Prepare ``record`` for the ice volume correction.
Converts all numbers to actual number dtypes, converts
Age to integer years and sets it as index.
Parameters
----------
record : pandas DataFrame
A pandas DataFrame containing t... | ec0c0d14230f655ebced932b7a99701e36e4d537 | 235,564 |
def url_build(*parts):
"""Join parts of a url into a string."""
url = "/".join(p.strip("/") for p in parts)
return url | aebc2e6118f77d8439c7b7819d8eada54b417f4d | 133,783 |
def dimension_matrice(matrice: list, n: int) -> bool:
"""
Description:
Vérifie si la matrice est de taille n.
Paramètres:
matrice: {list} -- Matrice à vérifier.
n: {int} -- Taille de la matrice.
Retourne:
{bool} -- True si la matrice est de taille n, False sinon.
... | b2922341af4fbed473fb7d459d2e4850cb979fe0 | 488,721 |
def colored(msg, color=None, background=None, bold=None, underline=None):
"""
Return string formatted using ANSI escape codes. Supports 256 colors.
https://upload.wikimedia.org/wikipedia/en/1/15/Xterm_256color_chart.svg
:param string: String to format.
:param color: Color of text.
:param backg... | 54e0dee61ff755862e48800bf7be8d47ea359806 | 442,123 |
def get_arn(vpc_id, region, account_id):
"""Creates a vpc ARN."""
return f'arn:aws:ec2:{region}:{account_id}:vpc/{vpc_id}' | 2ac5a32d2246ccd689fccca5470889b54e48df37 | 176,385 |
def calculate(triangle):
"""Returns the maximum total from top to bottom by starting at the top
of the specified triangle and moving to adjacent numbers on the row below"""
def calculate_helper(row, col):
"""Returns the maximum path value of a specified cell in the triangle"""
if row == len... | 2c7d3c96841db960414e043aaebdae83b81eaf7d | 537,291 |
def precision(xs, ys):
"""Precision of list `xs` to list `ys`."""
return len([x for x in xs if x in ys]) / float(len(xs)) if xs else 0. | 601866550480572c79e397b8a2e9a6fcbcc83e10 | 567,918 |
import requests
def check_uri(uri, timeout=5):
"""
Checks if a uri returns response of 200 if it is requested
Will return True if the response is 200, false otherwise
:param uri: URI to request
:param timeout: how long to return False, if we do not get a response
:return: True/False
:rtype... | fdb5f34facef287d47900508e124e81b88c57fc7 | 593,274 |
def str_input(prompt: str) -> str:
"""Prompt user for string value.
Args:
prompt (str): Prompt to display.
Returns:
str: User string response.
"""
return input(f"{prompt} ") | ac6c3c694adf227fcc1418574d4875d7fa637541 | 4,474 |
def linear_extrap(x1, x2, x3, y1, y2):
"""
return y3 such that (y2 - y1)/(x2 - x1) = (y3 - y2)/(x3 - x2)
"""
return (x3-x2)*(y2-y1)/(x2-x1) + y2; | 9f45b7443ded484c2699e9bd545a3d551a39313e | 100,750 |
import torch
def subsequent_chunk_mask(
size: int,
chunk_size: int,
num_left_chunks: int = -1,
device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
"""Create mask for subsequent steps (size, size) with chunk size,
this is for streaming encoder
Args:
siz... | e06afa21778e92725e07445048ab60a2cfa24af0 | 671,190 |
def deltaf(series, baseline):
"""calculate deltaf over f for a signal (1D array)"""
deltaf = series - baseline
return deltaf / baseline | 06899e35b6229aca983bdc01207bddba53b56c6f | 593,627 |
import yaml
def read_types(infile):
""" Reads types definitions from a file. """
with open(infile, "r") as stream:
return yaml.safe_load(stream) | f325a5a69eb1c718fe80ed9c77528354b86a15ae | 351,564 |
def normdirpath(path):
"""Make a directory path end with /"""
if not path.endswith('/') and path != '':
path += '/'
return path | 32ab35955e1a3b60e18c3ec36f469989fa42d135 | 233,092 |
import ast
def safe_eval_maths(expr):
"""
Safely evaluates a maths expression,
such as (2**32-1) or (400|0x1000)
Will throw a ValueError exception on error
Note: This is still susceptible to memory or CPU exhaustion by putting
in large numbers.
"""
allowed = (ast.Expression, ast... | 54dcf13679dffa13c02bb7920f7d24b1626e3285 | 587,625 |
def _get_command_name(command_raw):
"""Return command name by splitting up DExTer command contained in
command_raw on the first opening paranthesis and further stripping
any potential leading or trailing whitespace.
"""
command_name = command_raw.split('(', 1)[0].rstrip()
return command_na... | c6e4df2c5086ca8d7e082c5eea3607b10d6497bd | 445,350 |
def subtract(a, b):
"""Subtraction applied to two numbers
Args:
a (numeric): number to be subtracted
b (numeric): subtractor
Raises:
ValueError: Raised when inputs are not numeric
"""
try:
return a - b
except:
raise ValueError("inputs should be numeric") | 7cfa9607145fb1713309fcb2e543a3a528aa26f1 | 19,389 |
def compute_breakdown(tp, start_ts=None, end_ts=None, process_name=None):
"""For each userspace slice in the trace processor instance |tp|, computes
the self-time of that slice grouping by process name, thread name
and thread state.
Args:
tp: the trace processor instance to query.
start_ts: optional bo... | d92df5f4dc06ae4f705b7daa014915d372253cde | 457,895 |
from typing import Tuple
from typing import Union
import requests
def check_url(url: str) -> Tuple[bool, Union[str, requests.Response]]:
"""Returns information on the availability of the url
Parameters
----------
url : str
The url to test
Returns
-------
Tuple[bool, Union[str, Re... | 09ed074bd8f71288788a4265e98f23aa953a6969 | 44,599 |
import re
def file_matches_regexps(filename, patterns):
"""Does this filename match any of the regular expressions?"""
return any(re.match(pat, filename) for pat in patterns) | b64f28c1391c04de56269f32ee5e0a25cff2811a | 396,874 |
import torch
def clamp_ref(x, y, l_inf):
""" Clamps each element of x to be within l_inf of each element of y """
return torch.clamp(x - y , -l_inf, l_inf) + y | d3fd0dd46d4cf821c3faa62ff00a314ea4575304 | 182,448 |
def split_query_into_tokens(query):
"""
Splits query string into tokens for parsing by 'tokenize_query'.
Returns list of strigs
Rules:
Split on whitespace
Unless
- inside enclosing quotes -> 'user:"foo bar"'
- end of last word is a ':' -> 'user: foo'
Example:
>>>... | 6f4bee48f9f10511022eac363d1f2e9df6bdcecf | 325,194 |
def convert_name(name, to_version=False):
"""This function centralizes converting between the name of the OVA, and the
version of software it contains.
OneFS OVAs follow the naming convention of <VERSION>.ova
:param name: The thing to covert
:type name: String
:param to_version: Set to True t... | 2800c22e2af5a6ad3d537a9713c473e6d44101c6 | 690,519 |
def hex_list(items):
"""
Return a string of a python-like list string, with hex numbers.
[0, 5420, 1942512] --> '[0x0, 0x152C, 0x1DA30]'
"""
return '[{}]'.format(', '.join('0x%X' % x for x in items)) | 775166e908ae9202e330d76fc82c9c45a4388cca | 117,893 |
def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs):
"""A reply handler for commands that haven't been added to the reply list.
Returns empty strings for stdout and stderr.
"""
return '', '' | e73bd970030c4f78aebf2913b1540fc1b370d906 | 706,860 |
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
index = 0
if len(pattern) == 0:
return True
for... | 2b69f1e6e0ee730c65ba671e2c99a99fcb30f367 | 195,908 |
def seminorm_loop(x, p, display = False):
"""
Calculate for a given complex vector and some 1 <= p < inf the l_p-semi-norm
using loops and scalar arithmetic
"""
if p < 1:
raise ValueError("p must be >= 1")
# Using scalar arithmetic to calculate each elements absolute value raised to p
... | 31717d937f729e80824b7f756ce8cd75ad38b75f | 265,828 |
def min_distinct(expr):
"""
Function ``MIN(DISTINCT expr)``
"""
return min(expr).distinct() | 30a6445149daa8e2ad5113182c5c35c3e9996107 | 449,794 |
import re
def is_single_symbol(expr):
"""Returns ``True`` if the expression is a single symbol, possibly
surrounded with white-spaces
>>> is_single_symbol('hello')
True
>>> is_single_symbol('hello * world')
False
"""
expr = expr.strip()
single_symbol = re.compile("^[a-zA-Z_]+[a-... | 350c1653b28a0a4c6986023453cc9cef06df3f25 | 137,272 |
def day_to_lookup(day):
"""Turns a day into its lookup key in the full year hash"""
return day.strftime('%Y-%m-%d') | c0ccf7c0b2957843c3ef618a2685fb44472cde79 | 514,154 |
def do_sort(reverse=False):
"""
Sort a sequence. Per default it sorts ascending, if you pass it
`True` as first argument it will reverse the sorting.
*new in Jinja 1.1*
"""
def wrapped(env, context, value):
return sorted(value, reverse=reverse)
return wrapped | 2254464025c9701d402c0417174731fdaf397d48 | 437,932 |
def _parse_commit_response(commit_response_pb):
"""Extract response data from a commit response.
:type commit_response_pb: :class:`._generated.datastore_pb2.CommitResponse`
:param commit_response_pb: The protobuf response from a commit request.
:rtype: tuple
:returns': The pair of the number of in... | e23ce5ee97c9bc3f4d4cf48d93d0d4932e0c8432 | 242,661 |
def validate_pause_time(pause_time: str) -> str:
"""Validate pause time."""
if not pause_time.startswith("PT"):
raise ValueError("PauseTime should look like PT#H#M#S")
return pause_time | 82e7f9041bd5f774e8e9c088e829bded4796503e | 508,611 |
import string
import random
def generate_filename(size=10, chars=string.ascii_uppercase + string.digits, extension='png'):
"""Creates random filename
Args:
size: length of the filename part, without dot and extention
chars: character range to draw random characters from
extension: exten... | 171c635f849b262894bb09749c1f22a76133dacc | 120,974 |
from typing import List
from typing import Any
def _unique(x: List[Any]) -> List[Any]:
"""Uniquify a list, preserving order."""
return list(dict.fromkeys(x)) | 3be8ac99fba1ff2ef8e3b0c0000686697038dbff | 461,318 |
import mpmath
def pdf(x, mu=0, sigma=1):
"""
Log-normal distribution probability density function.
"""
if x <= 0:
return mpmath.mp.zero
x = mpmath.mpf(x)
lnx = mpmath.log(x)
return mpmath.npdf(lnx, mu, sigma) / x | ae9ffb6bee3deab68e5f5a19c4153cb017af2909 | 433,252 |
def _generate_scope_signature (scoped):
"""Returns the signature for the scope of a scoped Topic Maps
construct.
This function returns the signature for the scope only. No other
properties of the scoped construct are taken into account.
:param scoped: the scoped Topic Maps construct
:type scop... | a72a1a8e82f3dce32440f912f81b0e1c1d7bf893 | 247,778 |
def create_health_check(lock):
"""
Return health check function that captures whether the lock is acquired
"""
def health_check():
d = lock.is_acquired()
return d.addCallback(lambda b: (True, {"has_lock": b}))
return health_check | fc77f8c42f271fd98051f91771d99ccc8aec7a9e | 34,199 |
def get_igmp_status(cli_output):
""" takes str output from 'show ip igmp snooping | include "IGMP Snooping" n 1' command
and returns a dictionary containing enabled/disabled state of each vlan
"""
search_prefix = "IGMP Snooping information for vlan "
vlan_status={}
counter = 0
line_list ... | 150b3f1213f82f3ccc70ba922fc8e4602349e660 | 514,899 |
def linear_interpolate(a, b, v1, v2, i):
"""Linear interpolation"""
if v1 == v2:
return a
else:
return a + (b - a) * (i - v1) / (v2 - v1) | dd686797f5311ff08ef5c0f7bb3642344ce8c705 | 33,401 |
import time
def total_time(func):
"""
Calculate the running time of the function
:param func: the function need to been calculated
:return: func's result
"""
def call_fun(*args, **kwargs):
start_time = time.time()
f = func(*args, **kwargs)
end_time = time.time()
... | 30879a8364106eb759922b63ae81319ed38dda34 | 585,392 |
def comp(current_command):
"""Return comp Mnemonic of current C-Command"""
#remove the dest part of command if exists (part before =)
command_without_dest = current_command.split("=")[-1]
#remove jump part of command if exists (part after ;)
comp_command = command_without_dest.split(";")[0]
return comp_command | 1da3cf0070669a584c84050acf154a65f697686b | 177,428 |
import itertools
def groupby(iterable, keyfunc):
"""
Group iterable by keyfunc
:param iterable: iterable obj
:param keyfunc: group by keyfunc
:return: dict {<keyfunc result>: [item1, item2]}
"""
data = sorted(iterable, key=keyfunc)
return {
k: list(g)
for k, g in iterto... | 8d695e0a03256fc5042eb75cad613e62c6dea89d | 503,170 |
import hashlib
def md5(filename: str) -> str:
"""Generate the md5 hash for a file with given filename.
:param filename: Name of the file to generate the MD5 hash for.
:return: md5 hash of the file.
"""
hash = hashlib.md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.re... | c9cafcf15e9e10b802f3da7efee39f251252de22 | 412,894 |
import calendar
def DateTimeToTimestamp(value):
"""Returns an integer timestamp from a datetime.
Args:
value: The datetime to convert.
Returns:
An integer representing the number of seconds since the epoch.
"""
return int(calendar.timegm(value.timetuple())) | 01d722ddc5a1e80f00886bbc733a706b5a9f7e81 | 359,182 |
import random
def random_partitioner(stream_record):
"""Generate a random partition_key."""
random_key = str(random.randint(0, 10**12))
return random_key | 09091b57f3f0908970457910d003a155108fbd29 | 138,189 |
def red_channel(image):
"""Return the red channel."""
return image[:, :, 0] | d07be3edc46d96f3e96f7816a92834282a5f4445 | 141,732 |
import torch
def unsorted_segment_sum(data, segment_ids, num_segments):
"""
Computes the sum along segments of a tensor. Similar to
tf.unsorted_segment_sum, but only supports 1-D indices.
:param data: A tensor whose segments are to be summed.
:param segment_ids: The 1-D segment indices tensor.
... | 4777e5dfe0edd1c5918ab53b600e930a84753c3a | 68,838 |
from typing import Tuple
def _convergent(continued_fractions: Tuple[int, ...],) -> Tuple[int, int]:
"""Get the convergent for a given continued fractions sequence of integers
:param continued_fractions: Tuple representation of continued fraction
:return: reduced continued fraction representation of conve... | c5263b5046e07fb9b19f20ede2080112013bbe4f | 652,523 |
def normalise(array, nodata):
"""Sets pixels with nodata value to zero then normalises each channel to between 0 and 1"""
array[array == nodata] = 0
return (array - array.min(axis=(1, 2))[:, None, None]) / (
(array.max(axis=(1, 2)) - array.min(axis=(1, 2)))[:, None, None]) | fecae49ba376095d3636d1b4e944d1c19d79da31 | 300,240 |
def days_in_minutes(days):
"""
Returns int minutes for float DAYS.
"""
return days * 60 * 24 | 37f464879e45ea7f183a50ce5a394564b636753e | 620,503 |
def alphabet_position(letter):
"""Returns an index number based on the passed
letter's position in the alphabet"""
mapping = "abcdefghijklmnopqrstuvwxyz"
ind = mapping.index(letter)
return ind | bf9ac53878a88249c7d018ca432cb7add57940b8 | 317,299 |
import requests
import time
def post_grafana_annotation(grafana_url, grafana_api_key, tags, text):
"""
Create annotation in a grafana instance.
"""
return requests.post(
grafana_url + "/api/annotations",
json={
'tags': tags,
'text': text,
'time': int... | 0b925725384dedd73d6260e8b1099de192b4f903 | 441,142 |
def extract_ranges(dfi):
"""Extract example ranges
"""
ranges = dfi[['example_chrom', 'example_start',
'example_end', 'example_idx']].drop_duplicates()
ranges.columns = ['chrom', 'start', 'end', 'example_idx']
return ranges | 2fa01976b5f1ea8da76ea9175eeb8a036015c7e9 | 194,589 |
def format_gro_coord(resid, resname, aname, seqno, xyz):
""" Print a line in accordance with .gro file format, with six decimal points of precision
Nine decimal points of precision are necessary to get forces below 1e-3 kJ/mol/nm.
@param[in] resid The number of the residue that the atom belongs to
@pa... | ceeeeeafe4f7484fa17ee4ebd79363209c8f7391 | 708,895 |
def multiGF8( input1, input2, modP8):
"""
multiGF8 - multiply 2 number on a Galois Field defined by a polynomial.
Args:
input1: first number to multiply.
input2: second number to multiply.
modP8: polynomial defining the Galos Field.
Returns:
the multiplication result.
... | cd11d536639fc0c80ef15240b83ff5833ea6ff73 | 287,834 |
def make_message(article: dict, hashtags: str) -> str:
"""
Action: make Telegram message from API response
:param article: dictionary from API response with individual article data
:param hashtags: list of hashtags, inserted at the end of the channel message
:return: string with assembled individual... | 325708ca457f688840efe4a65046fad3e2f15d11 | 189,787 |
from typing import Any
def is_reference(key: Any) -> bool:
"""Is this key a reference to output from elsewhere in the chores.
A reference has the form ^chore(.output)? where `chore` is the name of the
node you are consuming output from and `output` is either a name or a
number to tell which part of t... | 4e68a9903c57435ff73b7f652a8d6d9efded5ca9 | 616,164 |
def captioned_button(req, symbol, text):
"""Return symbol and text or only symbol, according to user preferences."""
return symbol if req.session.get('ui.use_symbols') \
else u'%s %s' % (symbol, text) | b2f4be2fe0dac6b0d0b90ca91d00a625d674517c | 600,190 |
def class_name(obj):
"""Returns the class name of the specified object.
"""
return obj.__class__.__name__ | 83b6b4beb2277b1c6ee8e78824bff5b95fda401c | 543,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.