content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def type_id(id):
"""
Returns an OCD identifier's type ID.
"""
return id.rsplit(':', 1)[1] | 14e2d42b7f3cf2fa8b2a749e07fa0f8ab57a3aaa | 70,771 |
def parse(sentence):
"""
Removes everything but alpha characters and spaces, transforms to lowercase
:param sentence: the sentence to parse
:return: the parsed sentence
"""
# re.sub(r'([^\s\w]|_)+', '', sentence)
# return sentence.lower()#.encode('utf-8')
# re.sub("^[a-zA-Z ]*$", '', sen... | 112bfd1048e9df97fcdcf400b261c260f2d76881 | 70,772 |
from typing import Dict
from typing import Set
def build_dependants(dependencies: Dict[str, Set[str]]) -> Dict[str, Set[str]]:
"""
Given a dependencies mapping, return the reversed dependants dictionary.
"""
dependants = {name: set() for name in dependencies.keys()}
for child, parents in dependenc... | 054860b29e73980860fcd244ec50b34fdd322a09 | 70,773 |
def process_csv(csv):
"""
Normalize and select usefull columns
** return (Tuple (numpy array, numpy array, numpy array)) **
*train_features.shape : (n, 5)
*train_targets.shape : (n)
*test_features.shape : (n, 5)
With n the numbers of rows
"""
#... | bf748eedf916392f3c5889fee73a254dd3e9c038 | 70,774 |
def _parameters_exists_in_docstring(docstring: str) -> bool:
"""
Get boolean of whether Parater part exists in docstring
or not.
Parameters
----------
docstring : str
Docstring to be checked.
Returns
-------
result_bool : bool
If exists, True will be set.
"""
... | d8aa9a6851218282b700e3d37921bf17a27ba5d7 | 70,778 |
def cats_game(board):
"""Checks if the any of the values in the board list has not been used"""
if board[0][0] == 1 or board[0][1] == 2 or board[0][2] == 3 or \
board[1][0] == 4 or board[1][1] == 5 or board[1][2] == 6 or \
board[2][0] == 7 or board[2][1] == 8 or board[2][2] == 9:
... | a1b029fea65d05c6c3b26c6c2cce151ca7aa4517 | 70,779 |
def new_mdecl_wrapper_t__getitem__(self,index):
"""Provide access to declaration.
If passed a standard index, then return contained decl.
Else call the getitem method of the contained decls.
"""
if isinstance(index, (int, slice)):
return self.declarations[index]
else:
return self.__g... | 134b22dcc18362d4564ea3895492baa51e9d6405 | 70,784 |
def get_batch_inds(batch_size, idx, N):
"""
Generates an array of indices of length N
:param batch_size: the size of training batches
:param idx: data to split into batches
:param N: Maximum size
:return batchInds: list of arrays of data of length batch_size
"""
batchInds = []
idx0 =... | 780ec20e98ec30141eaace50191983d610482545 | 70,790 |
def format_cdr_properties(
geometries,
densities,
id_col_name="tower_id",
density_col_name="density"
):
"""
Converts the format of additional CDR properties from being in a DataFrame
to being in a dictionary indexed by the tower node id
Args:
geometries (dict): o... | 23c92dacd6eb8c329167429946c2d6550027e08c | 70,791 |
def simplify_edge_attribute_name(G, key, name_list, simple_name):
"""
Simplify an arbitrary list of name values for a given key into one.
Parameters
----------
G : networkx Graph/DiGraph/MultiGraph/MultiDiGraph/...
Graph where we want to simplify an attribute.
key : str
Name of ... | 0e5a95c7c39d300eb51434eb66148331c4037a66 | 70,792 |
def myfuncPrimeSieve(n):
"""
This function generates and returns prime numbers from 2 up to n
via the Sieve of Eratosthenes algorithm.
Example of usage:
getAns = myfuncPrimeSieve( 20 )
print(getAns)
"""
thelist = list(range(3, n, 2)) #generates odd numbers starting from 3
thepri... | abef8a3d3f3c921840caa17bdf9b900cc230a617 | 70,793 |
def create_regular_grid(area_defn, tile_size, stride=None):
"""
Defines a regular grid of (overlapping) tiles.
:param area_defn: dictionary, defines one or multiple rectangularly-shaped geographic regions from which
DSM patches will be sampled. The dictionary is composed o... | 9ca35a48b882243ba50e68c2bf0c9e50099fb2ef | 70,796 |
import torch
def sum_hessian(loss, hidden):
"""Given scalar tensor 'loss' and [b, d] batch of hidden activations 'hidden', computes [d, d] size sum of hessians
for all entries in the batch.
We make use of the fact that grad^2(f) = grad(grad(f)) and that sum of grads = grad of sum. So, sum(grad^2(f)) is
... | 3e8ec30561568652cf403ab10ec2d353708370c2 | 70,798 |
def standard_codec_name(name: str) -> str:
"""
Map a codec name to the preferred standardized version.
The preferred names were taken from this list published by IANA:
U{http://www.iana.org/assignments/character-sets/character-sets.xhtml}
@param name:
Text encoding name, in lower case.
... | e9f30c9cb9da065f300900923e9b9ce5bac255e9 | 70,801 |
def price_change_color_red_green(val: str) -> str:
"""Add color tags to the price change cell
Parameters
----------
val : str
Price change cell
Returns
-------
str
Price change cell with color tags
"""
val_float = float(val.split(" ")[0])
if val_float > 0:
... | dedfaff32d88141af69d70e636c84191ebf24707 | 70,803 |
def minimize_attachment(attachment, doc_id):
"""
Takes an attachment obtained from a document in an experiment object and
strips it down to a subset of desired fields. The document @id, given by
doc_id, is prepended to the attachment href.
"""
minimized_attachment = {}
for key in ('md5... | 7e6b8dfbf53f840e6b46a2aa8acb1b7e1017fa46 | 70,804 |
def is_container(obj):
"""Check if `object` is a list or a tuple.
Args:
obj:
Returns:
True if it is a *container*, otherwise False
"""
return isinstance(obj, (list, tuple)) | 09db5b1d136b6db1969097d19f7d63d1750971ab | 70,805 |
import re
def is_uid(string):
"""Return true if string is a valid DHIS2 Unique Identifier (UID)"""
return re.compile('^[A-Za-z][A-Za-z0-9]{10}$').match(string) | 9e1c1d8dc2697a8535018b15662a69edfdbc8eaf | 70,821 |
def split_list_with_len(lst: list, length: int):
"""
return a list of sublists with len == length (except the last one)
"""
return [lst[i:i + length] for i in range(0, len(lst), length)] | 1133a7948e0ff37e3c1652ddeb266a9e8eb94f79 | 70,822 |
import json
def read_json(json_file="json_file_not_specified.json"):
"""
Reads a json file and it returns its object representation, no extra checks
are performed on the file so, in case anything happens, the exception will
reach the caller
:param json_file: path to the file in json format to read... | a75a97bac175ff05d648f9c32cd066529be6906c | 70,828 |
from typing import List
import re
def board_is_nrf(content: List[str]) -> bool:
"""Check if board is nRF based.
Args:
content: DT file content as list of lines.
Returns:
True if board is nRF based, False otherwise.
"""
for line in content:
m = re.match(r'^#include\s+(?:"... | c8b83127d142c5512b4e8129beecd6410f6bbce3 | 70,829 |
def get_jvm_class(cl):
"""Builds JVM class name from Python class
"""
return 'org.apache.{}.{}'.format(cl.__module__[2:], cl.__name__) | 7569f5be6768f87a347c7b84fb358f3e7fd9ef38 | 70,838 |
def client(app, db):
"""Return a Web client, used for testing, bound to a DB session."""
return app.test_client() | da1265c0a693316e9892a098be1ebb1043860902 | 70,839 |
def index(item, seq):
"""Helper function that returns -1 for non-found index value of a seq"""
if item in seq:
return seq.index(item)
else:
return -1 | 85b50e1e66c050f5072ce834672b130c7a7f0a46 | 70,840 |
from typing import Dict
import requests
def get_json(url: str) -> Dict:
"""Get JSON from remote URL.
"""
response = requests.get(url)
return response.json() | 7a62fd2417a1b80979dc8eccebce41dc4d9cc2e1 | 70,843 |
def get_span(tag):
"""Returns a (start, end) extent for the given extent tag."""
return tag.attrib['start'], tag.attrib['end'] | 06f16e78b60b98065012cf3fdc19bfccf3625fb8 | 70,847 |
import getpass
def host_username() -> str:
"""Get the current username from the OS."""
return getpass.getuser() | cc2eac760d30f61832349568eec27e339602f093 | 70,849 |
def borehole_thermal_resistance(pipe, m_flow_borehole, cp_f):
"""
Evaluate the effective borehole thermal resistance.
Parameters
----------
pipe : pipe object
Model for pipes inside the borehole.
m_flow_borehole : float
Fluid mass flow rate (in kg/s) into the borehole.
cp_f ... | 36d3c0c484d892843ccd56750c0d7fa95468abe0 | 70,852 |
import re
def getidtype(identifier):
""" try and determine the type of identifier given """
# is the string an inchikey?
m = re.search('^[A-Z]{14}-[A-Z]{10}-[A-Z]$', identifier)
if m:
return "inchikey"
# is the string an inchi?
n = re.search('^InChI=1S?/', identifier)
if n:
... | f853d512029b0034e9657a7260b233f3b9a9303e | 70,855 |
def compute_metrics(outputs, targets, metrics, ids=None):
"""
Computes the evaluation metrics for the given list of output and target images.
:param outputs: list of output images
:param targets: list of gold standard images
:param metrics: dictionary containing each metric as {metric_name: metric_... | 348b26b71e36701cbd319a18db5bc2d1597beee7 | 70,856 |
def get_file_contents_as_string(filepath):
"""
Read a file and returns its contents as one big string.
"""
ret = []
with open(filepath, 'r') as infile:
for line in infile.readlines():
ret.append(line)
ret = "".join(ret)
return ret | 9370958576a10cb4c2cd0efd98045bd2d7b156bc | 70,857 |
def mkpad(items):
"""
Find the length of the longest element of a list. Return that value + two.
"""
pad = 0
stritems = [str(e) for e in items] # cast list to strings
for e in stritems:
index = stritems.index(e)
if len(stritems[index]) > pad:
pad = len(stritems[index... | 8c9d69431116827d2bd0eaac72d1c54a3997c890 | 70,858 |
def DFToXY(dataframe):
"""
Divide a dataframe producted by BuildDataFrames methode between features
and labels
Parameters
----------
dataframe : pandas DataFrame
dataframe with features and labels
Returns
-------
x : pandas DataFrame
dataframe of features.
y : p... | f74680438f2e31c1ad581b3ae31fd713cbfce0aa | 70,861 |
def get_assignment_detail(assignments):
"""
Iterate over assignments detail from response.
:param assignments: assignments detail from response.
:return: list of assignment elements.
"""
return [{
'ID': assignment.get('id', ''),
'FirstName': assignment.get('firstName', ''),
... | a0e61908386c3972cae84912d5eb3c181b6b7ed5 | 70,862 |
import hashlib
def make_password(service_provider_id, service_provider_password,
timestamp):
"""
Build a time-sensitive password for a request.
"""
return hashlib.md5(
service_provider_id +
service_provider_password +
timestamp).hexdigest() | eb68df2bdc5aac51f84341df085bf9320057eebb | 70,864 |
def PyMapping_Items(space, w_obj):
"""On success, return a list of the items in object o, where each item is a tuple
containing a key-value pair. On failure, return NULL. This is equivalent to
the Python expression o.items()."""
return space.call_function(space.w_list,
sp... | dec1501c5a1632e49bb7cddafa6a8cbe4802b3d9 | 70,871 |
def is_present(marks, text):
"""
return True, if all marks present in given text
"""
return all([mark in text for mark in marks]) | 0ea198520b1e46f1c9b26a9533e0785140348776 | 70,873 |
import csv
def read_csv(f, Model):
"""
Given a CSV file with a header, read rows through `Model` function.
Returns generator function.
"""
reader = csv.reader(f, dialect="excel")
next(reader, None) # skip the header row
return (Model(row) for row in reader) | e7b247947aa882ba5feb317898d4629b9a420752 | 70,875 |
def is_2d(fs):
"""Tests wether a function space is 2D or 3D"""
return fs.mesh().geometric_dimension() == 2 | 24dadb7ff6f6810a0ee9cfbc496bf41050270425 | 70,879 |
def indent_lines(s, indent=4, skip=0):
"""Indents the lines in the given string.
Args:
s: the string
indent (4): the number of spaces to indent
skip (0): the number of lines to skip before indenting
Returns:
the indented string
"""
lines = s.split("\n")
skipped... | f21d1cbff97c1d45a5ab46e6521a403539225440 | 70,880 |
import numbers
def discrete_signal(signal, step_size):
"""Discretize signal
Parameters
----------
signal: pd.Series
Signals for betting size ranged [-1, 1]
step_size: float
Discrete size
Returns
-------
pd.Series
"""
if isinstance(signal, numbers.Numbe... | 183af7cf6ca30daaebb44b0d41c860b001109136 | 70,887 |
def compute_strati_ratio(T, S, alpha, beta, grid):
"""
Compute the stratification ratio
R = (alpha * dT/dz + beta * dS/dz) / (alpha * dT/dz - beta * dS/dz)
"""
dT_dz = -grid.derivative(
T, axis="Z", boundary="extend"
) # - sign to take z in the right direction
dS_dz = -grid.derivat... | ead5554c467a9dd876aa15914f806993c888d06f | 70,889 |
def readfile(openedfile):
"""Read the contents of a file."""
openedfile.seek(0)
return str(openedfile.read()) | c8be0033794c5316381045a492c666fb90fdc378 | 70,891 |
import itertools
def Flatten(x: list) -> list:
"""Flatten a list."""
return list(itertools.chain.from_iterable(x)) | e7504a7f85eed2b81609c7fbfd46c45555ce7118 | 70,892 |
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors X and Y."""
return sum(x * y for x, y in zip(X, Y)) | 8c2f515c63cae018e4065c2913b610045c9e0f00 | 70,898 |
def seconds_to_MMSS_colon_notation(sec):
"""Convert integer seconds into MM:SS colon format. If sec=121, then return '02:01'. """
assert isinstance(sec, int) and sec <= 99*60 + 59 and sec >= 0
return '%02d:%02d' % (int(sec/60.0), sec % 60) | 6716dea4c3c9885fc056bf61d2d3366f7e13c7d3 | 70,906 |
def parse_fasta(fh):
"""Parses a RefSeq fasta file.
Fasta headers are expected to be like:
>NR_165790.1 Tardibacter chloracetimidivorans strain JJ-A5 16S ribosomal RNA, partial sequence
Args:
fh: filehandle to the fasta file
Returns:
A fasta_dict like {'name': ['seq1', 'seq2'], etc. }
"""
fasta_... | 22340a0c526085ef3280d460f654d0914f08b7b2 | 70,907 |
def max_available_power_rule(mod, prj, tmp):
"""
**Constraint Name**: GenVarStorHyb_Max_Available_Power_Constraint
**Enforced Over**: GEN_VAR_STOR_HYB_OPR_TMPS
Power provision plus upward services cannot exceed available power, which
is equal to the available capacity multiplied by the capacity fac... | 17f6c9ff570b15bafc49272599cfbe5832b8e62d | 70,910 |
def reward(total_reward, percentage):
"""
Reward for a problem with total_reward done to percentage.
Since the first a few test cases are generally very easy, a linear
approach will be unfair. Thus, the reward is given in 20:80 ratio.
The first 50% gives 20% of the reward, and the last 50% gives 8... | 957b0248d44c8033ceaf852e2780224f3fb379f9 | 70,918 |
def load_dat(filename: str) -> list:
"""
Loads the contents of the DAT data file into a list with each line of the file
into an element of the list.
"""
with open(file = f'{filename}.dat', mode = u'r') as dat_file:
return dat_file.read().split(u'\n') | 25f13fedb8bb0d2927e794b20691c648b8502bc5 | 70,920 |
def bps_mbps(val: float) -> float:
"""
Converts bits per second (bps) into megabits per second (mbps).
Args:
val (float): The value in bits per second to convert.
Returns:
float: Returns val in megabits per second.
Examples:
>>> bps_mbps(1000000)
1.0
>>> b... | 13520e00c393a647ccdc2ba0021445970e169fd2 | 70,921 |
def check_consistency_names_grounding_dict(grounding_dict, names_map):
"""Check that a grounding dict and names map have consistent names
"""
groundings = {grounding for grounding_map in grounding_dict.values()
for grounding in grounding_map.values()
if grounding != 'ungr... | a406225485d4d121da86eada198a913724d22bec | 70,923 |
def checkNoneOption(value):
"""
Check if a given option has been set to the string 'None' and return
None if so. Otherwise return the value unchanged
"""
if value is None:
return value
if value == 'None':
return None
if isinstance(value, list):
if len(value) == 1 and ... | 5ba1c9da12ecdb3f6d9562bac4017934c66393a3 | 70,925 |
import re
def get_jinja_variables(text):
"""Gets jinja variables
Args:
line (string): text to get jinja variables
Returns:
[list]: returns list of jinja variables
"""
variables = []
regex_pattern = regex_pattern = re.compile(
"(\\{{)((.|\n)*?)(\\}})", re.MULTILINE)
... | 2a68851ff318a2de8072466e14305caf64d7d65b | 70,928 |
def true_s2l(value: float) -> float:
"""Convert SRGB gamma corrected component to linear"""
if value <= 0.04045:
return value / 12.92
return ((value + 0.055) / 1.055) ** 2.4 | 0e0a4123589397a0ee246b1bc12ccaaf550aaea4 | 70,931 |
def freeze(obj):
"""Freeze a state (dict), for memoizing."""
if isinstance(obj, dict):
return frozenset({k: freeze(v) for k, v in obj.items()}.items())
if isinstance(obj, list):
return tuple([freeze(v) for v in obj])
return obj | 0cd224d292dbf2f5835b4154d894755ca652be13 | 70,933 |
def get_item(dictionary, index):
"""Returns a value from a dictionary"""
return dictionary.get(index) | 5134ab38a3d33f995a9f6358aa1949865c0c820c | 70,935 |
def dist(p1, p2):
"""Distance between p1 and p2"""
return abs(p2 - p1) | 6b59fd1354b1f01cfe67bf73ca1d9db3aa7689af | 70,939 |
import torch
def _convert_boxes_to_roi_format(boxes):
"""
Convert rois into the torchvision format.
:param boxes: The roi boxes as a native tensor[B, K, 4].
:return: The roi boxes in the format that roi pooling and roi align in torchvision require. Native tensor[B*K, 5].
"""
concat_boxes = bo... | 72ce30f5d7a92b3a09eb692c88f610da26b1edeb | 70,941 |
async def get(spfy, session, url):
"""
Makes a request to the Spotify API with the appropriate
OAuth headers.
:return: the json object for the response
"""
headers = {
**spfy._auth_headers(),
"Content-type": "application/json"
}
async with session.get(url, headers=heade... | e56486f0a85ada9c090439bd7a30503e47d33488 | 70,942 |
def _get_favorites(request):
"""
Gets the favorite articles' ids from request.user
Input: request
@return: <list> List of article ids
"""
# rows = [{'id': 2}, {'id': 4} ... ] (A list of article ids)
rows = request.user.favorite_article.values('id')
# favorites = [2, 4, ...] using list c... | 42a8025aeb0c5b2847344c21c66a17f3c386ab70 | 70,949 |
def read_igor_J_gene_parameters(params_file_name):
"""Load raw genJ from file.
genJ is a list of genomic J information. Each element is a list of three
elements. The first is the name of the J allele, the second is the genomic
sequence trimmed to the CDR3 region for productive sequences, and the last
... | b853081955db529c8f7b7db9491f7631902deb23 | 70,951 |
def import_class(model_name):
"""
Imports a predefined detection class by class name.
Args:
model_name: str
Name of the detection model class (example: "MmdetDetectionModel")
Returns:
class_: class with given path
"""
module = __import__("sahi.model", fromlist=[model... | cd4a8d4fd29e8977e3800d64487dabd0158363d5 | 70,952 |
def _join_codes(fg, bg):
"""Join `fg` and `bg` with ; and surround with correct esc sequence."""
colors = ';'.join(filter(lambda c: len(c) > 0, (fg, bg)))
if colors:
return '\x1b[' + colors + 'm'
return '' | 88e8bc886f100113dcf2221b5827f0acf5c76845 | 70,954 |
import math
def identityProbability(gs: int, mr: float = 1e-08) -> float:
"""Return the probabilty for a sequence
to not change over n generations of evolution.
**Keyword arguments:**
gs -- number of generations
mr -- mutation rate (default is 1e-08)
"""
return math.pow(1-mr, gs) | c8be5ef9c459e709482b69c0f4d7ace64364b639 | 70,958 |
def RegionPack(region_id, center=None, verts=None):
""" This function packs a region_id and the constructor overrides for that Region
into a tuple. Only center or verts can be overridden currently and only one of
those per Region. The resulting tuple looks like:
(region_id, {region_construct... | cdf023f41b877c1ab213552a3bc8c7a38bc1a7ec | 70,959 |
from typing import Callable
def pushcall(call: Callable, from_other_thread: bool = False) -> None:
"""pushcall(call: Callable, from_other_thread: bool = False) -> None
Pushes a call onto the event loop to be run during the next cycle.
Category: General Utility Functions
This can be handy for calls ... | b56b8d63bd265010e5daf94ee46e59bd194c13bf | 70,961 |
def splitIntoSingleMutations(mutation):
"""
split multiple mutation into single mutation list, e.g. 'A:N25R/A:N181D' -> ['A:N25R', 'A:N181D']
"""
single_mutations = []
start = 0
for i in range( len(mutation) ):
if mutation[i] == '/':
single_mutations.append(mutation[start:i])
... | 33edaa51b99b50d7b8b74c7f55157a4389db4a2f | 70,969 |
import re
def freeze_vars(variables, pattern):
"""Removes backbone+fpn variables from the input.
Args:
variables: all the variables in training
pattern: a reg experession such as ".*(efficientnet|fpn_cells).*".
Returns:
var_list: a list containing variables for training
"""
if pattern:
var... | 23de336ea09e2b054930c575f5c99af0fbcd82b6 | 70,970 |
from typing import AsyncGenerator
from typing import Optional
from typing import Callable
from typing import List
async def async_list(
gen: AsyncGenerator,
filter: Optional[Callable] = None) -> List:
"""Turn an async generator into a here and now list, with optional
filter."""
results = [... | f9b984fd27fc33fa907738c8cd9dfd7c2d86c05c | 70,978 |
def scale_census_variables(census):
"""
Function to scale Men, Women, Employed and Citizen
variables in census by TotalPop to get a percentage.
Input: dataframe of census data.
Output: dataframe of census data scaled to population (%).
"""
census.Men = 100*census.Men/census.TotalPop
cens... | 39dae100f2121732fe5f0d91f47a598dbfef092c | 70,980 |
def make_tag_dict(tag_list):
"""Returns a dictionary of existing tags.
Args:
tag_list (list): a list of tag dicts.
Returns:
dict: A dictionary where tag names are keys and tag values are values.
"""
return {i["Key"]: i["Value"] for i in tag_list} | 3432db43ac28c19d3abb0b8de03e0ad229a761a0 | 70,981 |
def create_translation_fieldname(translation):
"""
Description:
Generates a unique fieldname based on a given Translation instance
Args:
translation (Translation): Translation instance from our Translation model
Returns:
str: The generated field name
"""
field = translati... | de567834d710469c5b05f7427b8c6cc678f463ee | 70,982 |
def shift_within_range(value, min, max, reverse=False):
"""Shift numeric value within range."""
values = range(min, max + 1)
if reverse:
index = values.index(value) - 1
else:
index = values.index(value) + 1
return values[index % len(values)] | a8ffb3abfa7fb598e28359b5e38ac56859e3b551 | 70,983 |
def default_error_handler(exc: Exception) -> str:
"""Default string formatting exception handler."""
return str(exc) | 89df06d69055fdf9704ff573f141aba40dc39d58 | 70,984 |
def tcp_encode(string: str) -> bytes:
"""Encode string to TCP message."""
return string.encode() + b'\r\n' | 66715f6547b883394fbfea80edfde6b48b060825 | 70,989 |
def buildNameCountry(cfile):
"""
Take an open .csv file with format country, username and create a dictionary
indexed by username with value country
"""
retDict = {}
for [country, username] in cfile:
retDict[username] = country
return retDict | dbaf6b343b896c405aeb36b958cd2cdcad64c712 | 70,990 |
def number_split(num):
"""
12345678 => 12,345,678
:param num: the number needs to be formulated
:return: the string converted from formulated number
"""
return '{:,}'.format(int(num)) | a7cc03733d6ef9ae031d4fa8f2094c04260bd94c | 70,991 |
def param_undefined_info(param_name, default_value):
"""
Returns info warning an undefined parameter.
"""
return "Parameter warning: the hyper-parameter " + \
"'{}' is not specified, will use default value '{}'" \
.format(param_name, default_value) | 15334d816ad91f4a2b3a5a8c40cb4db8895d62ce | 70,993 |
def greater_than(ds, value):
"""Return a boolean array with True where elements > value
Parameters:
-----------
ds: xarray Dataset
The array to mask
value: float, xarray Dataset
The value(s) to use to mask ds
"""
return ds > value | 9d634bb70fb5f4f6b6bdf13d56f9279e56e337ae | 70,997 |
def has_next(seq, index):
"""
Returns true if there is at least one more item after the current
index in the sequence
"""
next_index = index + 1
return len(seq) > next_index | 607efe35930efaa2d37f0148629c65ec0d6f4fce | 71,000 |
def mm2m(da):
"""Convert mm to m.
Args:
da (xarray.DataArray): Data in mm.
Returns:
xarray.DataArray: Data in m.
"""
return da / 1000.0 | c7e0c8a9e0c5194a38f7e5e58e4fdb07355b3b23 | 71,009 |
def binary_printable(str):
"""Return a "hex" representation of of the bytes in STR."""
hex_dict = {"\x00":"00", "\x01":"01", "\x02":"02", "\x03":"03",
"\x04":"04", "\x05":"05", "\x06":"06", "\x07":"07",
"\x08":"08", "\x09":"09", "\x0a":"0a", "\x0b":"0b",
"\x0c":"0c", "\x0d":"0d", "\x0e":"0e", "\x0f... | e90727463e91d15974c1e0ca6064a9d5f0cd15c7 | 71,011 |
def reverse_dotted_decimals(ipaddress):
"""
Reverse the order of the decimals in the specified IP-address. E.g.
"192.168.10" would become "10.168.192"
"""
return '.'.join(ipaddress.split('.')[::-1]) | b86779437e92aa1c85a83ea9c6f9906e1a22e351 | 71,013 |
def get_Zb(k, l):
"""Return Z for k-l length suffix."""
assert 0 < k and 0 <= l <= k
return pow(2, k-l) - 1*(l<k) | e90d4cc4fb98f9aa2580e11b93cef3624465e88a | 71,016 |
import csv
def input_performances(name):
"""
Generates from a .csv file the list of actions and the performance dictionary.
:param name: Name of the .csv file which must contain on the first line the names
of the actions, on the second line the names of the criteria and on the
following l... | 366afa5736d700f717706db86037e2f400b70442 | 71,018 |
def get_selected_text(self):
"""
Return selected text from view.
Parameters
----------
self : class view
Returns
----------
str
Selected text
"""
sel_text = self.view.sel()
sel_text = self.view.substr(sel_text[0])
return sel_text | 4b4ea7c7d90ffc42baa9655a3f888a1795c990e9 | 71,023 |
def apply_filtering(tag, text):
"""Alter certain metadata elements according to the specified rules."""
if tag == 'PubNumber':
return text + '.pdf'
elif tag == 'Keyword':
return text.title()
elif tag == 'DegreeCode':
if text == "Ph.D.":
return "Dissertation"
else... | 28a4fb49f4d1c83d27c8d3459e4415a9c1b773a3 | 71,026 |
def card_to_flds(card):
"""Create fields string fro the given card."""
parts = [card.word, card.info, card.transcription,
'[sound:%s]' % card.sound if card.sound else '']
return '\x1f'.join(parts) | 0b78487bcb230cb9aa20720683a56dc57116ac10 | 71,035 |
import math
def calc_norm(k):
"""
Calculate the Euclidean norm on an n-dimensional Euclidean space Rn.
"""
c = 0
for i in range(len(k)):
c += k[i] ** 2
x = math.sqrt(c)
return x | 006a3b863c8f4909dfa6fe47cdf0eda33958e051 | 71,036 |
import random
def random_ip(pattern=None):
"""
Takes a pattern as a string in the format of #.#.#.# where a # is an
integer, and a can be substituded with an * to produce a random octet.
pattern = 127.0.0.* would return a random string between 127.0.0.1 and
127.0.0.254
"""
if pattern is No... | 8246f38df9ce2c6ed71c1c088e8f27f888c33f4d | 71,042 |
def invert_brackets(lhs: str) -> str:
"""
Helper function to swap brackets and parentheses in a string
"""
res = ""
pairs = ["()", "[]", "{}", "<>", "/\\"]
open_close = {x[0]: x[1] for x in pairs}
close_open = {x[1]: x[0] for x in pairs}
for char in lhs:
if char in open_close:
... | a264b24c083e3fec641d9dbb03dd2c8f743b76aa | 71,045 |
import random
def recommend_random(query, movies, k=10):
"""
Recommends a list of k random movie ids
"""
movies = movies.drop(index=query.keys())
list_ids = random.choices(
movies.index, weights=None, cum_weights=None, k=k)
return list_ids | 96874c0177cb397c0725b1c837143536451a603e | 71,050 |
def get_factors(x):
""" This function takes a number and returns its factors"""
listf = []
#print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
#print(i)
listf.append(i)
return listf | 3156c5a48ccfdb4491f4043d26541d965e60c577 | 71,052 |
def get_exp_label(val) -> str:
"""
:param val: numeric label to format
:return: label formatted in scientific notation
Format a label in scientific notation, using Latex math font.
For example, 10000 -> 10^4;
"""
# Get the power of 10
exp_val = 0
remaining_val = int(val)
wh... | 189d36550feeb7389e9c60f8a512d96f09703cf8 | 71,054 |
def name_splitter(name: str):
"""Extract gig name & start time from string
Args:
name (str): name item from ParisCat GetStack
Returns:
str, str: title, start_time
"""
# Initialise Reponse Variables
title = None
start_time = None
# Generally title & start time ... | 07ab1e30ed1dce61c4188766578327f7ff940828 | 71,056 |
def get_type_from_path(path):
"""Get the "file type" from a path.
This is just the last bit of text following the last ".", by definition.
"""
return path.split('.')[-1] | ecf59c13bc5bd5dc3a1749de0ff3ff01f40ad037 | 71,064 |
import torch
def masked_accuracy(scores,targets,tgt_pad_index = 0):
"""
Calculate accuracy for a given scores and targets, ignoring it for padding_index
@params scores(Tensor): output scores - shape(batch, tgt_seq_len-1, tgt_vocab_size)
@params target(Tensor): gold target - shape(batch,tgt_seq_len) - ... | 8975b4c0b6e7dfed7a5aefae38bb81e9acc4eb6c | 71,065 |
def process_STATS_ASCII_data_line(line,nchan):
"""This processes one line of a STATS data file
@param line : string
One line from an ASCII STATS data file
@param nchan : number of signal channels in the file
@return: list of lists
Lists of the means, rms, kurtoses and skews for the subchannels
... | ee3f46ac18efc5ff66f97ba14900437e44d90697 | 71,070 |
def ord_to_str(ord_list):
"""
Convert list of character orders to string
:param ord_list: list of character orders
:type ord_list: int or list[int]
:return: corresponding string
:rtype: str
"""
if isinstance(ord_list, int):
ord_list = [ord_list]
s = ''
for o in ord_list:... | 3141f1130d7f105e93e1cce14d4e31a585d23c40 | 71,071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.